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,
'iTransformer': iTransformer,
'iInformer': iInformer,
'iReformer': iReformer,
'iFlowformer': iFlowformer,
|
class Exp_Basic(object):
def __init__(self, args):
self.args = args
self.model_dict = {
'Transformer': Transformer,
'Informer': Informer,
'Reformer': Reformer,
'Flowformer': Flowformer,
'Flashformer': Flashformer,
'iTransformer': iTransformer,
'iInformer': iInformer,
'iReformer': iReformer,
'iFlowformer': iFlowformer, | '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 = timesteps.float()[:, None] * emb[None, :]
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
if embedding_dim % 2 == 1: # zero pad
emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
return emb
def nonlinearity(x):
# swish
return x * torch.sigmoid(x)
def Normalize(in_channels, num_groups=32):
return torch.nn.BatchNorm2d(num_features=in_channels)
class Upsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
self.conv = torch.nn.Conv2d(
in_channels, in_channels, kernel_size=3, stride=1, padding=1
)
def forward(self, x):
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
if self.with_conv:
x = self.conv(x)
return x
class Downsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
# no asymmetric padding in torch conv, must do it ourselves
self.conv = torch.nn.Conv2d(
in_channels, in_channels, kernel_size=3, stride=2, padding=0
)
def forward(self, x):
if self.with_conv:
pad = (0, 1, 0, 1)
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
x = self.conv(x)
else:
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
return x
class ResnetBlock(nn.Module):
def __init__(
self,
*,
in_channels,
out_channels=None,
conv_shortcut=False,
dropout,
temb_channels=512,
):
super().__init__()
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels
self.out_channels = out_channels
self.use_conv_shortcut = conv_shortcut
self.norm1 = Normalize(in_channels)
self.conv1 = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=3, stride=1, padding=1
)
if temb_channels > 0:
self.temb_proj = torch.nn.Linear(temb_channels, out_channels)
self.norm2 = Normalize(out_channels)
self.dropout = torch.nn.Dropout(dropout)
self.conv2 = torch.nn.Conv2d(
out_channels, out_channels, kernel_size=3, stride=1, padding=1
)
if self.in_channels != self.out_channels:
if self.use_conv_shortcut:
self.conv_shortcut = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=3, stride=1, padding=1
)
else:
self.nin_shortcut = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=1, stride=1, padding=0
)
def forward(self, x, temb):
h = x
h = self.norm1(h)
h = nonlinearity(h)
h = self.conv1(h)
if temb is not None:
h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None]
h = self.norm2(h)
h = nonlinearity(h)
h = self.dropout(h)
h = self.conv2(h)
if self.in_channels != self.out_channels:
if self.use_conv_shortcut:
x = self.conv_shortcut(x)
else:
x = self.nin_shortcut(x)
return x + h
| # 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
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 = timesteps.float()[:, None] * emb[None, :]
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
if embedding_dim % 2 == 1: # zero pad
emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
return emb
def nonlinearity(x):
# swish
return x * torch.sigmoid(x)
def Normalize(in_channels, num_groups=32):
return torch.nn.BatchNorm2d(num_features=in_channels)
class Upsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
self.conv = torch.nn.Conv2d(
in_channels, in_channels, kernel_size=3, stride=1, padding=1
)
def forward(self, x):
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
if self.with_conv:
x = self.conv(x)
return x
class Downsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
# no asymmetric padding in torch conv, must do it ourselves
self.conv = torch.nn.Conv2d(
in_channels, in_channels, kernel_size=3, stride=2, padding=0
)
def forward(self, x):
if self.with_conv:
pad = (0, 1, 0, 1)
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
x = self.conv(x)
else:
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
return x
class ResnetBlock(nn.Module):
def __init__(
self,
*,
in_channels,
out_channels=None,
conv_shortcut=False,
dropout,
temb_channels=512,
):
super().__init__()
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels
self.out_channels = out_channels
self.use_conv_shortcut = conv_shortcut
self.norm1 = Normalize(in_channels)
self.conv1 = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=3, stride=1, padding=1
)
if temb_channels > 0:
self.temb_proj = torch.nn.Linear(temb_channels, out_channels)
self.norm2 = Normalize(out_channels)
self.dropout = torch.nn.Dropout(dropout)
self.conv2 = torch.nn.Conv2d(
out_channels, out_channels, kernel_size=3, stride=1, padding=1
)
if self.in_channels != self.out_channels:
if self.use_conv_shortcut:
self.conv_shortcut = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=3, stride=1, padding=1
)
else:
self.nin_shortcut = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=1, stride=1, padding=0
)
def forward(self, x, temb):
h = x
h = self.norm1(h)
h = nonlinearity(h)
h = self.conv1(h)
if temb is not None:
h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None]
h = self.norm2(h)
h = nonlinearity(h)
h = self.dropout(h)
h = self.conv2(h)
if self.in_channels != self.out_channels:
if self.use_conv_shortcut:
x = self.conv_shortcut(x)
else:
x = self.nin_shortcut(x)
return x + h
| 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_collate_batch
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from llmshearing.datasets.streaming_dataset import (
TextDynamicStreamingDataset, TextStreamingDataset)
import torch
import transformers | 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): Configuration dictionary.
device_batch_size (int): Batch size for one single device.
dynamic (bool, optional): Whether to use dynamic streaming dataset to load data from each
domain dynamically. Defaults to False.
set_names (str, optional): Name of the dataset. Defaults to None.
proportion (List[float], optional): Initial proportion of each domain in the dataset. Defaults to None.
Returns:
DataLoader: A PyTorch DataLoader object.
"""
if dynamic:
dataset = TextDynamicStreamingDataset(local=cfg.dataset.local,
max_seq_len=cfg.dataset.max_seq_len,
batch_size=device_batch_size,
shuffle=cfg.dataset.get(
'shuffle', False),
shuffle_seed=cfg.dataset.get(
'shuffle_seed', 9176),
num_canonical_nodes=cfg.dataset.get(
'num_canonical_nodes', 128),
proportion=proportion,
set_names=set_names,
is_uint16=cfg.dataset.get("is_uint16", False))
else:
| """ 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): Configuration dictionary.
device_batch_size (int): Batch size for one single device.
dynamic (bool, optional): Whether to use dynamic streaming dataset to load data from each
domain dynamically. Defaults to False.
set_names (str, optional): Name of the dataset. Defaults to None.
proportion (List[float], optional): Initial proportion of each domain in the dataset. Defaults to None.
Returns:
DataLoader: A PyTorch DataLoader object.
"""
if dynamic:
dataset = TextDynamicStreamingDataset(local=cfg.dataset.local,
max_seq_len=cfg.dataset.max_seq_len,
batch_size=device_batch_size,
shuffle=cfg.dataset.get(
'shuffle', False),
shuffle_seed=cfg.dataset.get(
'shuffle_seed', 9176),
num_canonical_nodes=cfg.dataset.get(
'num_canonical_nodes', 128),
proportion=proportion,
set_names=set_names,
is_uint16=cfg.dataset.get("is_uint16", False))
else: | 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_from_alpha, accumulate_along_rays
from nerfacc.intersection import ray_aabb_intersect | 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.config.get('modulate', False)
if self.modulate:
self.mod_start_steps = self.config.mod_start_steps
self.reach_max_steps = self.config.reach_max_steps
self.max_inv_s = self.config.max_inv_s
@property
def inv_s(self):
val = torch.exp(self.variance * 10.0)
if self.modulate and self.do_mod:
val = val.clamp_max(self.mod_val)
return val
def forward(self, x):
return torch.ones([len(x), 1], device=self.variance.device) * self.inv_s
def update_step(self, epoch, global_step):
if self.modulate:
self.do_mod = global_step > self.mod_start_steps
if not self.do_mod:
self.prev_inv_s = self.inv_s.item()
else:
self.mod_val = min((global_step / self.reach_max_steps) * (self.max_inv_s - self.prev_inv_s) + self.prev_inv_s, self.max_inv_s)
@models.register('neus')
class NeuSModel(BaseModel):
def setup(self):
self.geometry = models.make(self.config.geometry.name, self.config.geometry)
self.texture = models.make(self.config.texture.name, self.config.texture)
self.geometry.contraction_type = ContractionType.AABB
if self.config.learned_background:
self.geometry_bg = models.make(self.config.geometry_bg.name, self.config.geometry_bg)
self.texture_bg = models.make(self.config.texture_bg.name, self.config.texture_bg)
self.geometry_bg.contraction_type = ContractionType.UN_BOUNDED_SPHERE
self.near_plane_bg, self.far_plane_bg = 0.1, 1e3
self.cone_angle_bg = 10**(math.log10(self.far_plane_bg) / self.config.num_samples_per_ray_bg) - 1.
self.render_step_size_bg = 0.01
self.variance = VarianceNetwork(self.config.variance)
self.register_buffer('scene_aabb', torch.as_tensor([-self.config.radius, -self.config.radius, -self.config.radius, self.config.radius, self.config.radius, self.config.radius], dtype=torch.float32))
if self.config.grid_prune:
self.occupancy_grid = OccupancyGrid(
roi_aabb=self.scene_aabb,
resolution=128,
contraction_type=ContractionType.AABB
)
if self.config.learned_background:
self.occupancy_grid_bg = OccupancyGrid(
roi_aabb=self.scene_aabb,
resolution=256,
contraction_type=ContractionType.UN_BOUNDED_SPHERE
)
self.randomized = self.config.randomized
self.background_color = None
self.render_step_size = 1.732 * 2 * self.config.radius / self.config.num_samples_per_ray
def update_step(self, epoch, global_step):
|
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.config.get('modulate', False)
if self.modulate:
self.mod_start_steps = self.config.mod_start_steps
self.reach_max_steps = self.config.reach_max_steps
self.max_inv_s = self.config.max_inv_s
@property
def inv_s(self):
val = torch.exp(self.variance * 10.0)
if self.modulate and self.do_mod:
val = val.clamp_max(self.mod_val)
return val
def forward(self, x):
return torch.ones([len(x), 1], device=self.variance.device) * self.inv_s
def update_step(self, epoch, global_step):
if self.modulate:
self.do_mod = global_step > self.mod_start_steps
if not self.do_mod:
self.prev_inv_s = self.inv_s.item()
else:
self.mod_val = min((global_step / self.reach_max_steps) * (self.max_inv_s - self.prev_inv_s) + self.prev_inv_s, self.max_inv_s)
@models.register('neus')
class NeuSModel(BaseModel):
def setup(self):
self.geometry = models.make(self.config.geometry.name, self.config.geometry)
self.texture = models.make(self.config.texture.name, self.config.texture)
self.geometry.contraction_type = ContractionType.AABB
if self.config.learned_background:
self.geometry_bg = models.make(self.config.geometry_bg.name, self.config.geometry_bg)
self.texture_bg = models.make(self.config.texture_bg.name, self.config.texture_bg)
self.geometry_bg.contraction_type = ContractionType.UN_BOUNDED_SPHERE
self.near_plane_bg, self.far_plane_bg = 0.1, 1e3
self.cone_angle_bg = 10**(math.log10(self.far_plane_bg) / self.config.num_samples_per_ray_bg) - 1.
self.render_step_size_bg = 0.01
self.variance = VarianceNetwork(self.config.variance)
self.register_buffer('scene_aabb', torch.as_tensor([-self.config.radius, -self.config.radius, -self.config.radius, self.config.radius, self.config.radius, self.config.radius], dtype=torch.float32))
if self.config.grid_prune:
self.occupancy_grid = OccupancyGrid(
roi_aabb=self.scene_aabb,
resolution=128,
contraction_type=ContractionType.AABB
)
if self.config.learned_background:
self.occupancy_grid_bg = OccupancyGrid(
roi_aabb=self.scene_aabb,
resolution=256,
contraction_type=ContractionType.UN_BOUNDED_SPHERE
)
self.randomized = self.config.randomized
self.background_color = None
self.render_step_size = 1.732 * 2 * self.config.radius / self.config.num_samples_per_ray
def update_step(self, epoch, global_step): | 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, server_error_msg,
violates_moderation, moderation_msg) | 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",
}
def get_conv_log_filename():
t = datetime.datetime.now()
name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
return name
def get_model_list():
ret = requests.post(args.controller_url + "/refresh_all_workers")
assert ret.status_code == 200
ret = requests.post(args.controller_url + "/list_models")
models = ret.json()["models"]
models.sort(key=lambda x: priority.get(x, x))
logger.info(f"Models: {models}")
return models
get_window_url_params = """
function() {
const params = new URLSearchParams(window.location.search);
url_params = Object.fromEntries(params);
console.log(url_params);
return url_params;
}
"""
def load_demo(url_params, request: gr.Request):
logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
dropdown_update = gr.Dropdown.update(visible=True)
if "model" in url_params:
model = url_params["model"]
if model in models:
dropdown_update = gr.Dropdown.update(
value=model, visible=True)
|
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",
}
def get_conv_log_filename():
t = datetime.datetime.now()
name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
return name
def get_model_list():
ret = requests.post(args.controller_url + "/refresh_all_workers")
assert ret.status_code == 200
ret = requests.post(args.controller_url + "/list_models")
models = ret.json()["models"]
models.sort(key=lambda x: priority.get(x, x))
logger.info(f"Models: {models}")
return models
get_window_url_params = """
function() {
const params = new URLSearchParams(window.location.search);
url_params = Object.fromEntries(params);
console.log(url_params);
return url_params;
}
"""
def load_demo(url_params, request: gr.Request):
logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
dropdown_update = gr.Dropdown.update(visible=True)
if "model" in url_params:
model = url_params["model"]
if model in models:
dropdown_update = gr.Dropdown.update(
value=model, visible=True)
| 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):
self.brs_loss = brs_loss
self.optimizer_params = optimizer_params
self.prob_thresh = prob_thresh
self.reg_weight = reg_weight
self.min_iou_diff = min_iou_diff
self.with_flip = with_flip
self.flip_average = flip_average
self.best_prediction = None
self._get_prediction_logits = None
self._opt_shape = None
self._best_loss = None
self._click_masks = None
self._last_mask = None
self.device = None
def init_click(self, get_prediction_logits, pos_mask, neg_mask, device, shape=None):
self.best_prediction = None
self._get_prediction_logits = get_prediction_logits
self._click_masks = (pos_mask, neg_mask)
self._opt_shape = shape
self._last_mask = None
self.device = device
def __call__(self, x):
opt_params = torch.from_numpy(x).float().to(self.device)
opt_params.requires_grad_(True)
with torch.enable_grad():
opt_vars, reg_loss = self.unpack_opt_params(opt_params)
result_before_sigmoid = self._get_prediction_logits(*opt_vars)
result = torch.sigmoid(result_before_sigmoid)
pos_mask, neg_mask = self._click_masks
if self.with_flip and self.flip_average:
result, result_flipped = torch.chunk(result, 2, dim=0)
result = 0.5 * (result + torch.flip(result_flipped, dims=[3]))
pos_mask, neg_mask = pos_mask[:result.shape[0]], neg_mask[:result.shape[0]]
loss, f_max_pos, f_max_neg = self.brs_loss(result, pos_mask, neg_mask)
loss = loss + reg_loss
f_val = loss.detach().cpu().numpy()
if self.best_prediction is None or f_val < self._best_loss:
self.best_prediction = result_before_sigmoid.detach()
self._best_loss = f_val
if f_max_pos < (1 - self.prob_thresh) and f_max_neg < self.prob_thresh:
return [f_val, np.zeros_like(x)]
current_mask = result > self.prob_thresh
if self._last_mask is not None and self.min_iou_diff > 0:
|
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):
self.brs_loss = brs_loss
self.optimizer_params = optimizer_params
self.prob_thresh = prob_thresh
self.reg_weight = reg_weight
self.min_iou_diff = min_iou_diff
self.with_flip = with_flip
self.flip_average = flip_average
self.best_prediction = None
self._get_prediction_logits = None
self._opt_shape = None
self._best_loss = None
self._click_masks = None
self._last_mask = None
self.device = None
def init_click(self, get_prediction_logits, pos_mask, neg_mask, device, shape=None):
self.best_prediction = None
self._get_prediction_logits = get_prediction_logits
self._click_masks = (pos_mask, neg_mask)
self._opt_shape = shape
self._last_mask = None
self.device = device
def __call__(self, x):
opt_params = torch.from_numpy(x).float().to(self.device)
opt_params.requires_grad_(True)
with torch.enable_grad():
opt_vars, reg_loss = self.unpack_opt_params(opt_params)
result_before_sigmoid = self._get_prediction_logits(*opt_vars)
result = torch.sigmoid(result_before_sigmoid)
pos_mask, neg_mask = self._click_masks
if self.with_flip and self.flip_average:
result, result_flipped = torch.chunk(result, 2, dim=0)
result = 0.5 * (result + torch.flip(result_flipped, dims=[3]))
pos_mask, neg_mask = pos_mask[:result.shape[0]], neg_mask[:result.shape[0]]
loss, f_max_pos, f_max_neg = self.brs_loss(result, pos_mask, neg_mask)
loss = loss + reg_loss
f_val = loss.detach().cpu().numpy()
if self.best_prediction is None or f_val < self._best_loss:
self.best_prediction = result_before_sigmoid.detach()
self._best_loss = f_val
if f_max_pos < (1 - self.prob_thresh) and f_max_neg < self.prob_thresh:
return [f_val, np.zeros_like(x)]
current_mask = result > self.prob_thresh
if self._last_mask is not None and self.min_iou_diff > 0: | 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 import Data
from ultra import tasks, util
from ultra.models import Ultra | 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.multinomial(probs, 1, replacement=False).item()
graph = train_graphs[graph_id]
bs = len(batch)
edge_mask = torch.randperm(graph.target_edge_index.shape[1])[:bs]
batch = torch.cat([graph.target_edge_index[:, edge_mask], graph.target_edge_type[edge_mask].unsqueeze(0)]).t()
return graph, batch
# here we assume that train_data and valid_data are tuples of datasets
def train_and_validate(cfg, model, train_data, valid_data, filtered_data=None, batch_per_epoch=None):
if cfg.train.num_epoch == 0:
return
world_size = util.get_world_size()
rank = util.get_rank()
train_triplets = torch.cat([
torch.cat([g.target_edge_index, g.target_edge_type.unsqueeze(0)]).t()
for g in train_data
])
sampler = torch_data.DistributedSampler(train_triplets, world_size, rank)
train_loader = torch_data.DataLoader(train_triplets, cfg.train.batch_size, sampler=sampler, collate_fn=partial(multigraph_collator, train_graphs=train_data))
batch_per_epoch = batch_per_epoch or len(train_loader)
cls = cfg.optimizer.pop("class")
optimizer = getattr(optim, cls)(model.parameters(), **cfg.optimizer)
num_params = sum(p.numel() for p in model.parameters())
logger.warning(line)
logger.warning(f"Number of parameters: {num_params}")
if world_size > 1:
parallel_model = nn.parallel.DistributedDataParallel(model, device_ids=[device])
else:
parallel_model = model
step = math.ceil(cfg.train.num_epoch / 10)
best_result = float("-inf")
best_epoch = -1
batch_id = 0
for i in range(0, cfg.train.num_epoch, step):
parallel_model.train()
for epoch in range(i, min(cfg.train.num_epoch, i + step)):
if util.get_rank() == 0:
logger.warning(separator)
logger.warning("Epoch %d begin" % epoch)
losses = []
sampler.set_epoch(epoch)
for batch in islice(train_loader, batch_per_epoch):
# now at each step we sample a new graph and edges from it
train_graph, batch = batch
|
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.multinomial(probs, 1, replacement=False).item()
graph = train_graphs[graph_id]
bs = len(batch)
edge_mask = torch.randperm(graph.target_edge_index.shape[1])[:bs]
batch = torch.cat([graph.target_edge_index[:, edge_mask], graph.target_edge_type[edge_mask].unsqueeze(0)]).t()
return graph, batch
# here we assume that train_data and valid_data are tuples of datasets
def train_and_validate(cfg, model, train_data, valid_data, filtered_data=None, batch_per_epoch=None):
if cfg.train.num_epoch == 0:
return
world_size = util.get_world_size()
rank = util.get_rank()
train_triplets = torch.cat([
torch.cat([g.target_edge_index, g.target_edge_type.unsqueeze(0)]).t()
for g in train_data
])
sampler = torch_data.DistributedSampler(train_triplets, world_size, rank)
train_loader = torch_data.DataLoader(train_triplets, cfg.train.batch_size, sampler=sampler, collate_fn=partial(multigraph_collator, train_graphs=train_data))
batch_per_epoch = batch_per_epoch or len(train_loader)
cls = cfg.optimizer.pop("class")
optimizer = getattr(optim, cls)(model.parameters(), **cfg.optimizer)
num_params = sum(p.numel() for p in model.parameters())
logger.warning(line)
logger.warning(f"Number of parameters: {num_params}")
if world_size > 1:
parallel_model = nn.parallel.DistributedDataParallel(model, device_ids=[device])
else:
parallel_model = model
step = math.ceil(cfg.train.num_epoch / 10)
best_result = float("-inf")
best_epoch = -1
batch_id = 0
for i in range(0, cfg.train.num_epoch, step):
parallel_model.train()
for epoch in range(i, min(cfg.train.num_epoch, i + step)):
if util.get_rank() == 0:
logger.warning(separator)
logger.warning("Epoch %d begin" % epoch)
losses = []
sampler.set_epoch(epoch)
for batch in islice(train_loader, batch_per_epoch):
# now at each step we sample a new graph and edges from it
train_graph, batch = batch | 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_hints | 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)
):
return view_func(level, name, *args, **kwargs) # valid challenge
abort(404)
return wrapper
@sitemapper.include(changefreq="daily", priority=1.0)
@app_views.route("/")
def index():
return render_template(
"index.html",
challenges_groupby_level=challenge_manager.challenges_groupby_level,
)
@sitemapper.include(
changefreq="daily",
priority=0.5,
# https://github.com/h-janes/flask-sitemapper/wiki/Usage#dynamic-routes
url_variables={
"level": [c.level for c in challenge_manager.challenges.keys()],
"name": [c.name for c in challenge_manager.challenges.keys()],
},
)
@app_views.route("/<level>/<name>", methods=["GET"])
@validate_challenge
def get_challenge(level: str, name: str):
challenge = challenge_manager.get_challenge(ChallengeKey(Level(level), name))
params = {
"name": name,
"level": challenge.level,
"challenges_groupby_level": challenge_manager.challenges_groupby_level,
"code_under_test": challenge.user_code,
"test_code": challenge.test_code,
|
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)
):
return view_func(level, name, *args, **kwargs) # valid challenge
abort(404)
return wrapper
@sitemapper.include(changefreq="daily", priority=1.0)
@app_views.route("/")
def index():
return render_template(
"index.html",
challenges_groupby_level=challenge_manager.challenges_groupby_level,
)
@sitemapper.include(
changefreq="daily",
priority=0.5,
# https://github.com/h-janes/flask-sitemapper/wiki/Usage#dynamic-routes
url_variables={
"level": [c.level for c in challenge_manager.challenges.keys()],
"name": [c.name for c in challenge_manager.challenges.keys()],
},
)
@app_views.route("/<level>/<name>", methods=["GET"])
@validate_challenge
def get_challenge(level: str, name: str):
challenge = challenge_manager.get_challenge(ChallengeKey(Level(level), name))
params = {
"name": name,
"level": challenge.level,
"challenges_groupby_level": challenge_manager.challenges_groupby_level,
"code_under_test": challenge.user_code,
"test_code": challenge.test_code, | "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://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
class ImageEncoderViT(nn.Module):
def __init__(
self,
img_size: int = 1024,
patch_size: int = 16,
in_chans: int = 3,
embed_dim: int = 768,
depth: int = 12,
num_heads: int = 12,
mlp_ratio: float = 4.0,
out_chans: int = 256,
qkv_bias: bool = True,
norm_layer: Type[nn.Module] = nn.LayerNorm,
act_layer: Type[nn.Module] = nn.GELU,
use_abs_pos: bool = True,
use_rel_pos: bool = False,
rel_pos_zero_init: bool = True,
window_size: int = 0,
global_attn_indexes: Tuple[int, ...] = (),
) -> None:
"""
Args:
img_size (int): Input image size.
patch_size (int): Patch size.
in_chans (int): Number of input image channels.
embed_dim (int): Patch embedding dimension.
depth (int): Depth of ViT.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_abs_pos (bool): If True, use absolute positional embeddings.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks.
global_attn_indexes (list): Indexes for blocks using global attention.
"""
super().__init__()
self.img_size = img_size
self.patch_embed = PatchEmbed(
kernel_size=(patch_size, patch_size),
stride=(patch_size, patch_size),
in_chans=in_chans,
embed_dim=embed_dim,
)
self.pos_embed: Optional[nn.Parameter] = None
if use_abs_pos:
# Initialize absolute positional embedding with pretrain image size.
self.pos_embed = nn.Parameter(
torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim)
)
self.blocks = nn.ModuleList()
for i in range(depth):
block = Block(
dim=embed_dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
norm_layer=norm_layer,
act_layer=act_layer,
use_rel_pos=use_rel_pos,
rel_pos_zero_init=rel_pos_zero_init,
window_size=window_size if i not in global_attn_indexes else 0,
input_size=(img_size // patch_size, img_size // patch_size),
)
self.blocks.append(block)
self.neck = nn.Sequential(
nn.Conv2d(
embed_dim,
out_chans,
kernel_size=1,
bias=False,
),
| # 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://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
class ImageEncoderViT(nn.Module):
def __init__(
self,
img_size: int = 1024,
patch_size: int = 16,
in_chans: int = 3,
embed_dim: int = 768,
depth: int = 12,
num_heads: int = 12,
mlp_ratio: float = 4.0,
out_chans: int = 256,
qkv_bias: bool = True,
norm_layer: Type[nn.Module] = nn.LayerNorm,
act_layer: Type[nn.Module] = nn.GELU,
use_abs_pos: bool = True,
use_rel_pos: bool = False,
rel_pos_zero_init: bool = True,
window_size: int = 0,
global_attn_indexes: Tuple[int, ...] = (),
) -> None:
"""
Args:
img_size (int): Input image size.
patch_size (int): Patch size.
in_chans (int): Number of input image channels.
embed_dim (int): Patch embedding dimension.
depth (int): Depth of ViT.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_abs_pos (bool): If True, use absolute positional embeddings.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks.
global_attn_indexes (list): Indexes for blocks using global attention.
"""
super().__init__()
self.img_size = img_size
self.patch_embed = PatchEmbed(
kernel_size=(patch_size, patch_size),
stride=(patch_size, patch_size),
in_chans=in_chans,
embed_dim=embed_dim,
)
self.pos_embed: Optional[nn.Parameter] = None
if use_abs_pos:
# Initialize absolute positional embedding with pretrain image size.
self.pos_embed = nn.Parameter(
torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim)
)
self.blocks = nn.ModuleList()
for i in range(depth):
block = Block(
dim=embed_dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
norm_layer=norm_layer,
act_layer=act_layer,
use_rel_pos=use_rel_pos,
rel_pos_zero_init=rel_pos_zero_init,
window_size=window_size if i not in global_attn_indexes else 0,
input_size=(img_size // patch_size, img_size // patch_size),
)
self.blocks.append(block)
self.neck = nn.Sequential(
nn.Conv2d(
embed_dim,
out_chans,
kernel_size=1,
bias=False,
),
| 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)
continue
|
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)
continue
| 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.username = username
self.result_file = os.path.join("data", f"{self.username}.txt")
self.found_only = found_only
# this function checks if the url not a false positive result, return false
def is_soft404(self, html_response: str) -> bool:
# this is for checking the title bar of the page
soup = BeautifulSoup(html_response, "html.parser")
page_title = soup.title.string.strip() if soup.title else ""
# I know this is kinda messy solution but it currently solve.. reduce the problem
# in soft404 responses (false positives)
for error_indicator in soft404_indicators:
if (
# check if the error indicator is in the html string response
error_indicator.lower() in html_response.lower()
# check for the title bar of the page if there are anyi error_indicator
or error_indicator.lower() in page_title.lower()
# Specific check sites, since positive result will have the username in the title bar.
or page_title.lower() == "instagram"
# patreon's removed user
or page_title.lower() == "patreon logo"
or "sign in" in page_title.lower()
):
return True
return False
def check_site(self, site: str, url: str, headers):
url = url.format(self.username)
# we need headers to avoid being blocked by requesting the website 403 error
try:
with requests.Session() as session:
response = session.get(url, headers=headers)
# Raises an HTTPError for bad responses
# further check to reduce false positive results
if (
response.status_code == 200
and self.username.lower() in response.text.lower()
and not self.is_soft404(response.text)
):
# to prevent multiple threads from accessing/modifying the positive
# counts simultaneously and prevent race conditions.
with threading.Lock():
self.positive_count += 1
self.console.print(self.notify.found(site, url))
with open(self.result_file, "a") as f:
f.write(f"{url}\n")
# the site reurned 404 (user not found)
else:
if not self.found_only:
self.console.print(self.notify.not_found(site))
except Exception as e:
self.notify.exception(site, e)
def start(self):
"""
Start the search.
"""
self.console.print(self.notify.start(self.username, len(sites)))
current_datetime = datetime.datetime.now()
date = current_datetime.strftime("%m/%d/%Y")
time = current_datetime.strftime("%I:%M %p")
| #! /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.username = username
self.result_file = os.path.join("data", f"{self.username}.txt")
self.found_only = found_only
# this function checks if the url not a false positive result, return false
def is_soft404(self, html_response: str) -> bool:
# this is for checking the title bar of the page
soup = BeautifulSoup(html_response, "html.parser")
page_title = soup.title.string.strip() if soup.title else ""
# I know this is kinda messy solution but it currently solve.. reduce the problem
# in soft404 responses (false positives)
for error_indicator in soft404_indicators:
if (
# check if the error indicator is in the html string response
error_indicator.lower() in html_response.lower()
# check for the title bar of the page if there are anyi error_indicator
or error_indicator.lower() in page_title.lower()
# Specific check sites, since positive result will have the username in the title bar.
or page_title.lower() == "instagram"
# patreon's removed user
or page_title.lower() == "patreon logo"
or "sign in" in page_title.lower()
):
return True
return False
def check_site(self, site: str, url: str, headers):
url = url.format(self.username)
# we need headers to avoid being blocked by requesting the website 403 error
try:
with requests.Session() as session:
response = session.get(url, headers=headers)
# Raises an HTTPError for bad responses
# further check to reduce false positive results
if (
response.status_code == 200
and self.username.lower() in response.text.lower()
and not self.is_soft404(response.text)
):
# to prevent multiple threads from accessing/modifying the positive
# counts simultaneously and prevent race conditions.
with threading.Lock():
self.positive_count += 1
self.console.print(self.notify.found(site, url))
with open(self.result_file, "a") as f:
f.write(f"{url}\n")
# the site reurned 404 (user not found)
else:
if not self.found_only:
self.console.print(self.notify.not_found(site))
except Exception as e:
self.notify.exception(site, e)
def start(self):
"""
Start the search.
"""
self.console.print(self.notify.start(self.username, len(sites)))
current_datetime = datetime.datetime.now()
date = current_datetime.strftime("%m/%d/%Y")
time = current_datetime.strftime("%I:%M %p") | 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, MilvusUnavailableException
from RetrievalAugmentedGeneration.common import utils
from RetrievalAugmentedGeneration.examples.developer_rag import chains | 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The definition of the Llama Index chain server."""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# create the FastAPI server
app = FastAPI()
# prestage the embedding model
_ = utils.get_embedding_model()
# set the global service context for Llama Index
utils.set_service_context()
class Prompt(BaseModel):
"""Definition of the Prompt API data type."""
question: str = Field(description="The input query/prompt to the pipeline.")
context: str = Field(description="Additional context for the question (optional)")
use_knowledge_base: bool = Field(description="Whether to use a knowledge base", default=True)
num_tokens: int = Field(description="The maximum number of tokens in the response.", default=50)
class DocumentSearch(BaseModel):
"""Definition of the DocumentSearch API data type."""
content: str = Field(description="The content or keywords to search for within documents.")
num_docs: int = Field(description="The maximum number of documents to return in the response.", default=4)
@app.post("/uploadDocument")
async def upload_document(file: UploadFile = File(...)) -> JSONResponse:
"""Upload a document to the vector store."""
if not file.filename:
return JSONResponse(content={"message": "No files provided"}, status_code=200)
try:
upload_folder = "uploaded_files"
upload_file = os.path.basename(file.filename)
if not upload_file:
raise RuntimeError("Error parsing uploaded filename.")
file_path = os.path.join(upload_folder, upload_file)
uploads_dir = Path(upload_folder)
uploads_dir.mkdir(parents=True, exist_ok=True)
with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f)
| # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The definition of the Llama Index chain server."""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# create the FastAPI server
app = FastAPI()
# prestage the embedding model
_ = utils.get_embedding_model()
# set the global service context for Llama Index
utils.set_service_context()
class Prompt(BaseModel):
"""Definition of the Prompt API data type."""
question: str = Field(description="The input query/prompt to the pipeline.")
context: str = Field(description="Additional context for the question (optional)")
use_knowledge_base: bool = Field(description="Whether to use a knowledge base", default=True)
num_tokens: int = Field(description="The maximum number of tokens in the response.", default=50)
class DocumentSearch(BaseModel):
"""Definition of the DocumentSearch API data type."""
content: str = Field(description="The content or keywords to search for within documents.")
num_docs: int = Field(description="The maximum number of documents to return in the response.", default=4)
@app.post("/uploadDocument")
async def upload_document(file: UploadFile = File(...)) -> JSONResponse:
"""Upload a document to the vector store."""
if not file.filename:
return JSONResponse(content={"message": "No files provided"}, status_code=200)
try:
upload_folder = "uploaded_files"
upload_file = os.path.basename(file.filename)
if not upload_file:
raise RuntimeError("Error parsing uploaded filename.")
file_path = os.path.join(upload_folder, upload_file)
uploads_dir = Path(upload_folder)
uploads_dir.mkdir(parents=True, exist_ok=True)
with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f)
| 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())
# Get last OTA update time from db
|
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())
# Get last OTA update time from db | 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_argument('--output_path', type=str, required=True, help='Path to output database')
parser.add_argument('--bert-model', type=str, default='multi-qa-MiniLM-L6-cos-v1', help='Path to sentence transformer model')
parser.add_argument('--top_k', type=int, default=1, help='Number of top-k similar cases to retrieve')
parser.add_argument('--batch_size', type=int, default=32, help='Batch size for encoding')
parser.add_argument('--device', type=str, default=None, help='Device to use for encoding (e.g. "cuda:0")')
parser.add_argument("--model", type=str, default="gpt-4", help="The name of the OpenAI model to use")
parser.add_argument("--data-type", type=str, default="code", help="The name of the instruction function to use")
parser.add_argument("--max-workers", type=int, default=2, help="The maximum number of worker threads to use")
args = parser.parse_args()
check_openai_key()
bert_model = SentenceTransformer(args.bert_model)
database = build_database(bert_model, args.train_path, args.test_path, args.output_path, args.top_k, args.batch_size, args.device)
|
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_argument('--output_path', type=str, required=True, help='Path to output database')
parser.add_argument('--bert-model', type=str, default='multi-qa-MiniLM-L6-cos-v1', help='Path to sentence transformer model')
parser.add_argument('--top_k', type=int, default=1, help='Number of top-k similar cases to retrieve')
parser.add_argument('--batch_size', type=int, default=32, help='Batch size for encoding')
parser.add_argument('--device', type=str, default=None, help='Device to use for encoding (e.g. "cuda:0")')
parser.add_argument("--model", type=str, default="gpt-4", help="The name of the OpenAI model to use")
parser.add_argument("--data-type", type=str, default="code", help="The name of the instruction function to use")
parser.add_argument("--max-workers", type=int, default=2, help="The maximum number of worker threads to use")
args = parser.parse_args()
check_openai_key()
bert_model = SentenceTransformer(args.bert_model)
database = build_database(bert_model, args.train_path, args.test_path, args.output_path, args.top_k, args.batch_size, args.device)
| 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 normalize_smiles | 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 endpoints and so all the parameters from each endpoint is
collected into a list. This is also true in cases where there is only one
endpoint.
"""
reference_smiles: List[List[str]]
num_of_cuts: List[int] = field(default_factory=lambda: [1])
max_variable_heavies: List[int] = field(default_factory=lambda: [40])
max_variable_ratio: List[float] = field(default_factory=lambda: [0.33])
FRAG_CMD = "mmpdb --quiet fragment --num-cuts {ncuts}"
IDX_CMD = (
"mmpdb --quiet index --out csv --symmetric --max-variable-heavies {heavy} "
"--max-variable-ratio {ratio}"
)
@add_tag("__component")
class MMP:
def __init__(self, params: Parameters):
self.ref_smilies = params.reference_smiles
self.num_of_cuts = params.num_of_cuts
self.max_variable_heavies = params.max_variable_heavies
self.max_variable_ratio = params.max_variable_ratio
# needed in the normalize_smiles decorator
# FIXME: really needs to be configurable for each model separately
self.smiles_type = 'rdkit_smiles'
@normalize_smiles
def __call__(self, smilies: List[str]) -> np.array:
scores = []
self.ref_smilies = [[Chem.MolToSmiles(Chem.MolFromSmiles(smi), isomericSmiles=False)
for smi in self.ref_smilies[0] if Chem.MolFromSmiles(smi)]]
smilies = [Chem.MolToSmiles(Chem.MolFromSmiles(smi), isomericSmiles=False) for smi in smilies if
Chem.MolFromSmiles(smi)]
for ref_smilies, ncuts, max_heavy, max_ratio in zip(
self.ref_smilies, self.num_of_cuts, self.max_variable_heavies, self.max_variable_ratio
):
smiles_csv = format_smilies(smilies, ref_smilies)
frag_cmd = FRAG_CMD.format(ncuts=ncuts)
| """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 endpoints and so all the parameters from each endpoint is
collected into a list. This is also true in cases where there is only one
endpoint.
"""
reference_smiles: List[List[str]]
num_of_cuts: List[int] = field(default_factory=lambda: [1])
max_variable_heavies: List[int] = field(default_factory=lambda: [40])
max_variable_ratio: List[float] = field(default_factory=lambda: [0.33])
FRAG_CMD = "mmpdb --quiet fragment --num-cuts {ncuts}"
IDX_CMD = (
"mmpdb --quiet index --out csv --symmetric --max-variable-heavies {heavy} "
"--max-variable-ratio {ratio}"
)
@add_tag("__component")
class MMP:
def __init__(self, params: Parameters):
self.ref_smilies = params.reference_smiles
self.num_of_cuts = params.num_of_cuts
self.max_variable_heavies = params.max_variable_heavies
self.max_variable_ratio = params.max_variable_ratio
# needed in the normalize_smiles decorator
# FIXME: really needs to be configurable for each model separately
self.smiles_type = 'rdkit_smiles'
@normalize_smiles
def __call__(self, smilies: List[str]) -> np.array:
scores = []
self.ref_smilies = [[Chem.MolToSmiles(Chem.MolFromSmiles(smi), isomericSmiles=False)
for smi in self.ref_smilies[0] if Chem.MolFromSmiles(smi)]]
smilies = [Chem.MolToSmiles(Chem.MolFromSmiles(smi), isomericSmiles=False) for smi in smilies if
Chem.MolFromSmiles(smi)]
for ref_smilies, ncuts, max_heavy, max_ratio in zip(
self.ref_smilies, self.num_of_cuts, self.max_variable_heavies, self.max_variable_ratio
):
smiles_csv = format_smilies(smilies, ref_smilies)
frag_cmd = FRAG_CMD.format(ncuts=ncuts) | 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.
Attributes:
id_ (str): Unique identifier for the node, aliased as 'node_id'.
metadata (Dict[str, Any]): Dictionary of metadata related to the node.
label (Optional[str]): Label categorizing or identifying the node.
related_nodes (List[str]): Identifiers for nodes related to this node.
content (Union[str, Dict[str, Any], None, Any]): Content of the node.
"""
| # 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.
Attributes:
id_ (str): Unique identifier for the node, aliased as 'node_id'.
metadata (Dict[str, Any]): Dictionary of metadata related to the node.
label (Optional[str]): Label categorizing or identifying the node.
related_nodes (List[str]): Identifiers for nodes related to this node.
content (Union[str, Dict[str, Any], None, Any]): Content of the node.
""" | 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):
if hasattr(cls, "loaded_extensions") or use_gpu:
return
print_message(f"Loading segmented_lookup_cpp extension (set COLBERT_LOAD_TORCH_EXTENSION_VERBOSE=True for more info)...")
segmented_lookup_cpp = load(
name="segmented_lookup_cpp",
sources=[
os.path.join(
pathlib.Path(__file__).parent.resolve(), "segmented_lookup.cpp"
),
],
extra_cflags=["-O3"],
verbose=os.getenv("COLBERT_LOAD_TORCH_EXTENSION_VERBOSE", "False") == "True",
)
cls.segmented_lookup = segmented_lookup_cpp.segmented_lookup_cpp
cls.loaded_extensions = True
@classmethod
def pad_packed(cls, packed_tensor, lengths):
assert False, "This seems to be incorrect but I can't see why. Is it the inner_dims in the views?"
packed_tensor, lengths = packed_tensor.cuda().contiguous(), lengths.cuda()
inner_dims = packed_tensor.size()[1:]
stride = lengths.max().item()
offsets = torch.cumsum(lengths, dim=0) - lengths[0]
padding = torch.zeros(stride, *inner_dims, device=packed_tensor.device, dtype=packed_tensor.dtype)
packed_tensor = torch.cat((packed_tensor, padding))
|
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):
if hasattr(cls, "loaded_extensions") or use_gpu:
return
print_message(f"Loading segmented_lookup_cpp extension (set COLBERT_LOAD_TORCH_EXTENSION_VERBOSE=True for more info)...")
segmented_lookup_cpp = load(
name="segmented_lookup_cpp",
sources=[
os.path.join(
pathlib.Path(__file__).parent.resolve(), "segmented_lookup.cpp"
),
],
extra_cflags=["-O3"],
verbose=os.getenv("COLBERT_LOAD_TORCH_EXTENSION_VERBOSE", "False") == "True",
)
cls.segmented_lookup = segmented_lookup_cpp.segmented_lookup_cpp
cls.loaded_extensions = True
@classmethod
def pad_packed(cls, packed_tensor, lengths):
assert False, "This seems to be incorrect but I can't see why. Is it the inner_dims in the views?"
packed_tensor, lengths = packed_tensor.cuda().contiguous(), lengths.cuda()
inner_dims = packed_tensor.size()[1:]
stride = lengths.max().item()
offsets = torch.cumsum(lengths, dim=0) - lengths[0]
padding = torch.zeros(stride, *inner_dims, device=packed_tensor.device, dtype=packed_tensor.dtype)
packed_tensor = torch.cat((packed_tensor, padding))
| 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 == groups
def test_bitlinear_reset_parameters():
layer = BitLinear(10, 20)
original_weights = layer.weight.clone()
layer.reset_parameters()
assert not torch.equal(original_weights, layer.weight)
@pytest.mark.parametrize("groups", [1, 2, 5])
def test_bitlinear_forward_with_groups(random_tensor, groups):
layer = BitLinear(10, 20, groups=groups)
output = layer(random_tensor)
assert output.shape == (5, 20)
def test_bitlinear_zero_input():
layer = BitLinear(10, 20)
input_tensor = torch.zeros(5, 10)
output = layer(input_tensor)
assert torch.allclose(output, torch.zeros(5, 20), atol=1e-2)
def test_bitlinear_weight_sign():
layer = BitLinear(10, 20)
input_tensor = torch.randn(5, 10)
output_before = layer(input_tensor)
layer.weight.data = torch.abs(layer.weight.data)
output_after = layer(input_tensor)
assert not torch.allclose(output_before, output_after)
@pytest.mark.parametrize("groups", [1, 2, 5])
def test_bitlinear_weight_group_normalization(groups):
layer = BitLinear(10, 20, groups=groups)
weight = layer.weight.view(groups, -1)
mean = weight.mean(dim=1, keepdim=True)
assert torch.allclose(mean, torch.zeros_like(mean), atol=1e-2)
def test_bitlinear_weight_group_scaling():
layer = BitLinear(10, 20, groups=5)
weight = layer.weight.view(layer.groups, -1)
beta = torch.abs(weight).sum(dim=1, keepdim=True) / (
weight.shape[0] * weight.shape[1]
)
scaled_weight = weight * beta
assert torch.allclose(scaled_weight, layer.weight.view(20, 10))
def test_bitlinear_input_quantization(random_tensor):
layer = BitLinear(10, 20)
quant_input, _ = absmax_quantize(random_tensor)
output = layer(quant_input.float())
assert output.shape == (5, 20)
# ... Continue adding more tests ...
# - Test the forward pass with extreme input values.
# - Test with different types of input tensors (e.g., int8, float16).
# - Test the forward pass with batch sizes other than 5.
# - Verify that using different initializations produces different results.
# - Test the weight and input interactions during the forward pass.
# - And many more...
# ================================ Transformer with bitlinear ================================
@pytest.fixture
def random_tensor():
"""A fixture to generate a random tensor"""
return torch.randn(32, 512)
@pytest.fixture
def bitnet_model():
"""A fixture to create an instance of BitNetTransformer model"""
return BitNetTransformer(
num_tokens=20000,
dim=512,
depth=6,
dim_head=64,
heads=8,
ff_mult=4,
)
@pytest.mark.parametrize(
"dim, dim_head, heads, ff_mult",
[
(512, 64, 8, 4),
(256, 32, 4, 2),
(128, 16, 2, 1),
],
)
def test_parallel_transformer_block(dim, dim_head, heads, ff_mult, random_tensor):
block = ParallelTransformerBlock(dim, dim_head, heads, ff_mult)
output = block(random_tensor)
assert output.shape == random_tensor.shape
@pytest.mark.parametrize(
"dim, depth, heads, dim_head, ff_mult",
[
(512, 6, 8, 64, 4),
(256, 3, 4, 32, 2),
(128, 2, 2, 16, 1),
],
)
def test_transformer(dim, depth, heads, dim_head, ff_mult, random_tensor):
|
# 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.in_features == 10
assert layer.out_features == 20
assert layer.weight.shape == (20, 10)
def test_bitlinear_forward():
layer = BitLinear(10, 20)
input_tensor = torch.randn(5, 10)
output = layer(input_tensor)
assert output.shape == (5, 20)
# Fixtures:
@pytest.fixture
def random_tensor():
return torch.randn(5, 10)
# Parameterized Testing:
@pytest.mark.parametrize("bits", [4, 8, 12, 16])
def test_absmax_quantize_bits(random_tensor, bits):
quant, dequant = absmax_quantize(random_tensor, bits=bits)
assert quant.dtype == torch.int8
assert torch.allclose(dequant, random_tensor, atol=1e-2)
# More Tests for BitLinear:
@pytest.mark.parametrize(
"in_features,out_features", [(10, 20), (20, 40), (5, 10), (15, 10)]
)
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 == groups
def test_bitlinear_reset_parameters():
layer = BitLinear(10, 20)
original_weights = layer.weight.clone()
layer.reset_parameters()
assert not torch.equal(original_weights, layer.weight)
@pytest.mark.parametrize("groups", [1, 2, 5])
def test_bitlinear_forward_with_groups(random_tensor, groups):
layer = BitLinear(10, 20, groups=groups)
output = layer(random_tensor)
assert output.shape == (5, 20)
def test_bitlinear_zero_input():
layer = BitLinear(10, 20)
input_tensor = torch.zeros(5, 10)
output = layer(input_tensor)
assert torch.allclose(output, torch.zeros(5, 20), atol=1e-2)
def test_bitlinear_weight_sign():
layer = BitLinear(10, 20)
input_tensor = torch.randn(5, 10)
output_before = layer(input_tensor)
layer.weight.data = torch.abs(layer.weight.data)
output_after = layer(input_tensor)
assert not torch.allclose(output_before, output_after)
@pytest.mark.parametrize("groups", [1, 2, 5])
def test_bitlinear_weight_group_normalization(groups):
layer = BitLinear(10, 20, groups=groups)
weight = layer.weight.view(groups, -1)
mean = weight.mean(dim=1, keepdim=True)
assert torch.allclose(mean, torch.zeros_like(mean), atol=1e-2)
def test_bitlinear_weight_group_scaling():
layer = BitLinear(10, 20, groups=5)
weight = layer.weight.view(layer.groups, -1)
beta = torch.abs(weight).sum(dim=1, keepdim=True) / (
weight.shape[0] * weight.shape[1]
)
scaled_weight = weight * beta
assert torch.allclose(scaled_weight, layer.weight.view(20, 10))
def test_bitlinear_input_quantization(random_tensor):
layer = BitLinear(10, 20)
quant_input, _ = absmax_quantize(random_tensor)
output = layer(quant_input.float())
assert output.shape == (5, 20)
# ... Continue adding more tests ...
# - Test the forward pass with extreme input values.
# - Test with different types of input tensors (e.g., int8, float16).
# - Test the forward pass with batch sizes other than 5.
# - Verify that using different initializations produces different results.
# - Test the weight and input interactions during the forward pass.
# - And many more...
# ================================ Transformer with bitlinear ================================
@pytest.fixture
def random_tensor():
"""A fixture to generate a random tensor"""
return torch.randn(32, 512)
@pytest.fixture
def bitnet_model():
"""A fixture to create an instance of BitNetTransformer model"""
return BitNetTransformer(
num_tokens=20000,
dim=512,
depth=6,
dim_head=64,
heads=8,
ff_mult=4,
)
@pytest.mark.parametrize(
"dim, dim_head, heads, ff_mult",
[
(512, 64, 8, 4),
(256, 32, 4, 2),
(128, 16, 2, 1),
],
)
def test_parallel_transformer_block(dim, dim_head, heads, ff_mult, random_tensor):
block = ParallelTransformerBlock(dim, dim_head, heads, ff_mult)
output = block(random_tensor)
assert output.shape == random_tensor.shape
@pytest.mark.parametrize(
"dim, depth, heads, dim_head, ff_mult",
[
(512, 6, 8, 64, 4),
(256, 3, 4, 32, 2),
(128, 2, 2, 16, 1),
],
)
def test_transformer(dim, depth, heads, dim_head, ff_mult, random_tensor): | 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 RetrievalPrecisionMetric
from tonic_validate.services.openai_service import OpenAIService | 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, help="Resolution to render")
parser.add_argument("--env", type=str, required=True)
args = parser.parse_args()
data = storage.load_data(args.path, exclude_keys=["mask"])
assert "state" in data
env = gym.make(args.env)
|
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, help="Resolution to render")
parser.add_argument("--env", type=str, required=True)
args = parser.parse_args()
data = storage.load_data(args.path, exclude_keys=["mask"])
assert "state" in data
env = gym.make(args.env) | 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_eval.metrics import mean, weighted_perplexity, weighted_mean, bits_per_byte
from lm_eval import utils
from abc import abstractmethod | 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 calls whenever possible.
:param requests: list
A list of pairs (context, continuation)
context: str
Context string. Implementations of LM must be able to handle an
empty context string.
continuation: str
The continuation over which log likelihood will be calculated. If
there is a word boundary, the space should be in the continuation.
For example, context="hello" continuation=" world" is correct.
:return: list
A list of pairs (logprob, isgreedy)
logprob: float
The log probability of `continuation`
isgreedy:
Whether `continuation` would be generated by greedy sampling from `context`
"""
pass
@abstractmethod
def loglikelihood_rolling(self, requests):
"""Compute full log-likelihood of a string, with no truncation, for perplexity computation
- We will use the full max context length of the model.
- For inputs that exceed the max context length, we divide the tokenized string into chunks of up to
the max context length.
- IMPORTANT: Each document's loglikelihood/perplexity is computed *separately*, unlike other implementations
which may simply concatenate multiple documents together.
- IMPORTANT: We maximize the amount of context for each prediction. Specifically, for inputs that we break into
multiple chunks, the last input will still a full-sized context.
Example:
Input tokens: [ 0 1 2 3 4 5 6 7 8 9 ]
Prefix: EOT
Max context length: 4
Resulting input/prediction pairs:
INPUT: EOT 0 1 2
PRED: 0 1 2 3
INPUT: 3 4 5 6
PRED: 4 5 6 7
INPUT: 5 6 7 8
PRED: 8 9
Observe that:
1. Each token is predicted exactly once
2. For the last pair, we provide the full context, but only score the last two tokens
:param requests: list
A list of strings
string: str
String for which we are computing per-toke loglikelihood
:return: list
A list of pairs (logprob, isgreedy)
logprob: float
The log probability of `continuation`
isgreedy:
Whether `continuation` would be generated by greedy sampling from `context`
"""
pass
# TODO: Add an optional max length
@abstractmethod
def greedy_until(self, requests):
"""Generate greedily until a stopping sequence
:param requests: list
A list of pairs (context, until)
context: str
Context string
until: [str]
The string sequences to generate until. These string sequences
may each span across multiple tokens, or may be part of one token.
:return: list
A list of strings continuation
continuation: str
The generated continuation.
"""
pass
@classmethod
def create_from_arg_string(cls, arg_string, additional_config=None):
additional_config = {} if additional_config is None else additional_config
|
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 calls whenever possible.
:param requests: list
A list of pairs (context, continuation)
context: str
Context string. Implementations of LM must be able to handle an
empty context string.
continuation: str
The continuation over which log likelihood will be calculated. If
there is a word boundary, the space should be in the continuation.
For example, context="hello" continuation=" world" is correct.
:return: list
A list of pairs (logprob, isgreedy)
logprob: float
The log probability of `continuation`
isgreedy:
Whether `continuation` would be generated by greedy sampling from `context`
"""
pass
@abstractmethod
def loglikelihood_rolling(self, requests):
"""Compute full log-likelihood of a string, with no truncation, for perplexity computation
- We will use the full max context length of the model.
- For inputs that exceed the max context length, we divide the tokenized string into chunks of up to
the max context length.
- IMPORTANT: Each document's loglikelihood/perplexity is computed *separately*, unlike other implementations
which may simply concatenate multiple documents together.
- IMPORTANT: We maximize the amount of context for each prediction. Specifically, for inputs that we break into
multiple chunks, the last input will still a full-sized context.
Example:
Input tokens: [ 0 1 2 3 4 5 6 7 8 9 ]
Prefix: EOT
Max context length: 4
Resulting input/prediction pairs:
INPUT: EOT 0 1 2
PRED: 0 1 2 3
INPUT: 3 4 5 6
PRED: 4 5 6 7
INPUT: 5 6 7 8
PRED: 8 9
Observe that:
1. Each token is predicted exactly once
2. For the last pair, we provide the full context, but only score the last two tokens
:param requests: list
A list of strings
string: str
String for which we are computing per-toke loglikelihood
:return: list
A list of pairs (logprob, isgreedy)
logprob: float
The log probability of `continuation`
isgreedy:
Whether `continuation` would be generated by greedy sampling from `context`
"""
pass
# TODO: Add an optional max length
@abstractmethod
def greedy_until(self, requests):
"""Generate greedily until a stopping sequence
:param requests: list
A list of pairs (context, until)
context: str
Context string
until: [str]
The string sequences to generate until. These string sequences
may each span across multiple tokens, or may be part of one token.
:return: list
A list of strings continuation
continuation: str
The generated continuation.
"""
pass
@classmethod
def create_from_arg_string(cls, arg_string, additional_config=None):
additional_config = {} if additional_config is None else additional_config | 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_cache(openai_cache_file)
self.temperature = kwargs.get("temperature", 0.0)
self.interaction_history = []
def get_gold_domain_info(self, target_specification_file):
'''Gets the gold domain specification that the model should try to learn and other associated information.
'''
gold_task = json.load(open(target_specification_file)) #"sample_tests.json"
for key in gold_task:
setattr(self, key, gold_task[key])
if key == "regex":
self.gold_regex_text = self.regex
self.gold_regex = re.compile(self.gold_regex_text)
self.persona_text = self.persona
def get_task_description(self):
return "validate an email address adheres to a specific format"
@staticmethod
def format_questions_and_answers(questions_and_answers):
'''Formats the questions and answers into a string.
Looks like:
- Should the system allow numbers in the domain? -> Yes
Args:
questions_and_answers (list): A list of tuples of the form (question, answer).
Returns:
str: The formatted questions and answers.
'''
return '\n'.join([f"- {question} -> {answer}" for question, answer in questions_and_answers])
def get_test_case_prompt(self, interaction_history, test_case):
hypothesis_prompt = textwrap.dedent('''\
{single_instance_prompt1}
{previous_examples}
{single_instance_prompt2}
{test_case}
'''
).format(
single_instance_prompt1=self.test_case_prompt[0],
previous_examples=self.format_questions_and_answers(interaction_history),
single_instance_prompt2=self.test_case_prompt[1],
test_case=test_case,
)
return [{"role": "user", "content": hypothesis_prompt}]
def generate_test_case_answer(self, test_case):
test_case_messages = self.get_test_case_prompt(self.interaction_history, test_case)
|
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_cache(openai_cache_file)
self.temperature = kwargs.get("temperature", 0.0)
self.interaction_history = []
def get_gold_domain_info(self, target_specification_file):
'''Gets the gold domain specification that the model should try to learn and other associated information.
'''
gold_task = json.load(open(target_specification_file)) #"sample_tests.json"
for key in gold_task:
setattr(self, key, gold_task[key])
if key == "regex":
self.gold_regex_text = self.regex
self.gold_regex = re.compile(self.gold_regex_text)
self.persona_text = self.persona
def get_task_description(self):
return "validate an email address adheres to a specific format"
@staticmethod
def format_questions_and_answers(questions_and_answers):
'''Formats the questions and answers into a string.
Looks like:
- Should the system allow numbers in the domain? -> Yes
Args:
questions_and_answers (list): A list of tuples of the form (question, answer).
Returns:
str: The formatted questions and answers.
'''
return '\n'.join([f"- {question} -> {answer}" for question, answer in questions_and_answers])
def get_test_case_prompt(self, interaction_history, test_case):
hypothesis_prompt = textwrap.dedent('''\
{single_instance_prompt1}
{previous_examples}
{single_instance_prompt2}
{test_case}
'''
).format(
single_instance_prompt1=self.test_case_prompt[0],
previous_examples=self.format_questions_and_answers(interaction_history),
single_instance_prompt2=self.test_case_prompt[1],
test_case=test_case,
)
return [{"role": "user", "content": hypothesis_prompt}]
def generate_test_case_answer(self, test_case):
test_case_messages = self.get_test_case_prompt(self.interaction_history, test_case) | 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 StyleEncoder | 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 building model
Examples:
>>> from libcom import HarmonyScoreModel
>>> from libcom.utils.process_image import make_image_grid
>>> import cv2
>>> net = HarmonyScoreModel(device=0, model_type='BargainNet')
>>> test_dir = '../tests/harmony_score_prediction/'
>>> img_names = ['vaulted-cellar-247391_inharm.jpg', 'ameland-5651866_harm.jpg']
>>> vis_list,scores = [], []
>>> for img_name in img_names:
>>> comp_img = test_dir + 'composite/' + img_name
>>> comp_mask = test_dir + 'composite_mask/' + img_name
>>> score = net(comp_img, comp_mask)
>>> vis_list += [comp_img, comp_mask]
>>> scores.append(score)
>>> grid_img = make_image_grid(vis_list, text_list=[f'harmony_score:{scores[0]:.2f}', 'composite-mask', f'harmony_score:{scores[1]:.2f}', 'composite-mask'])
>>> cv2.imwrite('../docs/_static/image/harmonyscore_result1.jpg', grid_img)
Expected result:
.. image:: _static/image/harmonyscore_result1.jpg
:scale: 38 %
"""
def __init__(self, device=0, model_type='BargainNet', **kwargs):
assert model_type in model_set, f'Not implementation for {model_type}'
self.model_type = model_type
self.option = kwargs
weight_path = os.path.join(cur_dir, 'pretrained_models', 'BargainNet.pth')
|
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 building model
Examples:
>>> from libcom import HarmonyScoreModel
>>> from libcom.utils.process_image import make_image_grid
>>> import cv2
>>> net = HarmonyScoreModel(device=0, model_type='BargainNet')
>>> test_dir = '../tests/harmony_score_prediction/'
>>> img_names = ['vaulted-cellar-247391_inharm.jpg', 'ameland-5651866_harm.jpg']
>>> vis_list,scores = [], []
>>> for img_name in img_names:
>>> comp_img = test_dir + 'composite/' + img_name
>>> comp_mask = test_dir + 'composite_mask/' + img_name
>>> score = net(comp_img, comp_mask)
>>> vis_list += [comp_img, comp_mask]
>>> scores.append(score)
>>> grid_img = make_image_grid(vis_list, text_list=[f'harmony_score:{scores[0]:.2f}', 'composite-mask', f'harmony_score:{scores[1]:.2f}', 'composite-mask'])
>>> cv2.imwrite('../docs/_static/image/harmonyscore_result1.jpg', grid_img)
Expected result:
.. image:: _static/image/harmonyscore_result1.jpg
:scale: 38 %
"""
def __init__(self, device=0, model_type='BargainNet', **kwargs):
assert model_type in model_set, f'Not implementation for {model_type}'
self.model_type = model_type
self.option = kwargs
weight_path = os.path.join(cur_dir, 'pretrained_models', 'BargainNet.pth') | 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_provider_with_primitive_kwarg():
dp = SimpleDependencyProvider(x=1)
assert dp["x"] == 1
def test_create_provider_with_class_instance_arg():
service = FooService()
dp = SimpleDependencyProvider(service)
assert dp[FooService] is service
def test_create_provider_with_class_instance_karg():
service = FooService()
dp = SimpleDependencyProvider(service=service)
assert dp[FooService] is service
assert dp["service"] is service
def test_create_provider_with_class_instance_arg_and_kwarg_gets_overridden():
service1 = FooService()
service2 = FooService()
dp = SimpleDependencyProvider(service1, service=service2)
assert dp[FooService] is service2
assert dp["service"] is service2
def test_resolve_custom_primitive_type():
class Email(str):
...
email = Email("john@example.com")
dp = SimpleDependencyProvider(email=email)
assert dp[Email] == email
def test_get_function_parameters():
|
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_provider_with_primitive_kwarg():
dp = SimpleDependencyProvider(x=1)
assert dp["x"] == 1
def test_create_provider_with_class_instance_arg():
service = FooService()
dp = SimpleDependencyProvider(service)
assert dp[FooService] is service
def test_create_provider_with_class_instance_karg():
service = FooService()
dp = SimpleDependencyProvider(service=service)
assert dp[FooService] is service
assert dp["service"] is service
def test_create_provider_with_class_instance_arg_and_kwarg_gets_overridden():
service1 = FooService()
service2 = FooService()
dp = SimpleDependencyProvider(service1, service=service2)
assert dp[FooService] is service2
assert dp["service"] is service2
def test_resolve_custom_primitive_type():
class Email(str):
...
email = Email("john@example.com")
dp = SimpleDependencyProvider(email=email)
assert dp[Email] == email
def test_get_function_parameters(): | 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 or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def test_add_and_can_sample(
fake_transition: chex.ArrayTree,
min_length: int,
max_length: int,
add_batch_size: int,
) -> None:
"""Check the `add` function by filling the buffer all
the way to the max_length and checking that it produces the expected behaviour .
"""
| # 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 or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def test_add_and_can_sample(
fake_transition: chex.ArrayTree,
min_length: int,
max_length: int,
add_batch_size: int,
) -> None:
"""Check the `add` function by filling the buffer all
the way to the max_length and checking that it produces the expected behaviour .
""" | 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_windows_dpi_scaling, get_recordings_dir, name_to_button,
name_to_key) | 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
return False
self.listener.add_comb(("shift", "esc"), stop_comb_pressed)
self.listener.start()
def play(self, recording_path: str):
with open(os.path.join(recording_path, "events.jsonl"), "r") as f:
events = [json.loads(line) for line in f.readlines()]
with open(os.path.join(recording_path, "metadata.json"), "r") as f:
metadata = json.load(f)
self.playback(events, metadata)
def playback(self, events: list[dict], metadata: dict):
if metadata["system"] == "Windows":
fix_windows_dpi_scaling()
mouse_controller = MouseController()
keyboard_controller = KeyboardController()
if not events:
self.listener.stop()
return
presses_to_skip = 0
releases_to_skip = 0
in_click_sequence = False
for i, event in enumerate(events):
start_time = time.perf_counter()
if self.stop_playback:
return
def do_mouse_press(button):
for j, second_event in enumerate(events[i+1:]):
# make sure the time between mouse clicks is less than 500ms
if second_event["time_stamp"] - event["time_stamp"] > 0.5:
break
if "x" in second_event and "y" in second_event:
# if the mouse moves out of the click radius/rectangle, it is not a click sequence
if math.sqrt((second_event["y"] - event["y"]) ** 2 +
(second_event["x"] - event["x"]) ** 2) > 4:
break
if second_event["action"] == "click" and second_event["pressed"]:
for k, third_event in enumerate(events[i+j+2:]):
if third_event["time_stamp"] - second_event["time_stamp"] > 0.5:
break
if "x" in third_event and "y" in third_event:
if math.sqrt((third_event["y"] - event["y"]) ** 2 +
(third_event["x"] - event["x"]) ** 2) > 5:
break
if third_event["action"] == "click" and third_event["pressed"]:
mouse_controller.click(button, 3)
return 2, 2
mouse_controller.click(button, 2)
return 1, 1
mouse_controller.press(button)
return 0, 0
if event["action"] == "move":
mouse_controller.position = (event["x"], event["y"])
elif event["action"] == "click":
button = name_to_button(event["button"])
if event["pressed"]:
if presses_to_skip == 0:
presses, releases = do_mouse_press(button)
presses_to_skip += presses
releases_to_skip += releases
if presses > 0:
in_click_sequence = True
else:
presses_to_skip -= 1
else:
if releases_to_skip == 0:
mouse_controller.release(button)
if in_click_sequence:
keyboard_controller.press(Key.shift)
mouse_controller.click(Button.left)
keyboard_controller.release(Key.shift)
in_click_sequence = False
else:
releases_to_skip -= 1
elif event["action"] == "scroll":
if metadata["system"] == "Windows":
# for some reason on windows, pynput scroll is correct but pyautogui is not
mouse_controller.scroll(metadata["scroll_direction"] * event["dx"], metadata["scroll_direction"] * event["dy"])
else:
pyautogui.hscroll(clicks=metadata["scroll_direction"] * event["dx"])
pyautogui.vscroll(clicks=metadata["scroll_direction"] * event["dy"])
elif event["action"] in ["press", "release"]:
|
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
return False
self.listener.add_comb(("shift", "esc"), stop_comb_pressed)
self.listener.start()
def play(self, recording_path: str):
with open(os.path.join(recording_path, "events.jsonl"), "r") as f:
events = [json.loads(line) for line in f.readlines()]
with open(os.path.join(recording_path, "metadata.json"), "r") as f:
metadata = json.load(f)
self.playback(events, metadata)
def playback(self, events: list[dict], metadata: dict):
if metadata["system"] == "Windows":
fix_windows_dpi_scaling()
mouse_controller = MouseController()
keyboard_controller = KeyboardController()
if not events:
self.listener.stop()
return
presses_to_skip = 0
releases_to_skip = 0
in_click_sequence = False
for i, event in enumerate(events):
start_time = time.perf_counter()
if self.stop_playback:
return
def do_mouse_press(button):
for j, second_event in enumerate(events[i+1:]):
# make sure the time between mouse clicks is less than 500ms
if second_event["time_stamp"] - event["time_stamp"] > 0.5:
break
if "x" in second_event and "y" in second_event:
# if the mouse moves out of the click radius/rectangle, it is not a click sequence
if math.sqrt((second_event["y"] - event["y"]) ** 2 +
(second_event["x"] - event["x"]) ** 2) > 4:
break
if second_event["action"] == "click" and second_event["pressed"]:
for k, third_event in enumerate(events[i+j+2:]):
if third_event["time_stamp"] - second_event["time_stamp"] > 0.5:
break
if "x" in third_event and "y" in third_event:
if math.sqrt((third_event["y"] - event["y"]) ** 2 +
(third_event["x"] - event["x"]) ** 2) > 5:
break
if third_event["action"] == "click" and third_event["pressed"]:
mouse_controller.click(button, 3)
return 2, 2
mouse_controller.click(button, 2)
return 1, 1
mouse_controller.press(button)
return 0, 0
if event["action"] == "move":
mouse_controller.position = (event["x"], event["y"])
elif event["action"] == "click":
button = name_to_button(event["button"])
if event["pressed"]:
if presses_to_skip == 0:
presses, releases = do_mouse_press(button)
presses_to_skip += presses
releases_to_skip += releases
if presses > 0:
in_click_sequence = True
else:
presses_to_skip -= 1
else:
if releases_to_skip == 0:
mouse_controller.release(button)
if in_click_sequence:
keyboard_controller.press(Key.shift)
mouse_controller.click(Button.left)
keyboard_controller.release(Key.shift)
in_click_sequence = False
else:
releases_to_skip -= 1
elif event["action"] == "scroll":
if metadata["system"] == "Windows":
# for some reason on windows, pynput scroll is correct but pyautogui is not
mouse_controller.scroll(metadata["scroll_direction"] * event["dx"], metadata["scroll_direction"] * event["dy"])
else:
pyautogui.hscroll(clicks=metadata["scroll_direction"] * event["dx"])
pyautogui.vscroll(clicks=metadata["scroll_direction"] * event["dy"])
elif event["action"] in ["press", "release"]: | 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.modules.hopenet as hopenet | 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.Sequential()
self.slice3 = torch.nn.Sequential()
self.slice4 = torch.nn.Sequential()
self.slice5 = torch.nn.Sequential()
for x in range(2):
self.slice1.add_module(str(x), vgg_pretrained_features[x])
for x in range(2, 7):
self.slice2.add_module(str(x), vgg_pretrained_features[x])
for x in range(7, 12):
self.slice3.add_module(str(x), vgg_pretrained_features[x])
for x in range(12, 21):
self.slice4.add_module(str(x), vgg_pretrained_features[x])
for x in range(21, 30):
self.slice5.add_module(str(x), vgg_pretrained_features[x])
self.mean = torch.nn.Parameter(data=torch.Tensor(np.array([0.485, 0.456, 0.406]).reshape((1, 3, 1, 1))),
requires_grad=False)
self.std = torch.nn.Parameter(data=torch.Tensor(np.array([0.229, 0.224, 0.225]).reshape((1, 3, 1, 1))),
requires_grad=False)
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
def forward(self, X):
X = (X - self.mean) / self.std
h_relu1 = self.slice1(X)
h_relu2 = self.slice2(h_relu1)
h_relu3 = self.slice3(h_relu2)
h_relu4 = self.slice4(h_relu3)
h_relu5 = self.slice5(h_relu4)
out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]
return out
class ImagePyramide(torch.nn.Module):
"""
Create image pyramide for computing pyramide perceptual loss.
"""
def __init__(self, scales, num_channels):
super(ImagePyramide, self).__init__()
downs = {}
for scale in scales:
|
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.Sequential()
self.slice3 = torch.nn.Sequential()
self.slice4 = torch.nn.Sequential()
self.slice5 = torch.nn.Sequential()
for x in range(2):
self.slice1.add_module(str(x), vgg_pretrained_features[x])
for x in range(2, 7):
self.slice2.add_module(str(x), vgg_pretrained_features[x])
for x in range(7, 12):
self.slice3.add_module(str(x), vgg_pretrained_features[x])
for x in range(12, 21):
self.slice4.add_module(str(x), vgg_pretrained_features[x])
for x in range(21, 30):
self.slice5.add_module(str(x), vgg_pretrained_features[x])
self.mean = torch.nn.Parameter(data=torch.Tensor(np.array([0.485, 0.456, 0.406]).reshape((1, 3, 1, 1))),
requires_grad=False)
self.std = torch.nn.Parameter(data=torch.Tensor(np.array([0.229, 0.224, 0.225]).reshape((1, 3, 1, 1))),
requires_grad=False)
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
def forward(self, X):
X = (X - self.mean) / self.std
h_relu1 = self.slice1(X)
h_relu2 = self.slice2(h_relu1)
h_relu3 = self.slice3(h_relu2)
h_relu4 = self.slice4(h_relu3)
h_relu5 = self.slice5(h_relu4)
out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]
return out
class ImagePyramide(torch.nn.Module):
"""
Create image pyramide for computing pyramide perceptual loss.
"""
def __init__(self, scales, num_channels):
super(ImagePyramide, self).__init__()
downs = {}
for scale in scales: | 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 timezone or it will use system timezone by default!!!"
)
CRON_TRIGGER = os.getenv("CRON_TRIGGER", "0 0 * * *")
next_cron_time = (
croniter(CRON_TRIGGER, datetime.now(timezone.utc))
.get_next(datetime)
.replace(tzinfo=timezone.utc)
.astimezone()
)
dtd = etree.DTD(open("xmltv.dtd", "r"))
now = datetime.now()
current_timezone = now.astimezone().tzinfo
timezone_name = current_timezone.tzname(now)
timezone_offset = now.astimezone().strftime("%z")
print("use timezone:", timezone_name, f"UTC{timezone_offset}", flush=True)
config_path = os.path.join(os.getcwd(), "config", "channels.yaml")
epg_path = os.path.join(os.getcwd(), "web", "epg.xml")
if not os.path.exists(os.path.join(os.getcwd(), "web")):
os.mkdir(os.path.join(os.getcwd(), "web"))
channels = utils.load_config(config_path)
if XMLTV_URL == "":
xml_channels = []
print("!!!Please set XMLTV_URL environment variables to reuse XML!!!")
else:
print("reuse XML:", XMLTV_URL, flush=True)
|
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 timezone or it will use system timezone by default!!!"
)
CRON_TRIGGER = os.getenv("CRON_TRIGGER", "0 0 * * *")
next_cron_time = (
croniter(CRON_TRIGGER, datetime.now(timezone.utc))
.get_next(datetime)
.replace(tzinfo=timezone.utc)
.astimezone()
)
dtd = etree.DTD(open("xmltv.dtd", "r"))
now = datetime.now()
current_timezone = now.astimezone().tzinfo
timezone_name = current_timezone.tzname(now)
timezone_offset = now.astimezone().strftime("%z")
print("use timezone:", timezone_name, f"UTC{timezone_offset}", flush=True)
config_path = os.path.join(os.getcwd(), "config", "channels.yaml")
epg_path = os.path.join(os.getcwd(), "web", "epg.xml")
if not os.path.exists(os.path.join(os.getcwd(), "web")):
os.mkdir(os.path.join(os.getcwd(), "web"))
channels = utils.load_config(config_path)
if XMLTV_URL == "":
xml_channels = []
print("!!!Please set XMLTV_URL environment variables to reuse XML!!!")
else:
print("reuse XML:", XMLTV_URL, flush=True) | 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):
self.X_prefix = self.format_s.split('\n')[0].split(':')[0] + ':'
self.Y_prefix = self.format_s.split('\n')[1].split(':')[0] + ':'
def get_empty_demo_context(self, context: str, only_demo_part=True):
context = context.split('\n')
for i, line in enumerate(context[:-2]):
if self.X_prefix in line:
line = self.X_prefix
elif self.Y_prefix in line:
line = line
else:
raise warnings.warn('Global prefix or other str exists!')
context[i] = line
if only_demo_part:
context = context[:-2]
context = '\n'.join(context)
return context
def get_mask_strings_and_match_before(self, context, input_ids, tokenizer=None):
if tokenizer is None:
tokenizer = self.tokenizer
poss = torch.where(input_ids == tokenizer.encode('\n', add_special_tokens=False)[0])[0]
if len(poss) >= 2:
match_before = poss[-2] + 1
else:
match_before = None
list_s = []
list_s.append(self.X_prefix)
list_s.append('\n' + self.X_prefix)
context = context.split('\n')
for i, line in enumerate(context[:-2]):
if self.X_prefix in line:
pass
elif self.Y_prefix in line:
list_s.append('\n' + line)
list_s.append('\n' + line + '\n')
else:
raise warnings.warn('Global prefix or other str exists!')
return list_s, match_before
def get_mask(self, input_ids, tokenizer=None):
if isinstance(input_ids, list):
input_ids = torch.tensor(input_ids)
if len(input_ids.shape) == 2:
assert input_ids.shape[0] == 1
input_ids = input_ids[0]
if tokenizer is None:
tokenizer = self.tokenizer
context = tokenizer.decode(input_ids)
list_s, match_before = self.get_mask_strings_and_match_before(context, input_ids=input_ids,
tokenizer=tokenizer)
|
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):
self.X_prefix = self.format_s.split('\n')[0].split(':')[0] + ':'
self.Y_prefix = self.format_s.split('\n')[1].split(':')[0] + ':'
def get_empty_demo_context(self, context: str, only_demo_part=True):
context = context.split('\n')
for i, line in enumerate(context[:-2]):
if self.X_prefix in line:
line = self.X_prefix
elif self.Y_prefix in line:
line = line
else:
raise warnings.warn('Global prefix or other str exists!')
context[i] = line
if only_demo_part:
context = context[:-2]
context = '\n'.join(context)
return context
def get_mask_strings_and_match_before(self, context, input_ids, tokenizer=None):
if tokenizer is None:
tokenizer = self.tokenizer
poss = torch.where(input_ids == tokenizer.encode('\n', add_special_tokens=False)[0])[0]
if len(poss) >= 2:
match_before = poss[-2] + 1
else:
match_before = None
list_s = []
list_s.append(self.X_prefix)
list_s.append('\n' + self.X_prefix)
context = context.split('\n')
for i, line in enumerate(context[:-2]):
if self.X_prefix in line:
pass
elif self.Y_prefix in line:
list_s.append('\n' + line)
list_s.append('\n' + line + '\n')
else:
raise warnings.warn('Global prefix or other str exists!')
return list_s, match_before
def get_mask(self, input_ids, tokenizer=None):
if isinstance(input_ids, list):
input_ids = torch.tensor(input_ids)
if len(input_ids.shape) == 2:
assert input_ids.shape[0] == 1
input_ids = input_ids[0]
if tokenizer is None:
tokenizer = self.tokenizer
context = tokenizer.decode(input_ids)
list_s, match_before = self.get_mask_strings_and_match_before(context, input_ids=input_ids,
tokenizer=tokenizer) | 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"]]}
}
def test_or_operator_with_multiple_conditions_more_than_rwo(self):
q1 = Q(name="John")
q2 = Q(name="Alice")
q3 = Q(name="Bob")
q_combined = q1 | q2 | q3
assert dict(q_combined) == {
"$match": {
"$or": [dict(q1)["$match"], dict(q2)["$match"], dict(q3)["$match"]]
}
}
def test_and(self):
q1 = Q(name="Mahdi")
q2 = Q(age__gt=20)
q = q1 & q2
assert dict(q) == {"$match": {"$and": [dict(q1)["$match"], dict(q2)["$match"]]}}
def test_multiple_and(self):
q1 = Q(name="Mahdi")
q2 = Q(age__gt=20)
q3 = Q(age__lt=30)
q = q1 & q2 & q3
assert dict(q) == {
"$match": {
"$and": [dict(q1)["$match"], dict(q2)["$match"], dict(q3)["$match"]]
}
}
# Test combining NOT operators with AND
def test_combine_not_operators_with_and(self):
q1 = Q(name="John")
q2 = Q(age__lt=30)
q_combined = ~q1 & ~q2
assert dict(q_combined) == {
"$match": {
"$and": [{"$not": [dict(q1)["$match"]]}, {"$not": [dict(q2)["$match"]]}]
}
}
# Test combining NOT operators with OR
def test_combine_not_operators_with_or(self):
q1 = Q(name="John")
q2 = Q(age__lt=30)
q_combined = ~q1 | ~q2 # Changed | to combine OR
assert dict(q_combined) == {
"$match": {
"$or": [{"$not": [dict(q1)["$match"]]}, {"$not": [dict(q2)["$match"]]}]
}
}
def test_unsuitable_key_for_f(self):
|
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"]]}
}
def test_or_operator_with_multiple_conditions_more_than_rwo(self):
q1 = Q(name="John")
q2 = Q(name="Alice")
q3 = Q(name="Bob")
q_combined = q1 | q2 | q3
assert dict(q_combined) == {
"$match": {
"$or": [dict(q1)["$match"], dict(q2)["$match"], dict(q3)["$match"]]
}
}
def test_and(self):
q1 = Q(name="Mahdi")
q2 = Q(age__gt=20)
q = q1 & q2
assert dict(q) == {"$match": {"$and": [dict(q1)["$match"], dict(q2)["$match"]]}}
def test_multiple_and(self):
q1 = Q(name="Mahdi")
q2 = Q(age__gt=20)
q3 = Q(age__lt=30)
q = q1 & q2 & q3
assert dict(q) == {
"$match": {
"$and": [dict(q1)["$match"], dict(q2)["$match"], dict(q3)["$match"]]
}
}
# Test combining NOT operators with AND
def test_combine_not_operators_with_and(self):
q1 = Q(name="John")
q2 = Q(age__lt=30)
q_combined = ~q1 & ~q2
assert dict(q_combined) == {
"$match": {
"$and": [{"$not": [dict(q1)["$match"]]}, {"$not": [dict(q2)["$match"]]}]
}
}
# Test combining NOT operators with OR
def test_combine_not_operators_with_or(self):
q1 = Q(name="John")
q2 = Q(age__lt=30)
q_combined = ~q1 | ~q2 # Changed | to combine OR
assert dict(q_combined) == {
"$match": {
"$or": [{"$not": [dict(q1)["$match"]]}, {"$not": [dict(q2)["$match"]]}]
}
}
def test_unsuitable_key_for_f(self): | 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:
john_profile = _get_john_profile
background = get_bio(
|
@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:
john_profile = _get_john_profile
background = get_bio( | 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,
)
from .utils import async_get_binary_path, get_model_slug | 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-4", "needs_arkose_token": True},
"gpt-3.5": {"slug": "text-davinci-002-render-sha", "needs_arkose_token": False},
}
class AsyncConversation:
def __init__(self, chatgpt, conversation_id=None, model=None):
self.chatgpt = chatgpt
self.conversation_id = conversation_id
self.parent_id = None
self.model = model
async def fetch_chat(self) -> dict:
"""
Fetches the chat of the conversation from the API.
Returns:
dict: The JSON response from the API containing the chat if the conversation_id is not none, else returns an empty dict.
Raises:
UnexpectedResponseError: If the response is not a valid JSON object or if the response json is not in the expected format
"""
if not self.conversation_id:
return {}
url = CHATGPT_API.format(f"conversation/{self.conversation_id}")
response = await self.chatgpt.session.get(
url=url, headers=self.chatgpt.build_request_headers()
)
error = None
try:
chat = response.json()
self.parent_id = list(chat.get("mapping", {}))[-1]
model_slug = get_model_slug(chat)
self.model = [
key for key, value in MODELS.items() if value["slug"] == model_slug
][0]
except Exception as e:
error = e
if error is not None:
|
# 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-4", "needs_arkose_token": True},
"gpt-3.5": {"slug": "text-davinci-002-render-sha", "needs_arkose_token": False},
}
class AsyncConversation:
def __init__(self, chatgpt, conversation_id=None, model=None):
self.chatgpt = chatgpt
self.conversation_id = conversation_id
self.parent_id = None
self.model = model
async def fetch_chat(self) -> dict:
"""
Fetches the chat of the conversation from the API.
Returns:
dict: The JSON response from the API containing the chat if the conversation_id is not none, else returns an empty dict.
Raises:
UnexpectedResponseError: If the response is not a valid JSON object or if the response json is not in the expected format
"""
if not self.conversation_id:
return {}
url = CHATGPT_API.format(f"conversation/{self.conversation_id}")
response = await self.chatgpt.session.get(
url=url, headers=self.chatgpt.build_request_headers()
)
error = None
try:
chat = response.json()
self.parent_id = list(chat.get("mapping", {}))[-1]
model_slug = get_model_slug(chat)
self.model = [
key for key, value in MODELS.items() if value["slug"] == model_slug
][0]
except Exception as e:
error = e
if error is not None: | 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, BillSerializer
from organization.models import Bill
from test_utils import create_user, create_superuser, create_key, create_organizations, \
create_plans, create_bill | 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)
cls.su = create_superuser('admin', '12345678', cls.org1)
cls.key = create_key('key', cls.user1)
cls.plan1, cls.plan2 = create_plans('Plan', 2)
def setUp(self):
self.bill1 = create_bill(self.org1, self.plan1, date.today().replace(day=1))
self.bill2 = create_bill(self.org2, self.plan1, date.today().replace(day=1))
self.bill3 = create_bill(self.org1, self.plan1,
date.today().replace(day=1) - relativedelta(months=1))
def tearDown(self):
|
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)
cls.su = create_superuser('admin', '12345678', cls.org1)
cls.key = create_key('key', cls.user1)
cls.plan1, cls.plan2 = create_plans('Plan', 2)
def setUp(self):
self.bill1 = create_bill(self.org1, self.plan1, date.today().replace(day=1))
self.bill2 = create_bill(self.org2, self.plan1, date.today().replace(day=1))
self.bill3 = create_bill(self.org1, self.plan1,
date.today().replace(day=1) - relativedelta(months=1))
def tearDown(self): | 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 geometric
product of the reverse of x with y.
Both the scalar component of the GP, and the reversal matrix, are diagonal.
Their product is 0 for basis elements involving e0, and 1 elsewhere, i.e.
IP = [1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0]
for dim order '', 'e0', 'e1', 'e2', 'e3', 'e01', 'e02', 'e03', 'e12', 'e13', 'e23',
'e012', 'e013', 'e023', 'e123', 'e0123'
Parameters
----------
device : torch.device
Device
Returns
-------
ip_mask : torch.Tensor with shape (16,)
Inner product mask
"""
gp = _load_bilinear_basis("gp", device=device, dtype=torch.float32)
| # 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 geometric
product of the reverse of x with y.
Both the scalar component of the GP, and the reversal matrix, are diagonal.
Their product is 0 for basis elements involving e0, and 1 elsewhere, i.e.
IP = [1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0]
for dim order '', 'e0', 'e1', 'e2', 'e3', 'e01', 'e02', 'e03', 'e12', 'e13', 'e23',
'e012', 'e013', 'e023', 'e123', 'e0123'
Parameters
----------
device : torch.device
Device
Returns
-------
ip_mask : torch.Tensor with shape (16,)
Inner product mask
"""
gp = _load_bilinear_basis("gp", device=device, dtype=torch.float32) | 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
self.scale = glm.vec3(WEAPON_SCALE / ASPECT_RATIO, WEAPON_SCALE, 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.scale = glm.vec3(WEAPON_SCALE / ASPECT_RATIO, WEAPON_SCALE, 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
from pytorch3d.io import load_obj, load_objs_as_meshes, save_obj | 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__()
self.radius = radius
self.k = k
self.max_neigh_num = 40
self.sampling_strategy = sampling_strategy
self.one_ring_neigh = []
self.nodes_idx = None
self.weights = None
self.influence_nodes_idx = []
self.dists = []
self.vert_number = vert_number
def construct_graph(self, category_name, vertices=None, faces=None):
transform_fp = "transform_{}.pkl".format(category_name)
if self.sampling_strategy == 'qslim':
m = Mesh(v=vertices, f=faces)
if os.path.exists(transform_fp):
with open(transform_fp, 'rb') as f:
tmp = pickle.load(f, encoding='latin1')
M, A, D = tmp['M'], tmp['A'], tmp['D']
else:
| # 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__()
self.radius = radius
self.k = k
self.max_neigh_num = 40
self.sampling_strategy = sampling_strategy
self.one_ring_neigh = []
self.nodes_idx = None
self.weights = None
self.influence_nodes_idx = []
self.dists = []
self.vert_number = vert_number
def construct_graph(self, category_name, vertices=None, faces=None):
transform_fp = "transform_{}.pkl".format(category_name)
if self.sampling_strategy == 'qslim':
m = Mesh(v=vertices, f=faces)
if os.path.exists(transform_fp):
with open(transform_fp, 'rb') as f:
tmp = pickle.load(f, encoding='latin1')
M, A, D = tmp['M'], tmp['A'], tmp['D']
else: | 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 not in pred_ids:
fn += 1
return tp, fp, fn
def compute_edit_sim(samples):
refs, hyps = [], []
for s in samples:
refs.append(s["target"])
hyps.append(s["pred"])
return cal_edit_sim(refs, hyps)
def process_examples(lang, args):
sample, ex = args
global parser
prediction = postprocess_code_lines(ex["prompt"], sample["pred"], parser, lang)
prediction = remove_comments(prediction)
target = ex["groundtruth"]
target = remove_comments(target)
pred_lines = [l.strip() for l in prediction.split("\n") if l.strip()]
gt_lines = [l.strip() for l in target.split("\n") if l.strip()]
em_label = int(pred_lines == gt_lines)
|
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 not in pred_ids:
fn += 1
return tp, fp, fn
def compute_edit_sim(samples):
refs, hyps = [], []
for s in samples:
refs.append(s["target"])
hyps.append(s["pred"])
return cal_edit_sim(refs, hyps)
def process_examples(lang, args):
sample, ex = args
global parser
prediction = postprocess_code_lines(ex["prompt"], sample["pred"], parser, lang)
prediction = remove_comments(prediction)
target = ex["groundtruth"]
target = remove_comments(target)
pred_lines = [l.strip() for l in prediction.split("\n") if l.strip()]
gt_lines = [l.strip() for l in target.split("\n") if l.strip()]
em_label = int(pred_lines == gt_lines)
| 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
self.prompt0 = read_text("ailice.prompts", "prompt_searchengine.txt")
self.PATTERNS = {"QUERY": [{"re": GenerateRE4FunctionCalling("QUERY<!|request: str|!> -> str", faultTolerance = True), "isEntry": True}],
"ARXIV": [{"re": GenerateRE4FunctionCalling("ARXIV<!|keywords: str|!> -> str", faultTolerance = True), "isEntry": True}],
"SCROLLDOWNARXIV": [{"re": GenerateRE4FunctionCalling("SCROLLDOWNARXIV<!||!> -> str", faultTolerance = True), "isEntry": True}],
"GOOGLE": [{"re": GenerateRE4FunctionCalling("GOOGLE<!|keywords: str|!> -> str", faultTolerance = True), "isEntry": True}],
"SCROLLDOWNGOOGLE": [{"re": GenerateRE4FunctionCalling("SCROLLDOWNGOOGLE<!||!> -> str", faultTolerance = True), "isEntry": True}],
"DUCKDUCKGO": [{"re": GenerateRE4FunctionCalling("DUCKDUCKGO<!|keywords: str|!> -> str", faultTolerance = True), "isEntry": True}],
"SCROLLDOWNDUCKDUCKGO": [{"re": GenerateRE4FunctionCalling("SCROLLDOWNDUCKDUCKGO<!||!> -> str", faultTolerance = True), "isEntry": True}],
"BROWSE": [{"re": GenerateRE4FunctionCalling("BROWSE<!|url: str|!> -> str", faultTolerance = True), "isEntry": True}],
"SCROLLDOWN": [{"re": GenerateRE4FunctionCalling("SCROLLDOWN<!||!> -> str"), "isEntry": True}],
"RESPOND": [{"re": GenerateRE4FunctionCalling("RESPOND<!|message: str|!> -> None", faultTolerance = True), "isEntry": True}]}
self.ACTIONS= {}
return
def Reset(self):
return
def GetPatterns(self):
return self.PATTERNS
def GetActions(self):
return self.ACTIONS
def ParameterizedBuildPrompt(self, n: int):
prompt = f"""
{self.prompt0}
End of general instructions.
"""
#prompt += "Conversations:"
ret = self.formatter(prompt0 = prompt, conversations = self.conversations.GetConversations(frm = -n))
return ret, self.formatter.Len(ret)
def BuildPrompt(self):
|
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
self.prompt0 = read_text("ailice.prompts", "prompt_searchengine.txt")
self.PATTERNS = {"QUERY": [{"re": GenerateRE4FunctionCalling("QUERY<!|request: str|!> -> str", faultTolerance = True), "isEntry": True}],
"ARXIV": [{"re": GenerateRE4FunctionCalling("ARXIV<!|keywords: str|!> -> str", faultTolerance = True), "isEntry": True}],
"SCROLLDOWNARXIV": [{"re": GenerateRE4FunctionCalling("SCROLLDOWNARXIV<!||!> -> str", faultTolerance = True), "isEntry": True}],
"GOOGLE": [{"re": GenerateRE4FunctionCalling("GOOGLE<!|keywords: str|!> -> str", faultTolerance = True), "isEntry": True}],
"SCROLLDOWNGOOGLE": [{"re": GenerateRE4FunctionCalling("SCROLLDOWNGOOGLE<!||!> -> str", faultTolerance = True), "isEntry": True}],
"DUCKDUCKGO": [{"re": GenerateRE4FunctionCalling("DUCKDUCKGO<!|keywords: str|!> -> str", faultTolerance = True), "isEntry": True}],
"SCROLLDOWNDUCKDUCKGO": [{"re": GenerateRE4FunctionCalling("SCROLLDOWNDUCKDUCKGO<!||!> -> str", faultTolerance = True), "isEntry": True}],
"BROWSE": [{"re": GenerateRE4FunctionCalling("BROWSE<!|url: str|!> -> str", faultTolerance = True), "isEntry": True}],
"SCROLLDOWN": [{"re": GenerateRE4FunctionCalling("SCROLLDOWN<!||!> -> str"), "isEntry": True}],
"RESPOND": [{"re": GenerateRE4FunctionCalling("RESPOND<!|message: str|!> -> None", faultTolerance = True), "isEntry": True}]}
self.ACTIONS= {}
return
def Reset(self):
return
def GetPatterns(self):
return self.PATTERNS
def GetActions(self):
return self.ACTIONS
def ParameterizedBuildPrompt(self, n: int):
prompt = f"""
{self.prompt0}
End of general instructions.
"""
#prompt += "Conversations:"
ret = self.formatter(prompt0 = prompt, conversations = self.conversations.GetConversations(frm = -n))
return ret, self.formatter.Len(ret)
def BuildPrompt(self): | 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
self.conversation_id: str = conversation_id
self.conversation_signature: str = conversation_signature
self.encrypted_conversation_signature: str = encrypted_conversation_signature
self.invocation_id: int = invocation_id
def update(
self,
prompt: str,
conversation_style: CONVERSATION_STYLE_TYPE,
webpage_context: Union[str, None] = None,
search_result: bool = False,
|
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
self.conversation_id: str = conversation_id
self.conversation_signature: str = conversation_signature
self.encrypted_conversation_signature: str = encrypted_conversation_signature
self.invocation_id: int = invocation_id
def update(
self,
prompt: str,
conversation_style: CONVERSATION_STYLE_TYPE,
webpage_context: Union[str, None] = None,
search_result: bool = False, | 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 + OTHER_METHODS
class Interpolator1D(eqx.Module):
"""Convenience class for representing a 1D interpolated function.
Parameters
----------
x : ndarray, shape(Nx,)
coordinates of known function values ("knots")
f : ndarray, shape(Nx,...)
function values to interpolate
method : str
method of interpolation
- ``'nearest'``: nearest neighbor interpolation
- ``'linear'``: linear interpolation
- ``'cubic'``: C1 cubic splines (aka local splines)
- ``'cubic2'``: C2 cubic splines (aka natural splines)
- ``'catmull-rom'``: C1 cubic centripetal "tension" splines
- ``'cardinal'``: C1 cubic general tension splines. If used, can also pass
keyword parameter ``c`` in float[0,1] to specify tension
- ``'monotonic'``: C1 cubic splines that attempt to preserve monotonicity in the
data, and will not introduce new extrema in the interpolated points
- ``'monotonic-0'``: same as ``'monotonic'`` but with 0 first derivatives at
both endpoints
extrap : bool, float, array-like
whether to extrapolate values beyond knots (True) or return nan (False),
or a specified value to return for query points outside the bounds. Can
also be passed as a 2 element array or tuple to specify different conditions
for xq<x[0] and x[-1]<xq
period : float > 0, None
periodicity of the function. If given, function is assumed to be periodic
on the interval [0,period]. None denotes no periodicity
Notes
-----
This class is registered as a PyTree in JAX (it is actually an equinox.Module)
so should be compatible with standard JAX transformations (jit, grad, vmap, etc.)
"""
x: jax.Array
f: jax.Array
derivs: dict
method: str
extrap: Union[bool, float, tuple]
period: Union[None, float]
axis: int
def __init__(
self,
x: jax.Array,
f: jax.Array,
method: str = "cubic",
extrap: Union[bool, float, tuple] = False,
period: Union[None, float] = None,
**kwargs,
):
x, f = map(jnp.asarray, (x, f))
axis = kwargs.get("axis", 0)
fx = kwargs.pop("fx", None)
| """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 + OTHER_METHODS
class Interpolator1D(eqx.Module):
"""Convenience class for representing a 1D interpolated function.
Parameters
----------
x : ndarray, shape(Nx,)
coordinates of known function values ("knots")
f : ndarray, shape(Nx,...)
function values to interpolate
method : str
method of interpolation
- ``'nearest'``: nearest neighbor interpolation
- ``'linear'``: linear interpolation
- ``'cubic'``: C1 cubic splines (aka local splines)
- ``'cubic2'``: C2 cubic splines (aka natural splines)
- ``'catmull-rom'``: C1 cubic centripetal "tension" splines
- ``'cardinal'``: C1 cubic general tension splines. If used, can also pass
keyword parameter ``c`` in float[0,1] to specify tension
- ``'monotonic'``: C1 cubic splines that attempt to preserve monotonicity in the
data, and will not introduce new extrema in the interpolated points
- ``'monotonic-0'``: same as ``'monotonic'`` but with 0 first derivatives at
both endpoints
extrap : bool, float, array-like
whether to extrapolate values beyond knots (True) or return nan (False),
or a specified value to return for query points outside the bounds. Can
also be passed as a 2 element array or tuple to specify different conditions
for xq<x[0] and x[-1]<xq
period : float > 0, None
periodicity of the function. If given, function is assumed to be periodic
on the interval [0,period]. None denotes no periodicity
Notes
-----
This class is registered as a PyTree in JAX (it is actually an equinox.Module)
so should be compatible with standard JAX transformations (jit, grad, vmap, etc.)
"""
x: jax.Array
f: jax.Array
derivs: dict
method: str
extrap: Union[bool, float, tuple]
period: Union[None, float]
axis: int
def __init__(
self,
x: jax.Array,
f: jax.Array,
method: str = "cubic",
extrap: Union[bool, float, tuple] = False,
period: Union[None, float] = None,
**kwargs,
):
x, f = map(jnp.asarray, (x, f))
axis = kwargs.get("axis", 0)
fx = kwargs.pop("fx", None)
| 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.latents import chunk_batch, merge_chunks
from coreml_suite.lcm.utils import is_lcm
from coreml_suite.logger import logger | 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.chunks(self.expected_inputs)
chunked_out = [
self.get_torch_outputs(
self.coreml_model(**input_kwargs.coreml_kwargs(self.expected_inputs)),
x.device,
)
for input_kwargs in input_list
]
merged_out = merge_chunks(chunked_out, x.shape)
return merged_out
@staticmethod
def get_torch_outputs(model_output, device):
return torch.from_numpy(model_output["noise_pred"]).to(device)
@property
def expected_inputs(self):
return self.coreml_model.expected_inputs
@property
def is_lcm(self):
return is_lcm(self.coreml_model)
@property
def is_sdxl_base(self):
return is_sdxl_base(self.coreml_model)
@property
def is_sdxl_refiner(self):
return is_sdxl_refiner(self.coreml_model)
@property
def config(self):
if self.is_sdxl_base:
return get_model_config(ModelVersion.SDXL)
if self.is_sdxl_refiner:
return get_model_config(ModelVersion.SDXL_REFINER)
return get_model_config(ModelVersion.SD15)
class CoreMLModelWrapperLCM(CoreMLModelWrapper):
def __init__(self, coreml_model):
super().__init__(coreml_model)
self.config = None
class CoreMLInputs:
def __init__(self, x, t, context, control, **kwargs):
self.x = x
self.t = t
self.context = context
self.control = control
self.time_ids = kwargs.get("time_ids")
self.text_embeds = kwargs.get("text_embeds")
self.ts_cond = kwargs.get("timestep_cond")
def coreml_kwargs(self, expected_inputs):
sample = self.x.cpu().numpy().astype(np.float16)
context = self.context.cpu().numpy().astype(np.float16)
context = context.transpose(0, 2, 1)[:, :, None, :]
t = self.t.cpu().numpy().astype(np.float16)
model_input_kwargs = {
"sample": sample,
"encoder_hidden_states": context,
"timestep": t,
}
|
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.chunks(self.expected_inputs)
chunked_out = [
self.get_torch_outputs(
self.coreml_model(**input_kwargs.coreml_kwargs(self.expected_inputs)),
x.device,
)
for input_kwargs in input_list
]
merged_out = merge_chunks(chunked_out, x.shape)
return merged_out
@staticmethod
def get_torch_outputs(model_output, device):
return torch.from_numpy(model_output["noise_pred"]).to(device)
@property
def expected_inputs(self):
return self.coreml_model.expected_inputs
@property
def is_lcm(self):
return is_lcm(self.coreml_model)
@property
def is_sdxl_base(self):
return is_sdxl_base(self.coreml_model)
@property
def is_sdxl_refiner(self):
return is_sdxl_refiner(self.coreml_model)
@property
def config(self):
if self.is_sdxl_base:
return get_model_config(ModelVersion.SDXL)
if self.is_sdxl_refiner:
return get_model_config(ModelVersion.SDXL_REFINER)
return get_model_config(ModelVersion.SD15)
class CoreMLModelWrapperLCM(CoreMLModelWrapper):
def __init__(self, coreml_model):
super().__init__(coreml_model)
self.config = None
class CoreMLInputs:
def __init__(self, x, t, context, control, **kwargs):
self.x = x
self.t = t
self.context = context
self.control = control
self.time_ids = kwargs.get("time_ids")
self.text_embeds = kwargs.get("text_embeds")
self.ts_cond = kwargs.get("timestep_cond")
def coreml_kwargs(self, expected_inputs):
sample = self.x.cpu().numpy().astype(np.float16)
context = self.context.cpu().numpy().astype(np.float16)
context = context.transpose(0, 2, 1)[:, :, None, :]
t = self.t.cpu().numpy().astype(np.float16)
model_input_kwargs = {
"sample": sample,
"encoder_hidden_states": context,
"timestep": t,
} | 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.dropout = nn.Dropout(attention_dropout)
def forward(self, queries, keys, values, attn_mask):
B, L, H, E = queries.shape
_, S, _, D = values.shape
scale = self.scale or 1. / sqrt(E)
scores = torch.einsum("blhe,bshe->bhls", queries, keys)
if self.mask_flag:
if attn_mask is None:
attn_mask = TriangularCausalMask(B, L, device=queries.device)
scores.masked_fill_(attn_mask.mask, -np.inf)
A = self.dropout(torch.softmax(scale * scores, dim=-1))
V = torch.einsum("bhls,bshd->blhd", A, values)
if self.output_attention:
return (V.contiguous(), A)
else:
return (V.contiguous(), None)
class ProbAttention(nn.Module):
def __init__(self, mask_flag=True, factor=5, scale=None, attention_dropout=0.1, output_attention=False):
super(ProbAttention, self).__init__()
self.factor = factor
self.scale = scale
self.mask_flag = mask_flag
self.output_attention = output_attention
self.dropout = nn.Dropout(attention_dropout)
def _prob_QK(self, Q, K, sample_k, n_top): # n_top: c*ln(L_q)
# Q [B, H, L, D]
B, H, L_K, E = K.shape
_, _, L_Q, _ = Q.shape
# calculate the sampled Q_K
K_expand = K.unsqueeze(-3).expand(B, H, L_Q, L_K, E)
index_sample = torch.randint(L_K, (L_Q, sample_k)) # real U = U_part(factor*ln(L_k))*L_q
K_sample = K_expand[:, :, torch.arange(L_Q).unsqueeze(1), index_sample, :]
Q_K_sample = torch.matmul(Q.unsqueeze(-2), K_sample.transpose(-2, -1)).squeeze()
# find the Top_k query with sparisty measurement
M = Q_K_sample.max(-1)[0] - torch.div(Q_K_sample.sum(-1), L_K)
M_top = M.topk(n_top, sorted=False)[1]
# use the reduced Q to calculate Q_K
Q_reduce = Q[torch.arange(B)[:, None, None],
torch.arange(H)[None, :, None],
M_top, :] # factor*ln(L_q)
Q_K = torch.matmul(Q_reduce, K.transpose(-2, -1)) # factor*ln(L_q)*L_k
return Q_K, M_top
def _get_initial_context(self, V, L_Q):
B, H, L_V, D = V.shape
if not self.mask_flag:
# V_sum = V.sum(dim=-2)
V_sum = V.mean(dim=-2)
contex = V_sum.unsqueeze(-2).expand(B, H, L_Q, V_sum.shape[-1]).clone()
else: # use mask
assert (L_Q == L_V) # requires that L_Q == L_V, i.e. for self-attention only
contex = V.cumsum(dim=-2)
return contex
def _update_context(self, context_in, V, scores, index, L_Q, attn_mask):
B, H, L_V, D = V.shape
if self.mask_flag:
|
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.dropout = nn.Dropout(attention_dropout)
def forward(self, queries, keys, values, attn_mask):
B, L, H, E = queries.shape
_, S, _, D = values.shape
scale = self.scale or 1. / sqrt(E)
scores = torch.einsum("blhe,bshe->bhls", queries, keys)
if self.mask_flag:
if attn_mask is None:
attn_mask = TriangularCausalMask(B, L, device=queries.device)
scores.masked_fill_(attn_mask.mask, -np.inf)
A = self.dropout(torch.softmax(scale * scores, dim=-1))
V = torch.einsum("bhls,bshd->blhd", A, values)
if self.output_attention:
return (V.contiguous(), A)
else:
return (V.contiguous(), None)
class ProbAttention(nn.Module):
def __init__(self, mask_flag=True, factor=5, scale=None, attention_dropout=0.1, output_attention=False):
super(ProbAttention, self).__init__()
self.factor = factor
self.scale = scale
self.mask_flag = mask_flag
self.output_attention = output_attention
self.dropout = nn.Dropout(attention_dropout)
def _prob_QK(self, Q, K, sample_k, n_top): # n_top: c*ln(L_q)
# Q [B, H, L, D]
B, H, L_K, E = K.shape
_, _, L_Q, _ = Q.shape
# calculate the sampled Q_K
K_expand = K.unsqueeze(-3).expand(B, H, L_Q, L_K, E)
index_sample = torch.randint(L_K, (L_Q, sample_k)) # real U = U_part(factor*ln(L_k))*L_q
K_sample = K_expand[:, :, torch.arange(L_Q).unsqueeze(1), index_sample, :]
Q_K_sample = torch.matmul(Q.unsqueeze(-2), K_sample.transpose(-2, -1)).squeeze()
# find the Top_k query with sparisty measurement
M = Q_K_sample.max(-1)[0] - torch.div(Q_K_sample.sum(-1), L_K)
M_top = M.topk(n_top, sorted=False)[1]
# use the reduced Q to calculate Q_K
Q_reduce = Q[torch.arange(B)[:, None, None],
torch.arange(H)[None, :, None],
M_top, :] # factor*ln(L_q)
Q_K = torch.matmul(Q_reduce, K.transpose(-2, -1)) # factor*ln(L_q)*L_k
return Q_K, M_top
def _get_initial_context(self, V, L_Q):
B, H, L_V, D = V.shape
if not self.mask_flag:
# V_sum = V.sum(dim=-2)
V_sum = V.mean(dim=-2)
contex = V_sum.unsqueeze(-2).expand(B, H, L_Q, V_sum.shape[-1]).clone()
else: # use mask
assert (L_Q == L_V) # requires that L_Q == L_V, i.e. for self-attention only
contex = V.cumsum(dim=-2)
return contex
def _update_context(self, context_in, V, scores, index, L_Q, attn_mask):
B, H, L_V, D = V.shape
if self.mask_flag: | 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_changed,
)
from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker
from custom_components.oref_alert.const import (
ADD_SENSOR_SERVICE,
ATTR_COUNTRY_ALERTS,
ATTR_COUNTRY_ACTIVE_ALERTS,
ATTR_SELECTED_AREAS_ALERTS,
ATTR_SELECTED_AREAS_ACTIVE_ALERTS,
CONF_ALERT_MAX_AGE,
CONF_AREAS,
CONF_OFF_ICON,
CONF_ON_ICON,
CONF_POLL_INTERVAL,
DOMAIN,
OREF_ALERT_UNIQUE_ID,
ALL_AREAS_ID_SUFFIX,
)
from .utils import load_json_fixture, mock_urls | 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:
"""Integration setup."""
options = options or {}
config_entry = MockConfigEntry(
domain=DOMAIN, options={**DEFAULT_OPTIONS, **options}
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return config_entry.entry_id
async def async_shutdown(hass: HomeAssistant, config_id: str) -> None:
"""Shutdown by removing the integration."""
assert await hass.config_entries.async_remove(config_id)
await hass.async_block_till_done()
async def test_state(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test entity state."""
freezer.move_to("2023-10-07 06:30:00+03:00")
mock_urls(aioclient_mock, None, "single_alert_history.json")
config_id = await async_setup(hass)
assert hass.states.get(ENTITY_ID).state == STATE_ON
freezer.move_to("2023-10-07 06:39:50+03:00")
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID).state == STATE_ON
freezer.move_to("2023-10-07 06:40:01+03:00")
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID).state == STATE_OFF
await async_shutdown(hass, config_id)
@pytest.mark.parametrize(
("areas",),
((["תל אביב - כל האזורים"],), (["מחוז דן"],)),
ids=("City all areas", "District"),
)
async def test_real_time_alert_area_expansion(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, areas: list[str]
) -> None:
"""Test real time alert and city expansion."""
mock_urls(aioclient_mock, "single_alert_real_time.json", None)
config_id = await async_setup(hass, {CONF_AREAS: areas})
assert hass.states.get(ENTITY_ID).state == STATE_ON
await async_shutdown(hass, config_id)
async def test_state_attributes(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test state attributes."""
freezer.move_to("2023-10-07 06:30:00+03:00")
mock_urls(
aioclient_mock, "multi_alerts_real_time.json", "multi_alerts_history.json"
)
config_id = await async_setup(hass)
state = hass.states.get(ENTITY_ID)
| """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:
"""Integration setup."""
options = options or {}
config_entry = MockConfigEntry(
domain=DOMAIN, options={**DEFAULT_OPTIONS, **options}
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return config_entry.entry_id
async def async_shutdown(hass: HomeAssistant, config_id: str) -> None:
"""Shutdown by removing the integration."""
assert await hass.config_entries.async_remove(config_id)
await hass.async_block_till_done()
async def test_state(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test entity state."""
freezer.move_to("2023-10-07 06:30:00+03:00")
mock_urls(aioclient_mock, None, "single_alert_history.json")
config_id = await async_setup(hass)
assert hass.states.get(ENTITY_ID).state == STATE_ON
freezer.move_to("2023-10-07 06:39:50+03:00")
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID).state == STATE_ON
freezer.move_to("2023-10-07 06:40:01+03:00")
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID).state == STATE_OFF
await async_shutdown(hass, config_id)
@pytest.mark.parametrize(
("areas",),
((["תל אביב - כל האזורים"],), (["מחוז דן"],)),
ids=("City all areas", "District"),
)
async def test_real_time_alert_area_expansion(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, areas: list[str]
) -> None:
"""Test real time alert and city expansion."""
mock_urls(aioclient_mock, "single_alert_real_time.json", None)
config_id = await async_setup(hass, {CONF_AREAS: areas})
assert hass.states.get(ENTITY_ID).state == STATE_ON
await async_shutdown(hass, config_id)
async def test_state_attributes(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test state attributes."""
freezer.move_to("2023-10-07 06:30:00+03:00")
mock_urls(
aioclient_mock, "multi_alerts_real_time.json", "multi_alerts_history.json"
)
config_id = await async_setup(hass)
state = hass.states.get(ENTITY_ID) | 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(".", "_")
dirname = os.path.join(args.dirname, f'rir_mp3d/grid_{grid_distance_str}', args.room)
os.makedirs(dirname, exist_ok=True)
| #
# 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(".", "_")
dirname = os.path.join(args.dirname, f'rir_mp3d/grid_{grid_distance_str}', args.room)
os.makedirs(dirname, exist_ok=True)
| 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_TRAJECTORY, OPEN_GRIPPER, CLOSE_GRIPPER, TASK_COMPLETED, RESET_ENVIRONMENT | 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
self.segmentation_texts = []
self.segmentation_count = 0
self.trajectory_length = 0
self.attempted_task = False
self.completed_task = False
self.failed_task = False
self.head_camera_position = None
self.head_camera_orientation_q = None
self.wrist_camera_position = None
self.wrist_camera_orientation_q = None
self.command = None
def detect_object(self, segmentation_text):
self.logger.info(PROGRESS + "Capturing head and wrist camera images..." + ENDC)
self.main_connection.send([CAPTURE_IMAGES])
[head_camera_position, head_camera_orientation_q, wrist_camera_position, wrist_camera_orientation_q, env_connection_message] = self.main_connection.recv()
self.logger.info(env_connection_message)
self.head_camera_position = head_camera_position
self.head_camera_orientation_q = head_camera_orientation_q
self.wrist_camera_position = wrist_camera_position
self.wrist_camera_orientation_q = wrist_camera_orientation_q
rgb_image_head = Image.open(config.rgb_image_head_path).convert("RGB")
depth_image_head = Image.open(config.depth_image_head_path).convert("L")
depth_array = np.array(depth_image_head) / 255.
if self.segmentation_count == 0:
xmem_image = Image.fromarray(np.zeros_like(depth_array)).convert("L")
xmem_image.save(config.xmem_input_path)
segmentation_texts = [segmentation_text]
self.logger.info(PROGRESS + "Segmenting head camera image..." + ENDC)
model_predictions, boxes, segmentation_texts = models.get_langsam_output(rgb_image_head, self.langsam_model, segmentation_texts, self.segmentation_count)
|
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.segmentation_texts = []
self.segmentation_count = 0
self.trajectory_length = 0
self.attempted_task = False
self.completed_task = False
self.failed_task = False
self.head_camera_position = None
self.head_camera_orientation_q = None
self.wrist_camera_position = None
self.wrist_camera_orientation_q = None
self.command = None
def detect_object(self, segmentation_text):
self.logger.info(PROGRESS + "Capturing head and wrist camera images..." + ENDC)
self.main_connection.send([CAPTURE_IMAGES])
[head_camera_position, head_camera_orientation_q, wrist_camera_position, wrist_camera_orientation_q, env_connection_message] = self.main_connection.recv()
self.logger.info(env_connection_message)
self.head_camera_position = head_camera_position
self.head_camera_orientation_q = head_camera_orientation_q
self.wrist_camera_position = wrist_camera_position
self.wrist_camera_orientation_q = wrist_camera_orientation_q
rgb_image_head = Image.open(config.rgb_image_head_path).convert("RGB")
depth_image_head = Image.open(config.depth_image_head_path).convert("L")
depth_array = np.array(depth_image_head) / 255.
if self.segmentation_count == 0:
xmem_image = Image.fromarray(np.zeros_like(depth_array)).convert("L")
xmem_image.save(config.xmem_input_path)
segmentation_texts = [segmentation_text]
self.logger.info(PROGRESS + "Segmenting head camera image..." + ENDC)
model_predictions, boxes, segmentation_texts = models.get_langsam_output(rgb_image_head, self.langsam_model, segmentation_texts, self.segmentation_count) | 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 dataset path')
parser.add_argument('--pdbbind_path', type=str,
default='/home/dtj/work_site/test/tmp/data/v2020-PL', help='PDBbind dataset path')
parser.add_argument('--apo_info_path', type=str,
default='/home/dtj/work_site/test/tmp/data/apobind_all.csv', help='APObind apo-holo mapping csv path (provided by APObind)')
parser.add_argument('--aff_info_path', type=str,
default='/home/dtj/work_site/test/tmp/data/index/INDEX_general_PL_data.2020',
help='PDBbind affinity data path')
parser.add_argument('--aug_path', type=str,
default='/home/dtj/work_site/test/tmp/data/pdbbind_MC', help='Rosetta decoys (pseudo apo structures)')
# parameters
parser.add_argument('--max_len_pocket', type=int,
default=50, help='max number of protein pocket residues')
parser.add_argument('--max_len_ligand', type=int,
default=50, help='max number of ligand atoms')
# other
parser.add_argument('--tmp_path', type=str,
default='./tmp', help='tmp file for temporary saving')
# output
parser.add_argument('--save_path', type=str,
default='/home/dtj/work_site/test/tmp/data/processed_data_maxp50_maxl50', help='output path (preprocessed), npz or pkl')
args = parser.parse_args()
| 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 dataset path')
parser.add_argument('--pdbbind_path', type=str,
default='/home/dtj/work_site/test/tmp/data/v2020-PL', help='PDBbind dataset path')
parser.add_argument('--apo_info_path', type=str,
default='/home/dtj/work_site/test/tmp/data/apobind_all.csv', help='APObind apo-holo mapping csv path (provided by APObind)')
parser.add_argument('--aff_info_path', type=str,
default='/home/dtj/work_site/test/tmp/data/index/INDEX_general_PL_data.2020',
help='PDBbind affinity data path')
parser.add_argument('--aug_path', type=str,
default='/home/dtj/work_site/test/tmp/data/pdbbind_MC', help='Rosetta decoys (pseudo apo structures)')
# parameters
parser.add_argument('--max_len_pocket', type=int,
default=50, help='max number of protein pocket residues')
parser.add_argument('--max_len_ligand', type=int,
default=50, help='max number of ligand atoms')
# other
parser.add_argument('--tmp_path', type=str,
default='./tmp', help='tmp file for temporary saving')
# output
parser.add_argument('--save_path', type=str,
default='/home/dtj/work_site/test/tmp/data/processed_data_maxp50_maxl50', help='output path (preprocessed), npz or pkl')
args = parser.parse_args() | 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"i32 noundef (\S+)", arg):
return Arg(vtype="i32", value=m.group(1))
raise NotImplementedError(arg)
def parse_call(expr):
logger.debug(f"parse_call({expr})")
if m := re.match(r"\s*call \w+(?: \(.*\))? @(\w+)\((.*)\)", expr):
name, args = m.groups()
args = args.split(", ")
args = [parse_arg(arg) for arg in args if arg]
|
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"i32 noundef (\S+)", arg):
return Arg(vtype="i32", value=m.group(1))
raise NotImplementedError(arg)
def parse_call(expr):
logger.debug(f"parse_call({expr})")
if m := re.match(r"\s*call \w+(?: \(.*\))? @(\w+)\((.*)\)", expr):
name, args = m.groups()
args = args.split(", ")
args = [parse_arg(arg) for arg in args if arg] | 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 FastAPI, Body
from PIL import ImageFilter
from modules import shared
from math import sqrt
import gradio as gr
import numpy as np | 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 NudeNet mask detection"),
output_mask: bool = Body(None, title="return mask"),
|
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 NudeNet mask detection"),
output_mask: bool = Body(None, title="return mask"), | 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 time
import torchvision.utils as tvu
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F | 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, TimestepBlock):
"""
A sequential module that passes timestep embeddings to the children that
support it as an extra input.
"""
def forward(self, x, emb):
for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
else:
x = layer(x)
return x
class Upsample(nn.Module):
"""
An upsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
upsampling occurs in the inner-two dimensions.
"""
def __init__(self, channels, use_conv, dims=2):
super().__init__()
self.channels = channels
self.use_conv = use_conv
self.dims = dims
if use_conv:
|
class TimestepBlock(nn.Module):
"""
Any module where forward() takes timestep embeddings as a second argument.
"""
@abstractmethod
def forward(self, x, emb):
"""
Apply the module to `x` given `emb` timestep embeddings.
"""
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
"""
A sequential module that passes timestep embeddings to the children that
support it as an extra input.
"""
def forward(self, x, emb):
for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
else:
x = layer(x)
return x
class Upsample(nn.Module):
"""
An upsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
upsampling occurs in the inner-two dimensions.
"""
def __init__(self, channels, use_conv, dims=2):
super().__init__()
self.channels = channels
self.use_conv = use_conv
self.dims = dims
if use_conv: | 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 check_ngc_access | 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 or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
class Deployer:
def __init__(self, params, config):
self.tf_outputs = {}
self.params = params
self.config = config
self.existing_behavior = None
# save original params so we can recreate command line
self.input_params = params.copy()
# convert "in_china"
self.params["in_china"] = {"yes": True, "no": False, "auto": False}[
self.params["in_china"]
]
# create state directory if it doesn't exist
os.makedirs(self.config["state_dir"], exist_ok=True)
# print complete command line
if self.params["debug"]:
click.echo(colorize_info("* Command:\n" + self.recreate_command_line()))
def __del__(self):
# update meta info
self.save_meta()
def save_meta(self):
"""
Save command parameters in json file, just in case
"""
meta_file = (
f"{self.config['state_dir']}/{self.params['deployment_name']}/meta.json"
)
data = {
"command": self.recreate_command_line(separator=" "),
"input_params": self.input_params,
"params": self.params,
"config": self.config,
}
Path(meta_file).parent.mkdir(parents=True, exist_ok=True)
Path(meta_file).write_text(json.dumps(data, indent=4))
if self.params["debug"]:
click.echo(colorize_info(f"* Meta info saved to '{meta_file}'"))
| # 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 or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# endregion
class Deployer:
def __init__(self, params, config):
self.tf_outputs = {}
self.params = params
self.config = config
self.existing_behavior = None
# save original params so we can recreate command line
self.input_params = params.copy()
# convert "in_china"
self.params["in_china"] = {"yes": True, "no": False, "auto": False}[
self.params["in_china"]
]
# create state directory if it doesn't exist
os.makedirs(self.config["state_dir"], exist_ok=True)
# print complete command line
if self.params["debug"]:
click.echo(colorize_info("* Command:\n" + self.recreate_command_line()))
def __del__(self):
# update meta info
self.save_meta()
def save_meta(self):
"""
Save command parameters in json file, just in case
"""
meta_file = (
f"{self.config['state_dir']}/{self.params['deployment_name']}/meta.json"
)
data = {
"command": self.recreate_command_line(separator=" "),
"input_params": self.input_params,
"params": self.params,
"config": self.config,
}
Path(meta_file).parent.mkdir(parents=True, exist_ok=True)
Path(meta_file).write_text(json.dumps(data, indent=4))
if self.params["debug"]:
click.echo(colorize_info(f"* Meta info saved to '{meta_file}'"))
| 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_tokenizer import SimpleTokenizer as _Tokenizer
from torchvision.transforms import InterpolationMode | 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_resize
from misc.imutils import pil_rescale, pil_resize
from misc.torchutils import visualize_tensors | 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 ImageDataset(data.Dataset):
"""list dataloder"""
def __init__(self, root_dir: str,
split: str = 'train',
img_size: int = 256,
norm: bool = False,
img_folder_name: Union[str, list, tuple] = 'A',
list_folder_name: str = 'list',
scale_ratios: Union[int, list] = 1):
super(ImageDataset, self).__init__()
self.root_dir = root_dir
self.split = split # train | train_aug | val
self.list_path = os.path.join(self.root_dir, list_folder_name, self.split+'.txt')
self.img_name_list = load_img_name_list(self.list_path)
if isinstance(img_folder_name, list) or isinstance(img_folder_name, tuple):
# 此处为了兼容存在多个img_folder,内部文件共名字的情况,比如img_folder_name=['A','B']
self.img_folder_with_name_list = [img_folder_name_+'/'+name
for name in self.img_name_list
for img_folder_name_ in img_folder_name]
elif isinstance(img_folder_name, str):
self.img_folder_with_name_list = [img_folder_name+'/'+name
for name in self.img_name_list]
else:
raise NotImplementedError
self.A_size = len(self.img_folder_with_name_list) # get the size of dataset A
self.img_folder_name = img_folder_name
self.img_size = img_size
self.norm = norm
self.basic_transforms = get_transforms(norm=norm, img_size=img_size)
self.scale_ratios = scale_ratios
def __getitem__(self, index):
folder_with_name = self.img_folder_with_name_list[index % self.A_size]
img_folder_name = folder_with_name.split('/')[0]
name = folder_with_name.split('/')[-1]
A_path = os.path.join(self.root_dir, img_folder_name, name)
img = np.asarray(Image.open(A_path).convert('RGB'))
scales = self.scale_ratios
if isinstance(scales, list):
scale = scales[torch.randint(len(scales), (1,)).item()]
else:
scale = scales
if scale != 1:
h, w = img.shape[:2]
img = pil_rescale(img, scale=scale, order=3)
img = pil_resize(img, size=[h, w], order=3)
if self.basic_transforms is not None:
img = self.basic_transforms(img)
return {'A': img, 'name': name}
def __len__(self):
"""Return the total number of images in the dataset."""
return self.A_size
class SegDataset(ImageDataset):
'''
transforms: 表示同时对image 和 mask 做变换;
'''
def __init__(self,
root_dir: str,
split: str = 'train',
img_size: int = 256,
norm: bool = False,
img_folder_name: Union[str, list, tuple] = 'A',
label_transform: str = 'norm',
label_folder_name: str = 'label',
scale_ratios: Union[int, list] = 1):
super(SegDataset, self).__init__(root_dir, split=split,
img_size=img_size,
norm=norm,
img_folder_name=img_folder_name,
scale_ratios=scale_ratios)
|
"""
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 ImageDataset(data.Dataset):
"""list dataloder"""
def __init__(self, root_dir: str,
split: str = 'train',
img_size: int = 256,
norm: bool = False,
img_folder_name: Union[str, list, tuple] = 'A',
list_folder_name: str = 'list',
scale_ratios: Union[int, list] = 1):
super(ImageDataset, self).__init__()
self.root_dir = root_dir
self.split = split # train | train_aug | val
self.list_path = os.path.join(self.root_dir, list_folder_name, self.split+'.txt')
self.img_name_list = load_img_name_list(self.list_path)
if isinstance(img_folder_name, list) or isinstance(img_folder_name, tuple):
# 此处为了兼容存在多个img_folder,内部文件共名字的情况,比如img_folder_name=['A','B']
self.img_folder_with_name_list = [img_folder_name_+'/'+name
for name in self.img_name_list
for img_folder_name_ in img_folder_name]
elif isinstance(img_folder_name, str):
self.img_folder_with_name_list = [img_folder_name+'/'+name
for name in self.img_name_list]
else:
raise NotImplementedError
self.A_size = len(self.img_folder_with_name_list) # get the size of dataset A
self.img_folder_name = img_folder_name
self.img_size = img_size
self.norm = norm
self.basic_transforms = get_transforms(norm=norm, img_size=img_size)
self.scale_ratios = scale_ratios
def __getitem__(self, index):
folder_with_name = self.img_folder_with_name_list[index % self.A_size]
img_folder_name = folder_with_name.split('/')[0]
name = folder_with_name.split('/')[-1]
A_path = os.path.join(self.root_dir, img_folder_name, name)
img = np.asarray(Image.open(A_path).convert('RGB'))
scales = self.scale_ratios
if isinstance(scales, list):
scale = scales[torch.randint(len(scales), (1,)).item()]
else:
scale = scales
if scale != 1:
h, w = img.shape[:2]
img = pil_rescale(img, scale=scale, order=3)
img = pil_resize(img, size=[h, w], order=3)
if self.basic_transforms is not None:
img = self.basic_transforms(img)
return {'A': img, 'name': name}
def __len__(self):
"""Return the total number of images in the dataset."""
return self.A_size
class SegDataset(ImageDataset):
'''
transforms: 表示同时对image 和 mask 做变换;
'''
def __init__(self,
root_dir: str,
split: str = 'train',
img_size: int = 256,
norm: bool = False,
img_folder_name: Union[str, list, tuple] = 'A',
label_transform: str = 'norm',
label_folder_name: str = 'label',
scale_ratios: Union[int, list] = 1):
super(SegDataset, self).__init__(root_dir, split=split,
img_size=img_size,
norm=norm,
img_folder_name=img_folder_name,
scale_ratios=scale_ratios) | 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._render_options = render_options
self.values = {}
assert isinstance(self._data, pd.DataFrame) == True, "data must be a pandas.DataFrame"
assert self._target_column in self._data.columns, f"data must have '{self._target_column}' column"
self.compute()
if not self._render_options:
self._render_options = self.default_render_options()
@property
def min(self):
return self._data[self.target_column].min()
@property
def max(self):
return self._data[self.target_column].max()
@property
def target_column(self):
return self._target_column
@property
def name(self):
return self.__class__.__name__
@property
def names(self):
return self._names
def compute(self):
raise NotImplementedError
def default_render_options(self):
return {}
def render_options(self):
return {name: option.copy() for name, option in self._render_options.items()}
def __getitem__(self, index: int):
row = self._data.iloc[index]
for name in self.names:
if pd.isna(row[name]):
return None
self.values[name] = row[name]
if self._render_options.get(name):
self._render_options[name].value = row[name]
return self.serialise()
def __call__(self, index: int):
return self[index]
def serialise(self):
return {
'name': self.name,
'names': self.names,
'values': self.values.copy(),
'target_column': self.target_column,
'render_options': self.render_options(),
'min': self.min,
'max': self.max
}
class SMA(Indicator):
""" Trend indicator
A simple moving average (SMA) calculates the average of a selected range of prices, usually closing prices, by the number
of periods in that range.
The SMA is a technical indicator for determining if an asset price will continue or reverse a bull or bear trend. It is
calculated by summing up the closing prices of a stock over time and then dividing that total by the number of time periods
being examined. Short-term averages respond quickly to changes in the price of the underlying, while long-term averages are
slow to react.
https://www.investopedia.com/terms/s/sma.asp
"""
def __init__(
self,
data: pd.DataFrame,
period: int=20,
target_column: str='close',
render_options: dict={}
):
self._period = period
self._names = [f'SMA{period}']
super().__init__(data, target_column, render_options)
@property
def min(self):
return self._data[self.names[0]].min()
@property
def max(self):
return self._data[self.names[0]].max()
def default_render_options(self):
return {name: RenderOptions(
name=name,
color=(100, 100, 255),
|
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._render_options = render_options
self.values = {}
assert isinstance(self._data, pd.DataFrame) == True, "data must be a pandas.DataFrame"
assert self._target_column in self._data.columns, f"data must have '{self._target_column}' column"
self.compute()
if not self._render_options:
self._render_options = self.default_render_options()
@property
def min(self):
return self._data[self.target_column].min()
@property
def max(self):
return self._data[self.target_column].max()
@property
def target_column(self):
return self._target_column
@property
def name(self):
return self.__class__.__name__
@property
def names(self):
return self._names
def compute(self):
raise NotImplementedError
def default_render_options(self):
return {}
def render_options(self):
return {name: option.copy() for name, option in self._render_options.items()}
def __getitem__(self, index: int):
row = self._data.iloc[index]
for name in self.names:
if pd.isna(row[name]):
return None
self.values[name] = row[name]
if self._render_options.get(name):
self._render_options[name].value = row[name]
return self.serialise()
def __call__(self, index: int):
return self[index]
def serialise(self):
return {
'name': self.name,
'names': self.names,
'values': self.values.copy(),
'target_column': self.target_column,
'render_options': self.render_options(),
'min': self.min,
'max': self.max
}
class SMA(Indicator):
""" Trend indicator
A simple moving average (SMA) calculates the average of a selected range of prices, usually closing prices, by the number
of periods in that range.
The SMA is a technical indicator for determining if an asset price will continue or reverse a bull or bear trend. It is
calculated by summing up the closing prices of a stock over time and then dividing that total by the number of time periods
being examined. Short-term averages respond quickly to changes in the price of the underlying, while long-term averages are
slow to react.
https://www.investopedia.com/terms/s/sma.asp
"""
def __init__(
self,
data: pd.DataFrame,
period: int=20,
target_column: str='close',
render_options: dict={}
):
self._period = period
self._names = [f'SMA{period}']
super().__init__(data, target_column, render_options)
@property
def min(self):
return self._data[self.names[0]].min()
@property
def max(self):
return self._data[self.names[0]].max()
def default_render_options(self):
return {name: RenderOptions(
name=name,
color=(100, 100, 255), | 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时
preds = preds.unsqueeze(-1) if preds.dim()==1 else preds
preds = torch.concat([1-preds, preds], dim=-1)
preds = preds.argmax(dim=-1).flatten().int()
if targets.dim() > 1 and targets.shape[-1] > 1: # 当targets为one-hot时
targets = targets.argmax(dim=1).int()
else:
targets = targets.flatten().int()
cm = torch.zeros([num_classes, num_classes], dtype=preds.dtype, device=preds.device)
one = torch.tensor([1], dtype=preds.dtype, device=preds.device)
return cm.index_put_((targets, preds), one, accumulate=True)
@lru_cache(maxsize=1)
def cmats_and_weights(c_mat):
"""获取各类别的混淆矩阵和权值"""
if c_mat.shape[0] == 2:
| """
@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时
preds = preds.unsqueeze(-1) if preds.dim()==1 else preds
preds = torch.concat([1-preds, preds], dim=-1)
preds = preds.argmax(dim=-1).flatten().int()
if targets.dim() > 1 and targets.shape[-1] > 1: # 当targets为one-hot时
targets = targets.argmax(dim=1).int()
else:
targets = targets.flatten().int()
cm = torch.zeros([num_classes, num_classes], dtype=preds.dtype, device=preds.device)
one = torch.tensor([1], dtype=preds.dtype, device=preds.device)
return cm.index_put_((targets, preds), one, accumulate=True)
@lru_cache(maxsize=1)
def cmats_and_weights(c_mat):
"""获取各类别的混淆矩阵和权值"""
if c_mat.shape[0] == 2: | 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 (
DEFAULT_FLOAT_DTYPE_WGPU,
unlatexify,
)
from colour_visuals.visual import (
MixinPropertyModel,
MixinPropertySize,
Visual,
) | 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-Clause"
__maintainer__ = "Colour Developers"
__email__ = "colour-developers@colour-science.org"
__status__ = "Production"
__all__ = ["VisualAxes"]
| # !/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-Clause"
__maintainer__ = "Colour Developers"
__email__ = "colour-developers@colour-science.org"
__status__ = "Production"
__all__ = ["VisualAxes"]
| 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 WeightedRandomSampler
import logging
import json
import os
import os.path as osp
import numpy as np
import torch
import json | 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_proportion"][cfg["modes"].index(self.mode)]
self.data_root = join(cfg["root"], d_cfg["data_root"])
self.pad_nv = d_cfg["max_K"]
self.pad_np = d_cfg["max_P"]
self.n_pcl = d_cfg["n_pcl"]
self.valid_obj_ind = self.load_split(
d_cfg["split_path"], phase=self.mode, cates=d_cfg["cates"]
)
| # 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_proportion"][cfg["modes"].index(self.mode)]
self.data_root = join(cfg["root"], d_cfg["data_root"])
self.pad_nv = d_cfg["max_K"]
self.pad_np = d_cfg["max_P"]
self.n_pcl = d_cfg["n_pcl"]
self.valid_obj_ind = self.load_split(
d_cfg["split_path"], phase=self.mode, cates=d_cfg["cates"]
)
| 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) -> bool:
"""Check whether the layer is conditioned."""
return self.vis_x is not None
# Used this great idea from this implementation of Flamingo (https://github.com/dhansmair/flamingo-mini/)
def condition_vis_x(self, vis_x):
self.vis_x = vis_x
def condition_media_locations(self, media_locations):
self.media_locations = media_locations
def condition_attend_previous(self, attend_previous):
self.attend_previous = attend_previous
def forward(
self,
lang_x,
attention_mask=None,
**decoder_layer_kwargs,
):
if self.gated_cross_attn_layer is None:
return self.decoder_layer(
lang_x, attention_mask=attention_mask, **decoder_layer_kwargs
)
if self.vis_x is None:
raise ValueError("vis_x must be conditioned before forward pass")
if self.media_locations is None:
raise ValueError("media_locations must be conditioned before forward pass")
lang_x = self.gated_cross_attn_layer(
lang_x,
self.vis_x,
media_locations=self.media_locations,
attend_previous=self.attend_previous,
)
lang_x = self.decoder_layer(
lang_x, attention_mask=attention_mask, **decoder_layer_kwargs
)
return lang_x
class FlamingoLMMixin(nn.Module):
"""
Mixin to add cross-attention layers to a language model.
"""
def set_decoder_layers_attr_name(self, decoder_layers_attr_name):
self.decoder_layers_attr_name = decoder_layers_attr_name
def _get_decoder_layers(self):
return getattr_recursive(self, self.decoder_layers_attr_name)
def _set_decoder_layers(self, value):
setattr_recursive(self, self.decoder_layers_attr_name, value)
def init_flamingo(
self,
media_token_id,
vis_hidden_size,
cross_attn_every_n_layers,
use_media_placement_augmentation,
):
"""
Initialize Flamingo by adding a new gated cross attn to the decoder. Store the media token id for computing the media locations.
"""
self.gated_cross_attn_layers = nn.ModuleList(
[
|
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) -> bool:
"""Check whether the layer is conditioned."""
return self.vis_x is not None
# Used this great idea from this implementation of Flamingo (https://github.com/dhansmair/flamingo-mini/)
def condition_vis_x(self, vis_x):
self.vis_x = vis_x
def condition_media_locations(self, media_locations):
self.media_locations = media_locations
def condition_attend_previous(self, attend_previous):
self.attend_previous = attend_previous
def forward(
self,
lang_x,
attention_mask=None,
**decoder_layer_kwargs,
):
if self.gated_cross_attn_layer is None:
return self.decoder_layer(
lang_x, attention_mask=attention_mask, **decoder_layer_kwargs
)
if self.vis_x is None:
raise ValueError("vis_x must be conditioned before forward pass")
if self.media_locations is None:
raise ValueError("media_locations must be conditioned before forward pass")
lang_x = self.gated_cross_attn_layer(
lang_x,
self.vis_x,
media_locations=self.media_locations,
attend_previous=self.attend_previous,
)
lang_x = self.decoder_layer(
lang_x, attention_mask=attention_mask, **decoder_layer_kwargs
)
return lang_x
class FlamingoLMMixin(nn.Module):
"""
Mixin to add cross-attention layers to a language model.
"""
def set_decoder_layers_attr_name(self, decoder_layers_attr_name):
self.decoder_layers_attr_name = decoder_layers_attr_name
def _get_decoder_layers(self):
return getattr_recursive(self, self.decoder_layers_attr_name)
def _set_decoder_layers(self, value):
setattr_recursive(self, self.decoder_layers_attr_name, value)
def init_flamingo(
self,
media_token_id,
vis_hidden_size,
cross_attn_every_n_layers,
use_media_placement_augmentation,
):
"""
Initialize Flamingo by adding a new gated cross attn to the decoder. Store the media token id for computing the media locations.
"""
self.gated_cross_attn_layers = nn.ModuleList(
[ | 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}/merge_requests"
# 发送API请求,检查是否有与分支相关的Merge Request
params = {
"source_branch": branch_name,
"state": "opened" # 可以根据需求选择合适的状态(opened、closed、merged等)
}
headers = {"Private-Token": gitlab_private_token}
response = requests.get(url, params=params, headers=headers)
# 解析JSON响应并检查是否有相关的Merge Request
if response.status_code == 200:
merge_requests = response.json()
if len(merge_requests) > 0:
|
@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}/merge_requests"
# 发送API请求,检查是否有与分支相关的Merge Request
params = {
"source_branch": branch_name,
"state": "opened" # 可以根据需求选择合适的状态(opened、closed、merged等)
}
headers = {"Private-Token": gitlab_private_token}
response = requests.get(url, params=params, headers=headers)
# 解析JSON响应并检查是否有相关的Merge Request
if response.status_code == 200:
merge_requests = response.json()
if len(merge_requests) > 0: | 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 import Scalar, update_target_network
from .utils import prefix_metrics
import numpy as np
import jax
import jax.numpy as jnp
import flax
import flax.linen as nn
import optax
import distrax | 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.0
config.policy_lr = 3e-4
config.policy_weight_decay = 0.0
config.qf_lr = 3e-4
config.qf_weight_decay = 0.0
config.optimizer_type = 'adam'
config.soft_target_update_rate = 5e-3
config.use_cql = False
config.cql_n_actions = 10
config.cql_importance_sample = True
config.cql_lagrange = False
config.cql_target_action_gap = 1.0
config.cql_temp = 1.0
config.cql_min_q_weight = 5.0
config.cql_max_target_backup = False
config.cql_clip_diff_min = -np.inf
config.cql_clip_diff_max = np.inf
if updates is not None:
config.update(ConfigDict(updates).copy_and_resolve_references())
return config
def __init__(self, config, policy, qf):
self.config = self.get_default_config(config)
self.policy = policy
self.qf = qf
self.observation_dim = policy.observation_dim
self.action_dim = policy.action_dim
self._train_states = {}
optimizer_class = {
'adam': optax.adam,
'sgd': optax.sgd,
}[self.config.optimizer_type]
policy_params = self.policy.init(
|
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.0
config.policy_lr = 3e-4
config.policy_weight_decay = 0.0
config.qf_lr = 3e-4
config.qf_weight_decay = 0.0
config.optimizer_type = 'adam'
config.soft_target_update_rate = 5e-3
config.use_cql = False
config.cql_n_actions = 10
config.cql_importance_sample = True
config.cql_lagrange = False
config.cql_target_action_gap = 1.0
config.cql_temp = 1.0
config.cql_min_q_weight = 5.0
config.cql_max_target_backup = False
config.cql_clip_diff_min = -np.inf
config.cql_clip_diff_max = np.inf
if updates is not None:
config.update(ConfigDict(updates).copy_and_resolve_references())
return config
def __init__(self, config, policy, qf):
self.config = self.get_default_config(config)
self.policy = policy
self.qf = qf
self.observation_dim = policy.observation_dim
self.action_dim = policy.action_dim
self._train_states = {}
optimizer_class = {
'adam': optax.adam,
'sgd': optax.sgd,
}[self.config.optimizer_type]
policy_params = self.policy.init( | next_rng(self.policy.rng_keys()), | 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 functions:
def solve_puzzle(board, solution) -> bool: whether model can solve the puzzle
convert_pgn_to_game(pgn_moves) -> game
"""
DATA_DIR = Path("/data/chess-data/lichess_puzzles")
FILE_NAME = DATA_DIR / "pairs.csv"
def plot_acc_pairs(engine, bucket_size=200, enough_samples=10):
# Create buckets
buckets = {i*bucket_size: [] for i in range(30)}
# Read the data and sort into buckets
with open(FILE_NAME) as f:
reader = csv.reader(f)
print(reader.__next__())
for uid, rating, pgn, proofgame, solution in tqdm(list(reader)):
rating_bucket = int(rating) // bucket_size * bucket_size
if len(buckets[rating_bucket]) < enough_samples:
buckets[rating_bucket].append((pgn, proofgame, solution))
# print how many elems in buckets
for k, v in buckets.items():
print(f'rating [{k}, {k + bucket_size})', 'n', len(v))
nonempty_buckets = [k for k, v in buckets.items() if len(v) > 0]
# Test the puzzles
ok_pgn = {i*bucket_size: [] for i in range(30)}
ok_proofgame = {i*bucket_size: [] for i in range(30)}
for rating_bucket, puzzles in tqdm(buckets.items()):
for pgn, proofgame, solution in puzzles:
board_pgn = chess.Board()
board_proofgame = chess.Board()
print("pgn origi", pgn)
print("proofgame", proofgame)
# Iterate over the moves and apply them to the board
for move in convert_pgn_to_game(pgn).mainline_moves():
board_pgn.push(move)
for move in convert_pgn_to_game(proofgame).mainline_moves():
board_proofgame.push(move)
|
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 functions:
def solve_puzzle(board, solution) -> bool: whether model can solve the puzzle
convert_pgn_to_game(pgn_moves) -> game
"""
DATA_DIR = Path("/data/chess-data/lichess_puzzles")
FILE_NAME = DATA_DIR / "pairs.csv"
def plot_acc_pairs(engine, bucket_size=200, enough_samples=10):
# Create buckets
buckets = {i*bucket_size: [] for i in range(30)}
# Read the data and sort into buckets
with open(FILE_NAME) as f:
reader = csv.reader(f)
print(reader.__next__())
for uid, rating, pgn, proofgame, solution in tqdm(list(reader)):
rating_bucket = int(rating) // bucket_size * bucket_size
if len(buckets[rating_bucket]) < enough_samples:
buckets[rating_bucket].append((pgn, proofgame, solution))
# print how many elems in buckets
for k, v in buckets.items():
print(f'rating [{k}, {k + bucket_size})', 'n', len(v))
nonempty_buckets = [k for k, v in buckets.items() if len(v) > 0]
# Test the puzzles
ok_pgn = {i*bucket_size: [] for i in range(30)}
ok_proofgame = {i*bucket_size: [] for i in range(30)}
for rating_bucket, puzzles in tqdm(buckets.items()):
for pgn, proofgame, solution in puzzles:
board_pgn = chess.Board()
board_proofgame = chess.Board()
print("pgn origi", pgn)
print("proofgame", proofgame)
# Iterate over the moves and apply them to the board
for move in convert_pgn_to_game(pgn).mainline_moves():
board_pgn.push(move)
for move in convert_pgn_to_game(proofgame).mainline_moves():
board_proofgame.push(move)
| 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 Units (PTUs).")
sub_parsers = parser.add_subparsers()
load_parser = sub_parsers.add_parser("load", help="Run load generation tool.")
load_parser.add_argument("-a", "--api-version", type=str, default="2023-05-15", help="Set OpenAI API version.")
load_parser.add_argument("-k", "--api-key-env", type=str, default="OPENAI_API_KEY", help="Environment variable that contains the API KEY.")
load_parser.add_argument("-c", "--clients", type=int, default=20, help="Set number of parallel clients to use for load generation.")
load_parser.add_argument("-n", "--requests", type=int, help="Number of requests for the load run. Default to 'until killed'.")
load_parser.add_argument("-d", "--duration", type=int, help="Duration of load in seconds. Defaults to 'until killed'.")
load_parser.add_argument("-r", "--rate", type=float, help="Rate of request generation in Requests Per Minute (RPM). Default to as fast as possible.")
load_parser.add_argument("-w", "--aggregation-window", type=float, default=60, help="Statistics aggregation sliding window duration in seconds. See README.md for more details.")
load_parser.add_argument("-s", "--shape-profile", type=str, default="balanced", help="Shape profile of requests.", choices=["balanced", "context", "generation", "custom"])
load_parser.add_argument("-p", "--context-tokens", type=int, help="Number of context tokens to use when --shape-profile=custom.")
load_parser.add_argument("-m", "--max-tokens", type=int, help="Number of requested max_tokens when --shape-profile=custom. Defaults to unset.")
load_parser.add_argument("-i", "--completions", type=int, default=1, help="Number of completion for each request.")
load_parser.add_argument("--frequency-penalty", type=float, help="Request frequency_penalty.")
load_parser.add_argument("--presence-penalty", type=float, help="Request frequency_penalty.")
load_parser.add_argument("--temperature", type=float, help="Request temperature.")
load_parser.add_argument("--top-p", type=float, help="Request top_p.")
load_parser.add_argument("-f", "--output-format", type=str, default="human", help="Output format.", choices=["jsonl", "human"])
load_parser.add_argument("-t", "--retry", type=str, default="none", help="Request retry strategy.", choices=["none", "exponential"])
load_parser.add_argument("-e", "--deployment", type=str, help="Azure OpenAI deployment name.", required=True)
load_parser.add_argument("api_base_endpoint", help="Azure OpenAI deployment base endpoint.", nargs=1)
| # 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 Units (PTUs).")
sub_parsers = parser.add_subparsers()
load_parser = sub_parsers.add_parser("load", help="Run load generation tool.")
load_parser.add_argument("-a", "--api-version", type=str, default="2023-05-15", help="Set OpenAI API version.")
load_parser.add_argument("-k", "--api-key-env", type=str, default="OPENAI_API_KEY", help="Environment variable that contains the API KEY.")
load_parser.add_argument("-c", "--clients", type=int, default=20, help="Set number of parallel clients to use for load generation.")
load_parser.add_argument("-n", "--requests", type=int, help="Number of requests for the load run. Default to 'until killed'.")
load_parser.add_argument("-d", "--duration", type=int, help="Duration of load in seconds. Defaults to 'until killed'.")
load_parser.add_argument("-r", "--rate", type=float, help="Rate of request generation in Requests Per Minute (RPM). Default to as fast as possible.")
load_parser.add_argument("-w", "--aggregation-window", type=float, default=60, help="Statistics aggregation sliding window duration in seconds. See README.md for more details.")
load_parser.add_argument("-s", "--shape-profile", type=str, default="balanced", help="Shape profile of requests.", choices=["balanced", "context", "generation", "custom"])
load_parser.add_argument("-p", "--context-tokens", type=int, help="Number of context tokens to use when --shape-profile=custom.")
load_parser.add_argument("-m", "--max-tokens", type=int, help="Number of requested max_tokens when --shape-profile=custom. Defaults to unset.")
load_parser.add_argument("-i", "--completions", type=int, default=1, help="Number of completion for each request.")
load_parser.add_argument("--frequency-penalty", type=float, help="Request frequency_penalty.")
load_parser.add_argument("--presence-penalty", type=float, help="Request frequency_penalty.")
load_parser.add_argument("--temperature", type=float, help="Request temperature.")
load_parser.add_argument("--top-p", type=float, help="Request top_p.")
load_parser.add_argument("-f", "--output-format", type=str, default="human", help="Output format.", choices=["jsonl", "human"])
load_parser.add_argument("-t", "--retry", type=str, default="none", help="Request retry strategy.", choices=["none", "exponential"])
load_parser.add_argument("-e", "--deployment", type=str, help="Azure OpenAI deployment name.", required=True)
load_parser.add_argument("api_base_endpoint", help="Azure OpenAI deployment base endpoint.", nargs=1) | 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, 3)
assert get_grid_shape(10, 3) == (4, 3)
def test_ceil_division():
assert ceil_division(19, 10) == 2
assert ceil_division(20, 10) == 2
assert ceil_division(21, 10) == 3
def test_get_layout_from_image():
|
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, 3)
assert get_grid_shape(10, 3) == (4, 3)
def test_ceil_division():
assert ceil_division(19, 10) == 2
assert ceil_division(20, 10) == 2
assert ceil_division(21, 10) == 3
def test_get_layout_from_image(): | 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, bias=True, kernel_size=1, padding=0, groups=4):
super(MRConv2d, self).__init__()
| # 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, bias=True, kernel_size=1, padding=0, groups=4):
super(MRConv2d, self).__init__() | 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',
'created_date',
'updated_date',
]
class AuthorSerializer(serializers.ModelSerializer):
full_name = serializers.SerializerMethodField('get_full_name')
class Meta:
model = User
fields = (
'name',
'username',
'profile_photo',
'website',
'twitter',
'youtube',
'github',
'bio',
)
class UserSerializer(serializers.ModelSerializer):
name = serializers.CharField()
email = serializers.EmailField()
profile_photo = serializers.ImageField()
website = serializers.CharField()
twitter = serializers.CharField()
youtube = serializers.CharField()
github = serializers.CharField()
bio = serializers.CharField()
class Meta:
model = User
fields = [
'name',
'email',
'username',
'profile_photo',
'website',
'twitter',
'youtube',
'github',
'bio',
]
class CourseSerializer(serializers.ModelSerializer):
class Meta:
|
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = [
'id',
'title',
'article_count',
'slug',
'description',
'color',
'logo',
'publish_status',
'created_date',
'updated_date',
]
class AuthorSerializer(serializers.ModelSerializer):
full_name = serializers.SerializerMethodField('get_full_name')
class Meta:
model = User
fields = (
'name',
'username',
'profile_photo',
'website',
'twitter',
'youtube',
'github',
'bio',
)
class UserSerializer(serializers.ModelSerializer):
name = serializers.CharField()
email = serializers.EmailField()
profile_photo = serializers.ImageField()
website = serializers.CharField()
twitter = serializers.CharField()
youtube = serializers.CharField()
github = serializers.CharField()
bio = serializers.CharField()
class Meta:
model = User
fields = [
'name',
'email',
'username',
'profile_photo',
'website',
'twitter',
'youtube',
'github',
'bio',
]
class CourseSerializer(serializers.ModelSerializer):
class Meta: | 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 import GPTQQuantizer
import logging as log
import torch
import warnings | 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 = "GPTQ_INT4-{precision}"
def is_torch_compression(args):
return args.compress_weights and BackendType.PYTORCH.value in args.compress_weights_backends
def is_ov_compression(args):
return args.compress_weights and BackendType.OPENVINO.value in args.compress_weights_backends
def is_fp16(args):
return args.precision == "FP16"
def is_ov_model_provided(model_id, model_dir, precision, model_name="openvino_model.xml"):
model_dirs = []
if Path(model_id).is_dir():
model_dirs.append(Path(model_id))
model_dirs.append(Path(model_id) / precision)
model_dirs.append(Path(model_id) / OV_DIR / precision)
model_dirs.append(Path(model_id) / PYTORCH_DIR / OV_DIR / precision)
model_dir = Path(model_dir)
model_dirs.append(model_dir)
model_dirs.append(model_dir / precision)
model_dirs.append(model_dir / OV_DIR / precision)
model_dirs.append(model_dir / PYTORCH_DIR / OV_DIR / precision)
for md in model_dirs:
found = True
for suffix in ['.xml', '.bin']:
model_file = (md / model_name).with_suffix(suffix)
if not model_file.exists():
found = False
break
if found:
return found
return False
def get_fp_path(args, model_subpath):
model_dirs = []
if Path(args.model_id).is_dir():
base_model_dir = Path(args.model_id)
model_dirs.extend([
base_model_dir, base_model_dir / args.precision, base_model_dir / OV_DIR / args.precision, base_model_dir / PYTORCH_DIR / OV_DIR / args.precision
])
model_dir = Path(args.output_dir)
model_dirs.append(model_dir)
model_dirs.append(Path(model_dir) / args.precision)
model_dirs.append(Path(model_dir) / OV_DIR / args.precision)
model_dirs.append(Path(model_dir) / PYTORCH_DIR / OV_DIR / args.precision)
for md in model_dirs:
if (md / model_subpath).exists():
return md / model_subpath
return None
def save_tokenizer(tokenizer, out_dir):
try:
tokenizer.save_pretrained(out_dir)
except Exception as e:
log.error(f'tokenizer loading failed with {e}')
def compress_ov_model_weights_helper(ov_model, tok, config, out_path, compress_weights_format="INT8", fp16=False, args={}, model_name="openvino_model"):
compression_args = None
if "INT8" in compress_weights_format and "INT8_ASYM" in COMPRESSION_OPTIONS:
warnings.warn("Usage INT8 mode is deprecated and will be removed soon. Please use INT8_ASYM instead", DeprecationWarning)
if "4BIT_DEFAULT" in compress_weights_format:
model_id = out_path.parents[3].name
| # -*- 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 = "GPTQ_INT4-{precision}"
def is_torch_compression(args):
return args.compress_weights and BackendType.PYTORCH.value in args.compress_weights_backends
def is_ov_compression(args):
return args.compress_weights and BackendType.OPENVINO.value in args.compress_weights_backends
def is_fp16(args):
return args.precision == "FP16"
def is_ov_model_provided(model_id, model_dir, precision, model_name="openvino_model.xml"):
model_dirs = []
if Path(model_id).is_dir():
model_dirs.append(Path(model_id))
model_dirs.append(Path(model_id) / precision)
model_dirs.append(Path(model_id) / OV_DIR / precision)
model_dirs.append(Path(model_id) / PYTORCH_DIR / OV_DIR / precision)
model_dir = Path(model_dir)
model_dirs.append(model_dir)
model_dirs.append(model_dir / precision)
model_dirs.append(model_dir / OV_DIR / precision)
model_dirs.append(model_dir / PYTORCH_DIR / OV_DIR / precision)
for md in model_dirs:
found = True
for suffix in ['.xml', '.bin']:
model_file = (md / model_name).with_suffix(suffix)
if not model_file.exists():
found = False
break
if found:
return found
return False
def get_fp_path(args, model_subpath):
model_dirs = []
if Path(args.model_id).is_dir():
base_model_dir = Path(args.model_id)
model_dirs.extend([
base_model_dir, base_model_dir / args.precision, base_model_dir / OV_DIR / args.precision, base_model_dir / PYTORCH_DIR / OV_DIR / args.precision
])
model_dir = Path(args.output_dir)
model_dirs.append(model_dir)
model_dirs.append(Path(model_dir) / args.precision)
model_dirs.append(Path(model_dir) / OV_DIR / args.precision)
model_dirs.append(Path(model_dir) / PYTORCH_DIR / OV_DIR / args.precision)
for md in model_dirs:
if (md / model_subpath).exists():
return md / model_subpath
return None
def save_tokenizer(tokenizer, out_dir):
try:
tokenizer.save_pretrained(out_dir)
except Exception as e:
log.error(f'tokenizer loading failed with {e}')
def compress_ov_model_weights_helper(ov_model, tok, config, out_path, compress_weights_format="INT8", fp16=False, args={}, model_name="openvino_model"):
compression_args = None
if "INT8" in compress_weights_format and "INT8_ASYM" in COMPRESSION_OPTIONS:
warnings.warn("Usage INT8 mode is deprecated and will be removed soon. Please use INT8_ASYM instead", DeprecationWarning)
if "4BIT_DEFAULT" in compress_weights_format:
model_id = out_path.parents[3].name | 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]
@property
def channels(self):
return self.array.shape[3]
@property
def count(self):
return self.array.shape[0]
def init(self, im):
npim = self._convert_image_to_np(im)
for i in range(self.count):
self.array[i] = npim
def add(self, im):
self.array[self.last_index] = self._convert_image_to_np(im)
self.last_index += 1
self.last_index %= self.count
def average(self, trimming = 0.0, easing = 0.0, preference = 0.0):
return np_to_pil(self.array[0] if self.count == 1 else np.clip(average_array(
self.array,
axis = 0,
trim = trimming,
power = preference + 1.0,
weights = np.roll(make_eased_weight_array(self.count, easing), self.last_index),
), 0.0, 1.0))
def load(self, project_dir):
buffer_dir = project_dir / "session" / "buffer"
if data := load_json(buffer_dir / "data.json"):
load_object(self, data, buffer_dir)
def save(self, project_dir):
buffer_dir = ensure_directory_exists(project_dir / "session" / "buffer")
save_json(buffer_dir / "data.json", save_object(self, buffer_dir))
def _convert_image_to_np(self, im):
|
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]
@property
def channels(self):
return self.array.shape[3]
@property
def count(self):
return self.array.shape[0]
def init(self, im):
npim = self._convert_image_to_np(im)
for i in range(self.count):
self.array[i] = npim
def add(self, im):
self.array[self.last_index] = self._convert_image_to_np(im)
self.last_index += 1
self.last_index %= self.count
def average(self, trimming = 0.0, easing = 0.0, preference = 0.0):
return np_to_pil(self.array[0] if self.count == 1 else np.clip(average_array(
self.array,
axis = 0,
trim = trimming,
power = preference + 1.0,
weights = np.roll(make_eased_weight_array(self.count, easing), self.last_index),
), 0.0, 1.0))
def load(self, project_dir):
buffer_dir = project_dir / "session" / "buffer"
if data := load_json(buffer_dir / "data.json"):
load_object(self, data, buffer_dir)
def save(self, project_dir):
buffer_dir = ensure_directory_exists(project_dir / "session" / "buffer")
save_json(buffer_dir / "data.json", save_object(self, buffer_dir))
def _convert_image_to_np(self, im): | 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 ProcessingError | 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,
# merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software
# is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# For Python less 3.11 compatibility
try:
except ImportError:
log = logging.getLogger(__name__)
| # 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,
# merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software
# is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# For Python less 3.11 compatibility
try:
except ImportError:
log = logging.getLogger(__name__) | 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.losses import CharbonnierLoss, PerceptualLoss | 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 (float): Weight of the perceptual loss
lr (float): Learning rate
"""
def __init__(self, net: nn.Module, num_input_frames: int = 5, pixel_loss_weight: float = 200,
perceptual_loss_weight: float = 1, lr: float = 2e-5):
super(ModelModule, self).__init__()
self.save_hyperparameters(ignore=["net"])
self.net = net
self.num_input_frames = num_input_frames
self.pixel_loss_weight = pixel_loss_weight
self.perceptual_loss_weight = perceptual_loss_weight
self.lr = lr
|
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 (float): Weight of the perceptual loss
lr (float): Learning rate
"""
def __init__(self, net: nn.Module, num_input_frames: int = 5, pixel_loss_weight: float = 200,
perceptual_loss_weight: float = 1, lr: float = 2e-5):
super(ModelModule, self).__init__()
self.save_hyperparameters(ignore=["net"])
self.net = net
self.num_input_frames = num_input_frames
self.pixel_loss_weight = pixel_loss_weight
self.perceptual_loss_weight = perceptual_loss_weight
self.lr = lr
| 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 rearrange
from einops import rearrange | 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 files will be generated in different directories of the evaluated file to save the results
def GPT_eval(data_path, gpt_output, model_name, eval_filename_prefix):
with open('./templates/eval_template2.json', 'r', encoding="utf8") as file:
template_eval = json.load(file)[0]
gpt_eval_score = []
save_dir = f"./data/{data_path}/"
if eval_filename_prefix is None and os.path.exists(f'{save_dir}gpt_output_score.json'):
with open(f'{save_dir}gpt_output_score.json', 'r', encoding="utf8") as file:
gpt_eval_score = json.load(file)
elif os.path.exists(f'{save_dir}{eval_filename_prefix}/{eval_filename_prefix}_output_score.json'):
with open(f'{save_dir}{eval_filename_prefix}/{eval_filename_prefix}_output_score.json', 'r', encoding="utf8") as file:
gpt_eval_score = json.load(file)
if len(gpt_eval_score) == len(gpt_output):
write_log=False
else:
write_log=True
gpt_output= gpt_output[len(gpt_eval_score):]
fail_index = []
for index, output in enumerate(tqdm(gpt_output)):
fail_times = 0
while True:
|
#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 files will be generated in different directories of the evaluated file to save the results
def GPT_eval(data_path, gpt_output, model_name, eval_filename_prefix):
with open('./templates/eval_template2.json', 'r', encoding="utf8") as file:
template_eval = json.load(file)[0]
gpt_eval_score = []
save_dir = f"./data/{data_path}/"
if eval_filename_prefix is None and os.path.exists(f'{save_dir}gpt_output_score.json'):
with open(f'{save_dir}gpt_output_score.json', 'r', encoding="utf8") as file:
gpt_eval_score = json.load(file)
elif os.path.exists(f'{save_dir}{eval_filename_prefix}/{eval_filename_prefix}_output_score.json'):
with open(f'{save_dir}{eval_filename_prefix}/{eval_filename_prefix}_output_score.json', 'r', encoding="utf8") as file:
gpt_eval_score = json.load(file)
if len(gpt_eval_score) == len(gpt_output):
write_log=False
else:
write_log=True
gpt_output= gpt_output[len(gpt_eval_score):]
fail_index = []
for index, output in enumerate(tqdm(gpt_output)):
fail_times = 0
while True: | 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':
ft_ignore_param = args.frozen_weights_mot
param_dicts = [
{
"params": [p for n, p in model_without_ddp.named_parameters() if p.requires_grad],
"lr": args.lr
}
]
else:
|
__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':
ft_ignore_param = args.frozen_weights_mot
param_dicts = [
{
"params": [p for n, p in model_without_ddp.named_parameters() if p.requires_grad],
"lr": args.lr
}
]
else: | 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.conftest import YieldFixture
from tests.conftest import get_ros_version | 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 and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
from __future__ import annotations
@pytest.fixture()
def _copy_success_launch_file_project(
rosenv_target_path: Path,
example_project_launch_files: Path,
) -> YieldFixture[None]:
target_folder = rosenv_target_path.parent / "src"
target_folder.mkdir(exist_ok=True, parents=True)
failing_project = example_project_launch_files / "src/launch_success"
assert failing_project.exists(), "Failing launch file project doesn't exist!"
shutil.copytree(failing_project, target_folder / "launch_success")
yield
shutil.rmtree(target_folder, ignore_errors=True)
@pytest.fixture()
def _copy_failing_launch_file_project(
rosenv_target_path: Path,
example_project_launch_files: Path,
) -> YieldFixture[None]:
target_folder = rosenv_target_path.parent / "src"
target_folder.mkdir(exist_ok=True, parents=True)
failing_project = example_project_launch_files / "src/launch_fails"
assert failing_project.exists(), "Failing launch file project doesn't exist!"
shutil.copytree(failing_project, target_folder / "launch_fails")
yield
shutil.rmtree(target_folder, ignore_errors=True)
| #
# 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 and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
from __future__ import annotations
@pytest.fixture()
def _copy_success_launch_file_project(
rosenv_target_path: Path,
example_project_launch_files: Path,
) -> YieldFixture[None]:
target_folder = rosenv_target_path.parent / "src"
target_folder.mkdir(exist_ok=True, parents=True)
failing_project = example_project_launch_files / "src/launch_success"
assert failing_project.exists(), "Failing launch file project doesn't exist!"
shutil.copytree(failing_project, target_folder / "launch_success")
yield
shutil.rmtree(target_folder, ignore_errors=True)
@pytest.fixture()
def _copy_failing_launch_file_project(
rosenv_target_path: Path,
example_project_launch_files: Path,
) -> YieldFixture[None]:
target_folder = rosenv_target_path.parent / "src"
target_folder.mkdir(exist_ok=True, parents=True)
failing_project = example_project_launch_files / "src/launch_fails"
assert failing_project.exists(), "Failing launch file project doesn't exist!"
shutil.copytree(failing_project, target_folder / "launch_fails")
yield
shutil.rmtree(target_folder, ignore_errors=True)
| @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.imagebind import data, ModalityType, imagebind_model
from prompt_model import Prompt_ImageBind | 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='', type=str, help='load origin model checkpoint from given path')
parser.add_argument('--prompt_resume', default='', type=str, help='load prompt model checkpoint from given path')
parser.add_argument('--device', default='cuda:0')
parser.add_argument('--num_workers', default=6, type=int)
# data settings
parser.add_argument("--type", type=str, default='style2image', help='choose train text2image or style2image.')
parser.add_argument("--style", type=str, default='sketch', help='choose sketch, art or mosaic.')
parser.add_argument("--test_dataset_path", type=str, default='DSR/')
parser.add_argument("--test_json_path", type=str, default='DSR/test.json')
parser.add_argument("--batch_size", type=int, default=24)
# model settings
parser.add_argument('--model', type=str, default='prompt', help='prompt-imagebind or imagebind-huge.')
parser.add_argument('--n_prompts', type=int, default=3)
parser.add_argument('--prompt_dim', type=int, default=50176)
args = parser.parse_args()
return args
def S2IRetrieval(args, model, ori_feat, pair_feat):
t1 = time.time()
if args.model == 'prompt':
ori_feat = model(ori_feat, dtype='image')
ske_feat = model(pair_feat, mode='image')
prob = torch.softmax(ske_feat @ ori_feat.T, dim=-1)
else:
with torch.no_grad():
ori_feat = model(ori_feat)
ske_feat = model(pair_feat)
prob = torch.softmax(ske_feat[ModalityType.VISION] @ ori_feat[ModalityType.VISION].T, dim=-1)
t2 = time.time()
print('inference a batch costs {}ms'.format((t2-t1)*1000))
return prob
def T2IRetrieval(args, model, ori_feat, pair_feat):
t1 = time.time()
if args.model == 'prompt':
ori_feat = model(ori_feat, dtype='image')
ske_feat = model(pair_feat, mode='text')
else:
with torch.no_grad():
ori_feat = model(ori_feat)
ske_feat = model(pair_feat)
prob = torch.softmax(ske_feat[ModalityType.TEXT] @ ori_feat[ModalityType.VISION].T, dim=-1)
t2 = time.time()
print('inference a batch costs {}ms'.format((t2-t1)*1000))
return prob
if __name__ == "__main__":
args = parse_args()
setup_seed(args.seed)
pair = json.load(open(args.test_json_path, 'r'))
if args.model == 'prompt':
model = Prompt_ImageBind(args)
model.load_state_dict(torch.load(args.prompt_resume))
else:
model = imagebind_model.imagebind_huge(args.origin_resume)
model.eval()
model.to(args.device)
r1 = []
r5 = []
rang = int(len(pair)/args.batch_size)
pre_process_val = image_transform(224, True, image_mean, image_std)
if args.type == 'text2image':
test_dataset = T2ITestDataset(args.test_dataset_path, args.test_json_path, pre_process_val)
else:
|
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='', type=str, help='load origin model checkpoint from given path')
parser.add_argument('--prompt_resume', default='', type=str, help='load prompt model checkpoint from given path')
parser.add_argument('--device', default='cuda:0')
parser.add_argument('--num_workers', default=6, type=int)
# data settings
parser.add_argument("--type", type=str, default='style2image', help='choose train text2image or style2image.')
parser.add_argument("--style", type=str, default='sketch', help='choose sketch, art or mosaic.')
parser.add_argument("--test_dataset_path", type=str, default='DSR/')
parser.add_argument("--test_json_path", type=str, default='DSR/test.json')
parser.add_argument("--batch_size", type=int, default=24)
# model settings
parser.add_argument('--model', type=str, default='prompt', help='prompt-imagebind or imagebind-huge.')
parser.add_argument('--n_prompts', type=int, default=3)
parser.add_argument('--prompt_dim', type=int, default=50176)
args = parser.parse_args()
return args
def S2IRetrieval(args, model, ori_feat, pair_feat):
t1 = time.time()
if args.model == 'prompt':
ori_feat = model(ori_feat, dtype='image')
ske_feat = model(pair_feat, mode='image')
prob = torch.softmax(ske_feat @ ori_feat.T, dim=-1)
else:
with torch.no_grad():
ori_feat = model(ori_feat)
ske_feat = model(pair_feat)
prob = torch.softmax(ske_feat[ModalityType.VISION] @ ori_feat[ModalityType.VISION].T, dim=-1)
t2 = time.time()
print('inference a batch costs {}ms'.format((t2-t1)*1000))
return prob
def T2IRetrieval(args, model, ori_feat, pair_feat):
t1 = time.time()
if args.model == 'prompt':
ori_feat = model(ori_feat, dtype='image')
ske_feat = model(pair_feat, mode='text')
else:
with torch.no_grad():
ori_feat = model(ori_feat)
ske_feat = model(pair_feat)
prob = torch.softmax(ske_feat[ModalityType.TEXT] @ ori_feat[ModalityType.VISION].T, dim=-1)
t2 = time.time()
print('inference a batch costs {}ms'.format((t2-t1)*1000))
return prob
if __name__ == "__main__":
args = parse_args()
setup_seed(args.seed)
pair = json.load(open(args.test_json_path, 'r'))
if args.model == 'prompt':
model = Prompt_ImageBind(args)
model.load_state_dict(torch.load(args.prompt_resume))
else:
model = imagebind_model.imagebind_huge(args.origin_resume)
model.eval()
model.to(args.device)
r1 = []
r5 = []
rang = int(len(pair)/args.batch_size)
pre_process_val = image_transform(224, True, image_mean, image_std)
if args.type == 'text2image':
test_dataset = T2ITestDataset(args.test_dataset_path, args.test_json_path, pre_process_val)
else: | 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class PromptTuningInit(str, enum.Enum):
TEXT = "TEXT"
RANDOM = "RANDOM"
@dataclass
class PromptTuningConfig(PromptLearningConfig):
"""
This is the configuration class to store the configuration of a [`PromptEmbedding`].
Args:
prompt_tuning_init (Union[[`PromptTuningInit`], `str`]): The initialization of the prompt embedding.
prompt_tuning_init_text (`str`, *optional*):
The text to initialize the prompt embedding. Only used if `prompt_tuning_init` is `TEXT`.
tokenizer_name_or_path (`str`, *optional*):
The name or path of the tokenizer. Only used if `prompt_tuning_init` is `TEXT`.
"""
prompt_tuning_init: Union[PromptTuningInit, str] = field(
default=PromptTuningInit.RANDOM,
metadata={"help": "How to initialize the prompt tuning parameters"},
)
prompt_tuning_init_text: Optional[str] = field(
default=None,
metadata={
"help": "The text to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`"
},
)
tokenizer_name_or_path: Optional[str] = field(
default=None,
metadata={
"help": "The tokenizer to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`"
},
)
def __post_init__(self):
| # coding=utf-8
# Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class PromptTuningInit(str, enum.Enum):
TEXT = "TEXT"
RANDOM = "RANDOM"
@dataclass
class PromptTuningConfig(PromptLearningConfig):
"""
This is the configuration class to store the configuration of a [`PromptEmbedding`].
Args:
prompt_tuning_init (Union[[`PromptTuningInit`], `str`]): The initialization of the prompt embedding.
prompt_tuning_init_text (`str`, *optional*):
The text to initialize the prompt embedding. Only used if `prompt_tuning_init` is `TEXT`.
tokenizer_name_or_path (`str`, *optional*):
The name or path of the tokenizer. Only used if `prompt_tuning_init` is `TEXT`.
"""
prompt_tuning_init: Union[PromptTuningInit, str] = field(
default=PromptTuningInit.RANDOM,
metadata={"help": "How to initialize the prompt tuning parameters"},
)
prompt_tuning_init_text: Optional[str] = field(
default=None,
metadata={
"help": "The text to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`"
},
)
tokenizer_name_or_path: Optional[str] = field(
default=None,
metadata={
"help": "The tokenizer to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`"
},
)
def __post_init__(self): | 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,
Union,
overload,
)
from urllib.parse import urlencode, urlsplit, urlunsplit
from typing import Literal
from typing_extensions import Literal
from voyageai import error, util, version
from voyageai.api_resources.voyage_response import VoyageResponse
from voyageai.util import ApiType | 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:
query = "%s&%s" % (base_query, query)
return urlunsplit((scheme, netloc, path, query, fragment))
def _requests_proxies_arg(proxy) -> Optional[Dict[str, str]]:
"""Returns a value suitable for the 'proxies' argument to 'requests.request."""
if proxy is None:
return None
elif isinstance(proxy, str):
return {"http": proxy, "https": proxy}
elif isinstance(proxy, dict):
return proxy.copy()
else:
raise ValueError(
"'voyageai.proxy' must be specified as either a string URL or a dict with string URL under the https and/or http keys."
)
def _aiohttp_proxies_arg(proxy) -> Optional[str]:
"""Returns a value suitable for the 'proxies' argument to 'aiohttp.ClientSession.request."""
if proxy is None:
return None
elif isinstance(proxy, str):
return proxy
elif isinstance(proxy, dict):
return proxy["https"] if "https" in proxy else proxy["http"]
else:
raise ValueError(
"'voyageai.proxy' must be specified as either a string URL or a dict with string URL under the https and/or http keys."
)
def _make_session() -> requests.Session:
if voyageai.requestssession:
if isinstance(voyageai.requestssession, requests.Session):
return voyageai.requestssession
return voyageai.requestssession()
if not voyageai.verify_ssl_certs:
warnings.warn("verify_ssl_certs is ignored; voyageai always verifies.")
s = requests.Session()
proxies = _requests_proxies_arg(voyageai.proxy)
if proxies:
s.proxies = proxies
s.mount(
"https://",
requests.adapters.HTTPAdapter(max_retries=MAX_CONNECTION_RETRIES),
)
return s
def parse_stream_helper(line: bytes) -> Optional[str]:
if line and line.startswith(b"data:"):
if line.startswith(b"data: "):
# SSE event may be valid when it contain whitespace
line = line[len(b"data: "):]
else:
line = line[len(b"data:"):]
if line.strip() == b"[DONE]":
# return here will cause GeneratorExit exception in urllib3
# and it will close http connection with TCP Reset
return None
else:
return line.decode("utf-8")
return None
def parse_stream(rbody: Iterator[bytes]) -> Iterator[str]:
for line in rbody:
_line = parse_stream_helper(line)
if _line is not None:
yield _line
async def parse_stream_async(rbody: aiohttp.StreamReader):
async for line in rbody:
_line = parse_stream_helper(line)
if _line is not None:
yield _line
class APIRequestor:
def __init__(
self,
key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
):
self.api_base = api_base or voyageai.api_base
|
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:
query = "%s&%s" % (base_query, query)
return urlunsplit((scheme, netloc, path, query, fragment))
def _requests_proxies_arg(proxy) -> Optional[Dict[str, str]]:
"""Returns a value suitable for the 'proxies' argument to 'requests.request."""
if proxy is None:
return None
elif isinstance(proxy, str):
return {"http": proxy, "https": proxy}
elif isinstance(proxy, dict):
return proxy.copy()
else:
raise ValueError(
"'voyageai.proxy' must be specified as either a string URL or a dict with string URL under the https and/or http keys."
)
def _aiohttp_proxies_arg(proxy) -> Optional[str]:
"""Returns a value suitable for the 'proxies' argument to 'aiohttp.ClientSession.request."""
if proxy is None:
return None
elif isinstance(proxy, str):
return proxy
elif isinstance(proxy, dict):
return proxy["https"] if "https" in proxy else proxy["http"]
else:
raise ValueError(
"'voyageai.proxy' must be specified as either a string URL or a dict with string URL under the https and/or http keys."
)
def _make_session() -> requests.Session:
if voyageai.requestssession:
if isinstance(voyageai.requestssession, requests.Session):
return voyageai.requestssession
return voyageai.requestssession()
if not voyageai.verify_ssl_certs:
warnings.warn("verify_ssl_certs is ignored; voyageai always verifies.")
s = requests.Session()
proxies = _requests_proxies_arg(voyageai.proxy)
if proxies:
s.proxies = proxies
s.mount(
"https://",
requests.adapters.HTTPAdapter(max_retries=MAX_CONNECTION_RETRIES),
)
return s
def parse_stream_helper(line: bytes) -> Optional[str]:
if line and line.startswith(b"data:"):
if line.startswith(b"data: "):
# SSE event may be valid when it contain whitespace
line = line[len(b"data: "):]
else:
line = line[len(b"data:"):]
if line.strip() == b"[DONE]":
# return here will cause GeneratorExit exception in urllib3
# and it will close http connection with TCP Reset
return None
else:
return line.decode("utf-8")
return None
def parse_stream(rbody: Iterator[bytes]) -> Iterator[str]:
for line in rbody:
_line = parse_stream_helper(line)
if _line is not None:
yield _line
async def parse_stream_async(rbody: aiohttp.StreamReader):
async for line in rbody:
_line = parse_stream_helper(line)
if _line is not None:
yield _line
class APIRequestor:
def __init__(
self,
key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
):
self.api_base = api_base or voyageai.api_base | 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_exceptionhandlers | 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 .utils import DataProcessor
from torch.utils.data import TensorDataset | 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_answer_text))
for new_start in range(input_start, input_end + 1):
for new_end in range(input_end, new_start - 1, -1):
text_span = " ".join(doc_tokens[new_start : (new_end + 1)])
if text_span == tok_answer_text:
return (new_start, new_end)
return (input_start, input_end)
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
def _new_check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# if len(doc_spans) == 1:
# return True
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span["start"] + doc_span["length"] - 1
if position < doc_span["start"]:
continue
if position > end:
continue
num_left_context = position - doc_span["start"]
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span["length"]
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
def _is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
def squad_convert_example_to_features(example, max_seq_length, doc_stride, max_query_length, is_training):
features = []
# print (is_training)
if is_training and not example.is_impossible:
# Get start and end position
start_position = example.start_position
end_position = example.end_position
# print (start_position, end_position, example.answer_text)
# If the answer cannot be found in the text, then skip this example.
actual_text = " ".join(example.doc_tokens[start_position : (end_position + 1)])
|
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_answer_text))
for new_start in range(input_start, input_end + 1):
for new_end in range(input_end, new_start - 1, -1):
text_span = " ".join(doc_tokens[new_start : (new_end + 1)])
if text_span == tok_answer_text:
return (new_start, new_end)
return (input_start, input_end)
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
def _new_check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# if len(doc_spans) == 1:
# return True
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span["start"] + doc_span["length"] - 1
if position < doc_span["start"]:
continue
if position > end:
continue
num_left_context = position - doc_span["start"]
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span["length"]
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
def _is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
def squad_convert_example_to_features(example, max_seq_length, doc_stride, max_query_length, is_training):
features = []
# print (is_training)
if is_training and not example.is_impossible:
# Get start and end position
start_position = example.start_position
end_position = example.end_position
# print (start_position, end_position, example.answer_text)
# If the answer cannot be found in the text, then skip this example.
actual_text = " ".join(example.doc_tokens[start_position : (end_position + 1)]) | 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,
ortho_init: bool = False,
):
super().__init__()
self.mlp = MLP(
state_space.shape[0],
action_space.shape[0],
hidden_layers=hidden_layers,
act=act,
output_act=output_act,
)
if ortho_init:
|
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,
ortho_init: bool = False,
):
super().__init__()
self.mlp = MLP(
state_space.shape[0],
action_space.shape[0],
hidden_layers=hidden_layers,
act=act,
output_act=output_act,
)
if ortho_init: | 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 = []
labels = []
messages = []
messages.extend(example["messages"])
for message in messages:
input_ids.append(user if message["role"] == "user" else assistant)
labels.append(IGNORE_INDEX)
content = tokenize(message["content"]) + [eot]
input_ids.extend(content)
labels.extend([IGNORE_INDEX]*len(content) if message["role"] == "user" else content)
input_ids.append(assistant)
labels.append(IGNORE_INDEX)
assert len(input_ids) == len(labels)
attention_mask = [1] * len(input_ids)
processed.append( {'input_ids':torch.LongTensor(input_ids), 'labels': torch.LongTensor(labels), 'attention_mask': torch.LongTensor(attention_mask)} )
return processed
class Assistant:
def __init__(self, model_name_or_path):
tokenizer = LlamaTokenizer.from_pretrained(model_name_or_path)
tokenizer.padding_side = "left"
tokenizer.user_token_id, tokenizer.assistant_token_id, tokenizer.eot_token_id \
= tokenizer.convert_tokens_to_ids(ATTR_TO_SPECIAL_TOKEN["additional_special_tokens"])
model = LlamaForCausalLM.from_pretrained(model_name_or_path, device_map="auto")
model.tie_weights()
model.eval()
self.tokenizer = tokenizer
self.model = model
self.seed = 0
# use greedy decoding as default
self.config = GenerationConfig(
max_new_tokens=1024,
min_length=1,
do_sample=False,
output_scores=True,
return_dict_in_generate=True,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=[tokenizer.bos_token_id, tokenizer.eos_token_id, tokenizer.unk_token_id,
tokenizer.eot_token_id, tokenizer.user_token_id, tokenizer.assistant_token_id],
)
set_seed(self.seed)
def inference(self, batch):
processed = process(batch, tokenizer=self.tokenizer)
|
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 = []
labels = []
messages = []
messages.extend(example["messages"])
for message in messages:
input_ids.append(user if message["role"] == "user" else assistant)
labels.append(IGNORE_INDEX)
content = tokenize(message["content"]) + [eot]
input_ids.extend(content)
labels.extend([IGNORE_INDEX]*len(content) if message["role"] == "user" else content)
input_ids.append(assistant)
labels.append(IGNORE_INDEX)
assert len(input_ids) == len(labels)
attention_mask = [1] * len(input_ids)
processed.append( {'input_ids':torch.LongTensor(input_ids), 'labels': torch.LongTensor(labels), 'attention_mask': torch.LongTensor(attention_mask)} )
return processed
class Assistant:
def __init__(self, model_name_or_path):
tokenizer = LlamaTokenizer.from_pretrained(model_name_or_path)
tokenizer.padding_side = "left"
tokenizer.user_token_id, tokenizer.assistant_token_id, tokenizer.eot_token_id \
= tokenizer.convert_tokens_to_ids(ATTR_TO_SPECIAL_TOKEN["additional_special_tokens"])
model = LlamaForCausalLM.from_pretrained(model_name_or_path, device_map="auto")
model.tie_weights()
model.eval()
self.tokenizer = tokenizer
self.model = model
self.seed = 0
# use greedy decoding as default
self.config = GenerationConfig(
max_new_tokens=1024,
min_length=1,
do_sample=False,
output_scores=True,
return_dict_in_generate=True,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=[tokenizer.bos_token_id, tokenizer.eos_token_id, tokenizer.unk_token_id,
tokenizer.eot_token_id, tokenizer.user_token_id, tokenizer.assistant_token_id],
)
set_seed(self.seed)
def inference(self, batch):
processed = process(batch, tokenizer=self.tokenizer) | 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
from ._generate_schema import GenerateSchema | 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 GenerateJsonSchemaHandler(GetJsonSchemaHandler):
"""JsonSchemaHandler implementation that doesn't do ref unwrapping by default.
This is used for any Annotated metadata so that we don't end up with conflicting
modifications to the definition schema.
Used internally by Pydantic, please do not rely on this implementation.
See `GetJsonSchemaHandler` for the handler API.
"""
def __init__(self, generate_json_schema: GenerateJsonSchema, handler_override: HandlerOverride | None) -> None:
self.generate_json_schema = generate_json_schema
self.handler = handler_override or generate_json_schema.generate_inner
self.mode = generate_json_schema.mode
def __call__(self, __core_schema: CoreSchemaOrField) -> JsonSchemaValue:
return self.handler(__core_schema)
def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue) -> JsonSchemaValue:
"""Resolves `$ref` in the json schema.
This returns the input json schema if there is no `$ref` in json schema.
Args:
maybe_ref_json_schema: The input json schema that may contains `$ref`.
Returns:
Resolved json schema.
Raises:
LookupError: If it can't find the definition for `$ref`.
"""
if '$ref' not in maybe_ref_json_schema:
return maybe_ref_json_schema
ref = maybe_ref_json_schema['$ref']
json_schema = self.generate_json_schema.get_schema_from_definitions(ref)
if json_schema is None:
raise LookupError(
f'Could not find a ref for {ref}.'
' Maybe you tried to call resolve_ref_schema from within a recursive model?'
)
return json_schema
| """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 GenerateJsonSchemaHandler(GetJsonSchemaHandler):
"""JsonSchemaHandler implementation that doesn't do ref unwrapping by default.
This is used for any Annotated metadata so that we don't end up with conflicting
modifications to the definition schema.
Used internally by Pydantic, please do not rely on this implementation.
See `GetJsonSchemaHandler` for the handler API.
"""
def __init__(self, generate_json_schema: GenerateJsonSchema, handler_override: HandlerOverride | None) -> None:
self.generate_json_schema = generate_json_schema
self.handler = handler_override or generate_json_schema.generate_inner
self.mode = generate_json_schema.mode
def __call__(self, __core_schema: CoreSchemaOrField) -> JsonSchemaValue:
return self.handler(__core_schema)
def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue) -> JsonSchemaValue:
"""Resolves `$ref` in the json schema.
This returns the input json schema if there is no `$ref` in json schema.
Args:
maybe_ref_json_schema: The input json schema that may contains `$ref`.
Returns:
Resolved json schema.
Raises:
LookupError: If it can't find the definition for `$ref`.
"""
if '$ref' not in maybe_ref_json_schema:
return maybe_ref_json_schema
ref = maybe_ref_json_schema['$ref']
json_schema = self.generate_json_schema.get_schema_from_definitions(ref)
if json_schema is None:
raise LookupError(
f'Could not find a ref for {ref}.'
' Maybe you tried to call resolve_ref_schema from within a recursive model?'
)
return json_schema
| 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 engine, and model.
"""
self.name = name
self.personality = personality
self.llm_engine = llm_engine
self.model = model
self.pip_skills = []
self.user_context_variables = user_context_variables
def _m(self, messages):
return llm_completion(model=self.model, messages=messages)
def set_user_context_variables(self, user_context_variables: dict = {}):
"""
Set the user context variables for the assistant.
Parameters:
user_context_variables (dict): A dictionary containing the user context variables.
"""
self.user_context_variables = user_context_variables
def add_pip_skill(self, pip_module):
"""
Add a new skill to the assistant.
"""
installed_packages = pkg_resources.working_set
installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages])
if pip_module not in installed_packages_list:
try:
installed_packages_pip_freeze = subprocess.check_output(["pip", "freeze"]).decode().split('\n')
if pip_module not in (package.split('==')[0] for package in installed_packages_pip_freeze) and pip_module not in (package.split('==')[0] for package in installed_packages_pip_freeze):
raise ImportError(f"Trying to add skill, but pip module {pip_module} is not installed. \nTo solve this try: pip install {pip_module}")
except subprocess.CalledProcessError:
raise ImportError(f"Failed to execute pip freeze.")
self.pip_skills.append(pip_module)
def question(self, text: str):
"""
Send a message to the assistant and return the assistant's response.
"""
response = self.generate_and_run_code_for_question(text)
return response
def start_conversation(self, user_name: str):
"""
Start a new conversation with the user.
"""
return Conversation(self, user_name)
def generate_and_run_code_for_question(self, question, retries_until_figured = 10):
arg_data = {
"context_variables": {key: "<...HIDDEN...>" for key in self.user_context_variables}
}
arg_data_all = {
"context_variables": self.user_context_variables
}
arguments_dictionary_str = create_string(arg_data)
modules_metadata = ", ".join(self.pip_skills)
instruction =INSTRUCTION.format(modules_metadata = modules_metadata, input_dictionary_string = arguments_dictionary_str, question=question)
logging.debug("[OTTO] Generated Instruction: " + instruction)
messages = [{"role": "system", "content": instruction}]
error = 1
code = ''
error_message = None
for _ in range(retries_until_figured):
if error_message:
messages += [{"role": "system", "content":"ran {code} and had this error: {error}".format(code=code, error=error_message)}]
logging.debug("[OTTO] Messages: \n" + json.dumps(messages, indent=4))
resp = self._m(messages)
code = resp['choices'][0]['message']['content']
error_message = None
try:
function_code = extract_python_code_from_md(code)
if function_code is not None:
code = function_code
logging.debug("[OTTO] Generated Code: \n```\n{code}\n\n```\n".format(code = code))
|
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 engine, and model.
"""
self.name = name
self.personality = personality
self.llm_engine = llm_engine
self.model = model
self.pip_skills = []
self.user_context_variables = user_context_variables
def _m(self, messages):
return llm_completion(model=self.model, messages=messages)
def set_user_context_variables(self, user_context_variables: dict = {}):
"""
Set the user context variables for the assistant.
Parameters:
user_context_variables (dict): A dictionary containing the user context variables.
"""
self.user_context_variables = user_context_variables
def add_pip_skill(self, pip_module):
"""
Add a new skill to the assistant.
"""
installed_packages = pkg_resources.working_set
installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages])
if pip_module not in installed_packages_list:
try:
installed_packages_pip_freeze = subprocess.check_output(["pip", "freeze"]).decode().split('\n')
if pip_module not in (package.split('==')[0] for package in installed_packages_pip_freeze) and pip_module not in (package.split('==')[0] for package in installed_packages_pip_freeze):
raise ImportError(f"Trying to add skill, but pip module {pip_module} is not installed. \nTo solve this try: pip install {pip_module}")
except subprocess.CalledProcessError:
raise ImportError(f"Failed to execute pip freeze.")
self.pip_skills.append(pip_module)
def question(self, text: str):
"""
Send a message to the assistant and return the assistant's response.
"""
response = self.generate_and_run_code_for_question(text)
return response
def start_conversation(self, user_name: str):
"""
Start a new conversation with the user.
"""
return Conversation(self, user_name)
def generate_and_run_code_for_question(self, question, retries_until_figured = 10):
arg_data = {
"context_variables": {key: "<...HIDDEN...>" for key in self.user_context_variables}
}
arg_data_all = {
"context_variables": self.user_context_variables
}
arguments_dictionary_str = create_string(arg_data)
modules_metadata = ", ".join(self.pip_skills)
instruction =INSTRUCTION.format(modules_metadata = modules_metadata, input_dictionary_string = arguments_dictionary_str, question=question)
logging.debug("[OTTO] Generated Instruction: " + instruction)
messages = [{"role": "system", "content": instruction}]
error = 1
code = ''
error_message = None
for _ in range(retries_until_figured):
if error_message:
messages += [{"role": "system", "content":"ran {code} and had this error: {error}".format(code=code, error=error_message)}]
logging.debug("[OTTO] Messages: \n" + json.dumps(messages, indent=4))
resp = self._m(messages)
code = resp['choices'][0]['message']['content']
error_message = None
try:
function_code = extract_python_code_from_md(code)
if function_code is not None:
code = function_code
logging.debug("[OTTO] Generated Code: \n```\n{code}\n\n```\n".format(code = code)) | 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 limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM,
OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE, OR OTHER DEALINGS IN
THE SOFTWARE.
"""
| """
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 limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM,
OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE, OR OTHER DEALINGS IN
THE SOFTWARE.
"""
| class 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 None
async def before_execution(self) -> None:
"""
Before executing new code. Called multiple times per run when using
steps.
"""
return None
async def before_response(self) -> None:
"""
After the output has been set and before the response is sent
back to Inngest. This is where you can perform any final actions before
the response is sent back to Inngest. Called multiple times per run when
using steps. Not called for function middleware.
"""
return None
async def transform_input(
self,
| 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 None
async def before_execution(self) -> None:
"""
Before executing new code. Called multiple times per run when using
steps.
"""
return None
async def before_response(self) -> None:
"""
After the output has been set and before the response is sent
back to Inngest. This is where you can perform any final actions before
the response is sent back to Inngest. Called multiple times per run when
using steps. Not called for function middleware.
"""
return None
async def transform_input(
self, | 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 an order n Konrod rule with error estimated
using an embedded n//2 order Gauss rule.
Parameters
----------
fun : callable
Function to integrate, should have a signature of the form
``fun(x, *args)`` -> float, Array. Should be JAX transformable.
a, b : float
Lower and upper limits of integration. Must be finite.
args : tuple, optional
Extra arguments passed to fun.
norm : int, callable
Norm to use for measuring error for vector valued integrands. No effect if the
integrand is scalar valued. If an int, uses p-norm of the given order, otherwise
should be callable.
n : {15, 21, 31, 41, 51, 61}
Order of integration scheme.
Returns
-------
y : float, Array
Estimate of the integral of fun from a to b
err : float
Estimate of the absolute error in y from nested Gauss rule.
y_abs : float, Array
Estimate of the integral of abs(fun) from a to b
y_mmn : float, Array
Estimate of the integral of abs(fun - <fun>) from a to b, where <fun>
is the mean value of fun over the interval.
"""
_norm = norm if callable(norm) else lambda x: jnp.linalg.norm(x.flatten(), ord=norm)
vfun = wrap_func(fun, args)
def truefun():
f = jax.eval_shape(vfun, jnp.array(0.0))
z = jnp.zeros(f.shape, f.dtype)
return z, 0.0, z, z
def falsefun():
try:
xk, wk, wg = (
| """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 an order n Konrod rule with error estimated
using an embedded n//2 order Gauss rule.
Parameters
----------
fun : callable
Function to integrate, should have a signature of the form
``fun(x, *args)`` -> float, Array. Should be JAX transformable.
a, b : float
Lower and upper limits of integration. Must be finite.
args : tuple, optional
Extra arguments passed to fun.
norm : int, callable
Norm to use for measuring error for vector valued integrands. No effect if the
integrand is scalar valued. If an int, uses p-norm of the given order, otherwise
should be callable.
n : {15, 21, 31, 41, 51, 61}
Order of integration scheme.
Returns
-------
y : float, Array
Estimate of the integral of fun from a to b
err : float
Estimate of the absolute error in y from nested Gauss rule.
y_abs : float, Array
Estimate of the integral of abs(fun) from a to b
y_mmn : float, Array
Estimate of the integral of abs(fun - <fun>) from a to b, where <fun>
is the mean value of fun over the interval.
"""
_norm = norm if callable(norm) else lambda x: jnp.linalg.norm(x.flatten(), ord=norm)
vfun = wrap_func(fun, args)
def truefun():
f = jax.eval_shape(vfun, jnp.array(0.0))
z = jnp.zeros(f.shape, f.dtype)
return z, 0.0, z, z
def falsefun():
try:
xk, wk, wg = ( | 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, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", type=int, default=None)
parser.add_argument("--bn_decay", type=float, default=0.9)
parser.add_argument("--channels", type=int, default=64)
parser.add_argument("--num_tasks_test", type=int, default=100)
parser.add_argument("--num_tasks_train", type=int, default=10000)
parser.add_argument("--num_tasks_valid", type=int, default=10)
parser.add_argument("--ways", type=int, default=5)
parser.add_argument("--shots_test", type=int, default=10)
parser.add_argument("--shots_train", type=int, default=10)
parser.add_argument("--first_order", type=bool, default=False)
parser.add_argument("--lr_inner", type=float, default=0.4)
parser.add_argument("--lr_outer", type=float, default=0.001)
parser.add_argument("--meta_batch_size", type=int, default=16)
parser.add_argument("--steps_inner", type=int, default=1)
parser.add_argument("--steps_outer", type=int, default=100)
parser.add_argument("--seed", type=int, default=2022)
args = parser.parse_args()
# Load data from [jax_meta](https://github.com/tristandeleu/jax-meta-learning)
metaloader = Omniglot(
DATAPATH,
batch_size=args.meta_batch_size,
shots=args.shots_train,
ways=args.ways,
)
metaloader.input_shape = metaloader.shape
metaloader.output_dim = metaloader.ways
metaloader.sample_input = jnp.array(metaloader.dummy_input)
# Define the loss, meta-model and meta-learning algorithm
base_model = metax.models.Conv4(args.channels, args.bn_decay, readout=args.ways)
meta_model = metax.module.LearnedInit(
loss_fn_inner=metax.energy.CrossEntropy(),
loss_fn_outer=metax.energy.CrossEntropy(),
base_learner=base_model,
reg_strength=None
)
meta_learner = metax.learner.ModelAgnosticMetaLearning(
meta_model=meta_model,
batch_size=args.batch_size,
steps_inner=args.steps_inner,
optim_fn_inner=optax.sgd(args.lr_inner),
optim_fn_outer=optax.adam(args.lr_outer),
first_order=args.first_order,
)
# Initialize
rng = jax.random.PRNGKey(args.seed)
rng_reset, rng_train, rng_test = jax.random.split(rng, 3)
meta_state = meta_learner.reset(rng_reset, metaloader.sample_input)
meta_update = jax.jit(meta_learner.update)
meta_eval = jax.jit(meta_learner.eval, static_argnames="steps")
# Train
for idx, batch in zip(range(args.steps_outer), metaloader):
# Mangle data into the format expected by metax
| """
Copyright (c) Simon Schug
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", type=int, default=None)
parser.add_argument("--bn_decay", type=float, default=0.9)
parser.add_argument("--channels", type=int, default=64)
parser.add_argument("--num_tasks_test", type=int, default=100)
parser.add_argument("--num_tasks_train", type=int, default=10000)
parser.add_argument("--num_tasks_valid", type=int, default=10)
parser.add_argument("--ways", type=int, default=5)
parser.add_argument("--shots_test", type=int, default=10)
parser.add_argument("--shots_train", type=int, default=10)
parser.add_argument("--first_order", type=bool, default=False)
parser.add_argument("--lr_inner", type=float, default=0.4)
parser.add_argument("--lr_outer", type=float, default=0.001)
parser.add_argument("--meta_batch_size", type=int, default=16)
parser.add_argument("--steps_inner", type=int, default=1)
parser.add_argument("--steps_outer", type=int, default=100)
parser.add_argument("--seed", type=int, default=2022)
args = parser.parse_args()
# Load data from [jax_meta](https://github.com/tristandeleu/jax-meta-learning)
metaloader = Omniglot(
DATAPATH,
batch_size=args.meta_batch_size,
shots=args.shots_train,
ways=args.ways,
)
metaloader.input_shape = metaloader.shape
metaloader.output_dim = metaloader.ways
metaloader.sample_input = jnp.array(metaloader.dummy_input)
# Define the loss, meta-model and meta-learning algorithm
base_model = metax.models.Conv4(args.channels, args.bn_decay, readout=args.ways)
meta_model = metax.module.LearnedInit(
loss_fn_inner=metax.energy.CrossEntropy(),
loss_fn_outer=metax.energy.CrossEntropy(),
base_learner=base_model,
reg_strength=None
)
meta_learner = metax.learner.ModelAgnosticMetaLearning(
meta_model=meta_model,
batch_size=args.batch_size,
steps_inner=args.steps_inner,
optim_fn_inner=optax.sgd(args.lr_inner),
optim_fn_outer=optax.adam(args.lr_outer),
first_order=args.first_order,
)
# Initialize
rng = jax.random.PRNGKey(args.seed)
rng_reset, rng_train, rng_test = jax.random.split(rng, 3)
meta_state = meta_learner.reset(rng_reset, metaloader.sample_input)
meta_update = jax.jit(meta_learner.update)
meta_eval = jax.jit(meta_learner.eval, static_argnames="steps")
# Train
for idx, batch in zip(range(args.steps_outer), metaloader):
# Mangle data into the format expected by metax | 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, \
load_results_consistency, get_consistency_results_path
from setup import project_setup
from consistency.Medalpaca.params_medalpaca import * | 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 format_question(d):
question = d["question"]
options = d["options"]
for k, v in options.items():
question += f"\n{k}: {v}"
return question
def strip_special_chars(input_str):
"Remove special characters from string start/end"
if not input_str:
return input_str
start_index = 0
end_index = len(input_str) - 1
while start_index < len(input_str) and input_str[
start_index] not in string.ascii_letters + string.digits:
start_index += 1
while end_index >= 0 and input_str[
end_index] not in string.ascii_letters + string.digits:
end_index -= 1
if start_index <= end_index:
return input_str[start_index:end_index + 1]
else:
return ""
def starts_with_capital_letter(input_str):
"""
The answers should start like this:
'A: '
'A. '
'A '
"""
pattern = r'^[A-Z](:|\.|) .+'
return bool(re.match(pattern, input_str))
def run_consistency_medalpaca():
path = get_consistency_results_path(args)
model = init_medalpaca_model(args)
sampling['temperature'] = args.temperature
examples = load_data_consistency(args)
|
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 format_question(d):
question = d["question"]
options = d["options"]
for k, v in options.items():
question += f"\n{k}: {v}"
return question
def strip_special_chars(input_str):
"Remove special characters from string start/end"
if not input_str:
return input_str
start_index = 0
end_index = len(input_str) - 1
while start_index < len(input_str) and input_str[
start_index] not in string.ascii_letters + string.digits:
start_index += 1
while end_index >= 0 and input_str[
end_index] not in string.ascii_letters + string.digits:
end_index -= 1
if start_index <= end_index:
return input_str[start_index:end_index + 1]
else:
return ""
def starts_with_capital_letter(input_str):
"""
The answers should start like this:
'A: '
'A. '
'A '
"""
pattern = r'^[A-Z](:|\.|) .+'
return bool(re.match(pattern, input_str))
def run_consistency_medalpaca():
path = get_consistency_results_path(args)
model = init_medalpaca_model(args)
sampling['temperature'] = args.temperature
examples = load_data_consistency(args)
| 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], meta_url: str, allow_cache: bool, save_path: str):
try:
temp_file_path = None
async with httpx.AsyncClient() as client:
with tempfile.NamedTemporaryFile(mode="wb", delete=False) as temp_file:
if not allow_cache:
temp_file = open(os.devnull, 'wb')
async with client.stream(
method="GET", url=meta_url,
headers=headers,
timeout=WORKER_API_TIMEOUT,
) as response:
response_headers = response.headers
yield response_headers
async for raw_chunk in response.aiter_raw():
if not raw_chunk:
continue
temp_file.write(raw_chunk)
yield raw_chunk
if not allow_cache:
temp_file_path = None
else:
temp_file_path = temp_file.name
if temp_file_path is not None:
shutil.copyfile(temp_file_path, save_path)
finally:
if temp_file_path is not None:
os.remove(temp_file_path)
async def meta_generator(app: FastAPI, repo_type: Literal["model", "dataset"], org: str, repo: str, commit: str, request: Request):
headers = {k: v for k, v in request.headers.items()}
headers.pop("host")
# save
repos_path = app.app_settings.repos_path
save_dir = os.path.join(repos_path, f"api/{repo_type}s/{org}/{repo}/revision/{commit}")
save_path = os.path.join(save_dir, "meta.json")
if not os.path.exists(save_dir):
os.makedirs(save_dir, exist_ok=True)
use_cache = os.path.exists(save_path)
|
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], meta_url: str, allow_cache: bool, save_path: str):
try:
temp_file_path = None
async with httpx.AsyncClient() as client:
with tempfile.NamedTemporaryFile(mode="wb", delete=False) as temp_file:
if not allow_cache:
temp_file = open(os.devnull, 'wb')
async with client.stream(
method="GET", url=meta_url,
headers=headers,
timeout=WORKER_API_TIMEOUT,
) as response:
response_headers = response.headers
yield response_headers
async for raw_chunk in response.aiter_raw():
if not raw_chunk:
continue
temp_file.write(raw_chunk)
yield raw_chunk
if not allow_cache:
temp_file_path = None
else:
temp_file_path = temp_file.name
if temp_file_path is not None:
shutil.copyfile(temp_file_path, save_path)
finally:
if temp_file_path is not None:
os.remove(temp_file_path)
async def meta_generator(app: FastAPI, repo_type: Literal["model", "dataset"], org: str, repo: str, commit: str, request: Request):
headers = {k: v for k, v in request.headers.items()}
headers.pop("host")
# save
repos_path = app.app_settings.repos_path
save_dir = os.path.join(repos_path, f"api/{repo_type}s/{org}/{repo}/revision/{commit}")
save_path = os.path.join(save_dir, "meta.json")
if not os.path.exists(save_dir):
os.makedirs(save_dir, exist_ok=True)
use_cache = os.path.exists(save_path) | 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(self, token: str) -> bool:
...
@abstractmethod
|
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(self, token: str) -> bool:
...
@abstractmethod | async def get_logins(self) -> List[Login]: | 1 | 2023-10-18 11:09:34+00:00 | 2k |
Subsets and Splits
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have consistent code formatting levels across multiple scales (2k, 4k, 8k, 12k) and reveals the structured formatting patterns within these repositories.
SQL Console for tianyang/repobench_python_v1.1
Compares cross-file and in-file code structure patterns across different complexity levels, revealing how file organization strategies vary with code size and potentially informing better code architecture decisions.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have complete performance data across all seven code complexity levels, revealing consistent benchmarking patterns across different code sizes.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that contain all 7 distinct quality levels (2k through 32k), revealing complete datasets that might be useful for comprehensive analysis.