id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
19,473
import logging import math import os from collections import OrderedDict import copy import math import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss import torch.nn.functional as F from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from torch.nn.parameter impor...
null
19,474
import logging import math import os from collections import OrderedDict import copy import math import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss import torch.nn.functional as F from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from torch.nn.parameter impor...
Original Implementation of the gelu activation function in Google Bert repo when initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in torch.nn....
19,475
import logging import math import os from collections import OrderedDict import argparse import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss import torch.nn.functional as F from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR, _LRScheduler def add_optimizer_para...
null
19,476
import logging import math import os from collections import OrderedDict import argparse import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss import torch.nn.functional as F from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR, _LRScheduler class AdamW(Optimizer):...
null
19,477
import logging import math import os from collections import OrderedDict import argparse import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss import torch.nn.functional as F from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR, _LRScheduler def create_sgd_optimiz...
null
19,478
import logging import math import os from collections import OrderedDict import argparse import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss import torch.nn.functional as F from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR, _LRScheduler class AdamW(Optimizer):...
null
19,479
import logging import math import os from collections import OrderedDict import argparse import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss import torch.nn.functional as F from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR, _LRScheduler class CosineAnnealingWa...
null
19,480
import argparse import time import math import os, sys import itertools import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist def add_gpu_params(parser: argparse.ArgumentParser): parser.add_argument("--platform", default='k8s', type=str, help='platform c...
null
19,481
import argparse import time import math import os, sys import itertools import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist def distributed_opt(args, model, opt, grad_acc=1): if args.platform == 'azure': args.hvd.broadcast_parameters(model.stat...
null
19,482
import argparse import time import math import os, sys import itertools import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist def parse_gpu(args): torch.manual_seed(args.random_seed) if args.platform == 'local': dist.init_process_group(b...
null
19,483
import argparse import time import math import os, sys import itertools import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist def cleanup(args): if args.platform == 'k8s' or args.platform == 'philly': args.dist.destroy_process_group()
null
19,484
import functools import os, shutil import numpy as np import torch def logging(s, log_path, print_=True, log_=True): if print_: print(s) if log_: with open(log_path, 'a+') as f_log: f_log.write(s + '\n') def get_logger(log_path, **kwargs): return functools.partial(logging, log_pa...
null
19,485
import functools import os, shutil import numpy as np import torch def save_checkpoint(model, optimizer, path, epoch): torch.save(model, os.path.join(path, 'model_{}.pt'.format(epoch))) torch.save(optimizer.state_dict(), os.path.join(path, 'optimizer_{}.pt'.format(epoch)))
null
19,486
import os import json import regex as re from functools import lru_cache The provided code snippet includes necessary dependencies for implementing the `bytes_to_unicode` function. Write a Python function `def bytes_to_unicode()` to solve the following problem: Returns list of utf-8 byte and a corresponding list of un...
Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This ...
19,487
import os import json import regex as re from functools import lru_cache The provided code snippet includes necessary dependencies for implementing the `get_pairs` function. Write a Python function `def get_pairs(word)` to solve the following problem: Return set of symbol pairs in a word. Word is represented as tuple ...
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
19,488
import os import json import regex as re from functools import lru_cache class Encoder: def __init__(self, encoder, bpe_merges, errors='replace'): self.encoder = encoder self.decoder = {v:k for k,v in self.encoder.items()} self.errors = errors # how to handle errors in decoding self....
null
19,489
import sys import argparse import codecs import copy import os import pyter import logging import nltk import subprocess import re from bert_score import score from metrics.chrF import computeChrF from metrics.bleurt.bleurt import score as bleurt_score from nltk.translate.bleu_score import corpus_bleu, SmoothingFunctio...
null
19,490
argparse import json import logging import math import os import random from pathlib import Path import datasets import torch from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from tqdm.auto import tqdm import transformers from accelerate import Accelerator from accelerate.logging i...
null
19,491
import os import torch import torch.nn as nn from collections import OrderedDict from pst.sparse import SparseLinear def _setattr(model, name, module): name_list = name.split(".") for name in name_list[:-1]: model = getattr(model, name) setattr(model, name_list[-1], module) class SparseLinear(nn.Li...
null
19,492
import argparse import glob import json import logging import os import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from torch.utils.data.distributed import DistributedSampler from t...
Train the model
19,493
import argparse import glob import logging import os import random import timeit import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from torch.utils.data.distributed import DistributedSampler from...
Train the model
19,494
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import load_dataset, load_metric import torch import transformers from trainer_qa import QuestionAnsweringTrainer from transformers import ( AutoConfig, AutoModelForQuestionAnswering, AutoT...
null
19,498
import torch from torch.utils.data import DataLoader, SequentialSampler import numpy as np from itertools import islice from tqdm import tqdm from math import sqrt from collections import defaultdict The provided code snippet includes necessary dependencies for implementing the `determine_pruning_sequence` function. W...
Same ratio for attention heads and MLPs
19,499
import torch from torch.utils.data import DataLoader, SequentialSampler import numpy as np from itertools import islice from tqdm import tqdm from math import sqrt from collections import defaultdict def calculate_head_and_intermediate_importance( model, dataset, old_head_mask, old_intermediate_mask, ...
null
19,500
import torch from torch.utils.data import DataLoader, SequentialSampler import numpy as np from itertools import islice from tqdm import tqdm from math import sqrt from collections import defaultdict def what_to_prune_head( head_importance, n_to_prune, old_head_mask, at_least_x_heads_per_layer=1, ): ...
null
19,501
import torch from torch.utils.data import DataLoader, SequentialSampler import numpy as np from itertools import islice from tqdm import tqdm from math import sqrt from collections import defaultdict def what_to_prune_mlp( intermediate_importance, n_to_prune, old_intermediate_mask ): intermediate_impor...
null
19,502
import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import torch import numpy as np from datasets import load_dataset, load_metric import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, ...
null
19,503
import collections import json import logging import os from typing import Optional, Tuple import numpy as np from tqdm.auto import tqdm logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `postprocess_qa_predictions` function. Write a Python function `de...
Post-processes the predictions of a question-answering model to convert them to answers that are substrings of the original contexts. This is the base postprocessing functions for models that only return start and end logits. Args: examples: The non-preprocessed dataset (see the main script for more information). featu...
19,504
import collections import json import logging import os from typing import Optional, Tuple import numpy as np from tqdm.auto import tqdm logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `postprocess_qa_predictions_with_beam_search` function. Write a Py...
Post-processes the predictions of a question-answering model with beam search to convert them to answers that are substrings of the original contexts. This is the postprocessing functions for models that return start and end logits, indices, as well as cls token predictions. Args: examples: The non-preprocessed dataset...
19,505
import torch.nn as nn import torch import inspect from transformers.models.bert import BertPreTrainedModel from transformers.models.bert.modeling_bert import BertEmbeddings, BertPooler, BaseModelOutputWithPoolingAndCrossAttentions, BertAttention, BertIntermediate, BaseModelOutputWithPastAndCrossAttentions from typing i...
This function chunks the :obj:`input_tensors` into smaller input tensor parts of size :obj:`chunk_size` over the dimension :obj:`chunk_dim`. It then applies a layer :obj:`forward_fn` to each chunk independently to save memory. If the :obj:`forward_fn` is independent across the :obj:`chunk_dim` this function will yield ...
19,506
import argparse import json import re import string import sys from collections import Counter def f1_score(prediction, ground_truth): def exact_match_score(prediction, ground_truth): def metric_max_over_ground_truths(metric_fn, prediction, ground_truths): def evaluate(dataset, predictions): f1 = exact_match = tot...
null
19,507
import math import torch from torch.optim import Optimizer from torch.nn.utils import clip_grad_norm_ def warmup_cosine(x, warmup=0.002): if x < warmup: return x/warmup return 0.5 * (1.0 + torch.cos(math.pi * x))
null
19,508
import math import torch from torch.optim import Optimizer from torch.nn.utils import clip_grad_norm_ def warmup_constant(x, warmup=0.002): if x < warmup: return x/warmup return 1.0
null
19,509
import math import torch from torch.optim import Optimizer from torch.nn.utils import clip_grad_norm_ def warmup_linear(x, warmup=0.002): if x < warmup: return x/warmup return 1.0 - x def schedule_func(sch): try: f = eval(sch) except: f = warmup_linear return f
null
19,510
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import unicodedata import six The provided code snippet includes necessary dependencies for implementing the `printable_text` function. Write a Python function `def printable_text(text)` to s...
Returns text encoded in a way suitable for print or `tf.logging`.
19,511
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import unicodedata import six def convert_to_unicode(text): """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" if six.PY3: if isinstance(text, str): ...
Loads a vocabulary file into a dictionary.
19,512
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import unicodedata import six The provided code snippet includes necessary dependencies for implementing the `whitespace_tokenize` function. Write a Python function `def whitespace_tokenize(t...
Runs basic whitespace cleaning and splitting on a peice of text.
19,513
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import unicodedata import six The provided code snippet includes necessary dependencies for implementing the `_is_whitespace` function. Write a Python function `def _is_whitespace(char)` to s...
Checks whether `chars` is a whitespace character.
19,514
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import unicodedata import six The provided code snippet includes necessary dependencies for implementing the `_is_control` function. Write a Python function `def _is_control(char)` to solve t...
Checks whether `chars` is a control character.
19,515
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import unicodedata import six The provided code snippet includes necessary dependencies for implementing the `_is_punctuation` function. Write a Python function `def _is_punctuation(char)` to...
Checks whether `chars` is a punctuation character.
19,516
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import logging import argparse import random from tqdm import tqdm, trange import sys import torch import json from torch.utils.data import Dataset, Sampler, TensorDataset, DataLoader, Rando...
null
19,517
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import logging import argparse import random from tqdm import tqdm, trange import sys import torch import json from torch.utils.data import Dataset, Sampler, TensorDataset, DataLoader, Rando...
Loads a data file into a list of `InputBatch`s.
19,518
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import logging import argparse import random from tqdm import tqdm, trange import sys import torch import json from torch.utils.data import Dataset, Sampler, TensorDataset, DataLoader, Rando...
null
19,519
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import logging import argparse import random from tqdm import tqdm, trange import sys import torch import json from torch.utils.data import Dataset, Sampler, TensorDataset, DataLoader, Rando...
null
19,520
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import logging import argparse import random from tqdm import tqdm, trange import sys import torch import json from torch.utils.data import Dataset, Sampler, TensorDataset, DataLoader, Rando...
Utility function for optimize_on_cpu and 16-bits training. Copy the parameters optimized on CPU/RAM back to the model on GPU
19,521
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import logging import argparse import random from tqdm import tqdm, trange import sys import torch import json from torch.utils.data import Dataset, Sampler, TensorDataset, DataLoader, Rando...
Utility function for optimize_on_cpu and 16-bits training. Copy the gradient of the GPU parameters to the CPU/RAMM copy of the model
19,522
from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import json import math import six import torch import torch.nn as nn import torch.utils.checkpoint from torch.nn import CrossEntropyLoss import torch.nn.functional as F import numpy as np The provi...
Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
19,523
from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import json import math import six import torch import torch.nn as nn import torch.utils.checkpoint from torch.nn import CrossEntropyLoss import torch.nn.functional as F import numpy as np def dim_d...
null
19,524
import collections.abc as collections from pathlib import Path from types import SimpleNamespace from typing import Callable, List, Optional, Tuple, Union import cv2 import kornia import numpy as np import torch def read_image(path: Path, grayscale: bool = False) -> np.ndarray: """Read an image from path as RGB or ...
null
19,525
import collections.abc as collections from pathlib import Path from types import SimpleNamespace from typing import Callable, List, Optional, Tuple, Union import cv2 import kornia import numpy as np import torch def batch_to_device(batch: dict, device: str = "cpu", non_blocking: bool = True): """Move batch (dict) t...
Match a pair of images (image0, image1) with an extractor and matcher
19,526
from typing import Callable, Optional import torch import torch.nn.functional as F import torchvision from kornia.color import grayscale_to_rgb from torch import nn from torch.nn.modules.utils import _pair from torchvision.models import resnet from .utils import Extractor def get_patches( tensor: torch.Tensor, req...
null
19,527
from typing import Callable, Optional import torch import torch.nn.functional as F import torchvision from kornia.color import grayscale_to_rgb from torch import nn from torch.nn.modules.utils import _pair from torchvision.models import resnet from .utils import Extractor The provided code snippet includes necessary d...
Fast Non-maximum suppression to remove nearby points
19,528
from typing import Callable, Optional import torch import torch.nn.functional as F import torchvision from kornia.color import grayscale_to_rgb from torch import nn from torch.nn.modules.utils import _pair from torchvision.models import resnet from .utils import Extractor class DeformableConv2d(nn.Module): def __in...
null
19,529
import matplotlib import matplotlib.patheffects as path_effects import matplotlib.pyplot as plt import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `cm_RdGn` function. Write a Python function `def cm_RdGn(x)` to solve the following problem: Custom colormap: re...
Custom colormap: red (0) -> yellow (0.5) -> green (1).
19,530
import matplotlib import matplotlib.patheffects as path_effects import matplotlib.pyplot as plt import numpy as np import torch def cm_BlRdGn(x_): """Custom colormap: blue (-1) -> red (0.0) -> green (1).""" x = np.clip(x_, 0, 1)[..., None] * 2 c = x * np.array([[0, 1.0, 0, 1.0]]) + (2 - x) * np.array([[1.0,...
Custom colormap to visualize pruning
19,531
import matplotlib import matplotlib.patheffects as path_effects import matplotlib.pyplot as plt import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `plot_images` function. Write a Python function `def plot_images(imgs, titles=None, cmaps="gray", dpi=100, pad=0...
Plot a set of images horizontally. Args: imgs: list of NumPy RGB (H, W, 3) or PyTorch RGB (3, H, W) or mono (H, W). titles: a list of strings, as titles for each image. cmaps: colormaps for monochrome images. adaptive: whether the figure size should fit the image aspect ratios.
19,532
import matplotlib import matplotlib.patheffects as path_effects import matplotlib.pyplot as plt import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `plot_keypoints` function. Write a Python function `def plot_keypoints(kpts, colors="lime", ps=4, axes=None, a=1...
Plot keypoints for existing images. Args: kpts: list of ndarrays of size (N, 2). colors: string, or list of list of tuples (one for each keypoints). ps: size of the keypoints as float.
19,533
import matplotlib import matplotlib.patheffects as path_effects import matplotlib.pyplot as plt import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `plot_matches` function. Write a Python function `def plot_matches(kpts0, kpts1, color=None, lw=1.5, ps=4, a=1.0...
Plot matches for a pair of existing images. Args: kpts0, kpts1: corresponding keypoints of size (N, 2). color: color of each match, string or RGB tuple. Random if not given. lw: width of the lines. ps: size of the end points (no endpoint if ps=0) indices: indices of the images to draw the matches on. a: alpha opacity o...
19,534
import matplotlib import matplotlib.patheffects as path_effects import matplotlib.pyplot as plt import numpy as np import torch def add_text( idx, text, pos=(0.01, 0.99), fs=15, color="w", lcolor="k", lwidth=2, ha="left", va="top", ): ax = plt.gcf().axes[idx] t = ax.text( ...
null
19,535
import matplotlib import matplotlib.patheffects as path_effects import matplotlib.pyplot as plt import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `save_plot` function. Write a Python function `def save_plot(path, **kw)` to solve the following problem: Save t...
Save the current figure without any white margin.
19,536
import torch from kornia.color import rgb_to_grayscale from torch import nn from .utils import Extractor The provided code snippet includes necessary dependencies for implementing the `simple_nms` function. Write a Python function `def simple_nms(scores, nms_radius: int)` to solve the following problem: Fast Non-maxim...
Fast Non-maximum suppression to remove nearby points
19,537
import torch from kornia.color import rgb_to_grayscale from torch import nn from .utils import Extractor def top_k_keypoints(keypoints, scores, k): if k >= len(keypoints): return keypoints, scores scores, indices = torch.topk(scores, k, dim=0, sorted=True) return keypoints[indices], scores
null
19,538
import torch from kornia.color import rgb_to_grayscale from torch import nn from .utils import Extractor The provided code snippet includes necessary dependencies for implementing the `sample_descriptors` function. Write a Python function `def sample_descriptors(keypoints, descriptors, s: int = 8)` to solve the follow...
Interpolate descriptors at keypoint locations
19,539
import warnings import cv2 import numpy as np import torch from kornia.color import rgb_to_grayscale from packaging import version from .utils import Extractor def filter_dog_point(points, scales, angles, image_shape, nms_radius, scores=None): h, w = image_shape ij = np.round(points - 0.5).astype(int).T[::-1] ...
null
19,540
import warnings import cv2 import numpy as np import torch from kornia.color import rgb_to_grayscale from packaging import version from .utils import Extractor def sift_to_rootsift(x: torch.Tensor, eps=1e-6) -> torch.Tensor: x = torch.nn.functional.normalize(x, p=1, dim=-1, eps=eps) x.clip_(min=eps).sqrt_() ...
null
19,541
import warnings import cv2 import numpy as np import torch from kornia.color import rgb_to_grayscale from packaging import version from .utils import Extractor The provided code snippet includes necessary dependencies for implementing the `run_opencv_sift` function. Write a Python function `def run_opencv_sift(feature...
Detect keypoints using OpenCV Detector. Optionally, perform description. Args: features: OpenCV based keypoints detector and descriptor image: Grayscale image of uint8 data type Returns: keypoints: 1D array of detected cv2.KeyPoint scores: 1D array of responses descriptors: 1D array of descriptors
19,542
import warnings from pathlib import Path from types import SimpleNamespace from typing import Callable, List, Optional, Tuple import numpy as np import torch import torch.nn.functional as F from torch import nn torch.backends.cudnn.deterministic = True def normalize_keypoints( kpts: torch.Tensor, size: Optional[to...
null
19,543
import warnings from pathlib import Path from types import SimpleNamespace from typing import Callable, List, Optional, Tuple import numpy as np import torch import torch.nn.functional as F from torch import nn torch.backends.cudnn.deterministic = True def pad_to_length(x: torch.Tensor, length: int) -> Tuple[torch.Ten...
null
19,544
import warnings from pathlib import Path from types import SimpleNamespace from typing import Callable, List, Optional, Tuple import numpy as np import torch import torch.nn.functional as F from torch import nn torch.backends.cudnn.deterministic = True def rotate_half(x: torch.Tensor) -> torch.Tensor: x = x.unflatt...
null
19,545
import warnings from pathlib import Path from types import SimpleNamespace from typing import Callable, List, Optional, Tuple import numpy as np import torch import torch.nn.functional as F from torch import nn torch.backends.cudnn.deterministic = True The provided code snippet includes necessary dependencies for impl...
create the log assignment matrix from logits and similarity
19,546
import warnings from pathlib import Path from types import SimpleNamespace from typing import Callable, List, Optional, Tuple import numpy as np import torch import torch.nn.functional as F from torch import nn torch.backends.cudnn.deterministic = True The provided code snippet includes necessary dependencies for impl...
obtain matches from a log assignment matrix [Bx M+1 x N+1]
19,547
import argparse import time from collections import defaultdict from pathlib import Path import matplotlib.pyplot as plt import numpy as np import torch import torch._dynamo from lightglue import LightGlue, SuperPoint from lightglue.utils import load_image torch.set_grad_enabled(False) def measure(matcher, data, devic...
null
19,548
import argparse import time from collections import defaultdict from pathlib import Path import matplotlib.pyplot as plt import numpy as np import torch import torch._dynamo from lightglue import LightGlue, SuperPoint from lightglue.utils import load_image def print_as_table(d, title, cnames): print() header =...
null
19,549
from collections import Counter from pathlib import Path from loguru import logger from eaio import __electron_source__ from eaio.function.link import link as link_, unlink as unlink_ from eaio.function.check import get_repos_status, find_app_entries, get_files_link_status from eaio.function.download import download_el...
null
19,550
from collections import Counter from pathlib import Path from loguru import logger from eaio import __electron_source__ from eaio.function.link import link as link_, unlink as unlink_ from eaio.function.check import get_repos_status, find_app_entries, get_files_link_status from eaio.function.download import download_el...
null
19,551
from collections import Counter from pathlib import Path from loguru import logger from eaio import __electron_source__ from eaio.function.link import link as link_, unlink as unlink_ from eaio.function.check import get_repos_status, find_app_entries, get_files_link_status from eaio.function.download import download_el...
null
19,552
import argparse from pathlib import Path import sys from loguru import logger from eaio import __fullname__, __description__, __electron_repo_root__, __electron_source__ from eaio.entry.gui import gui from eaio.entry.cli import link, unlink, check, status, download from eaio.util.utils import to_drive, log log = io.St...
null
19,553
import sys import json from typing import Optional import cv2 import torch from PIL import Image import mmcv from mmdet.core.visualization.image import imshow_det_bboxes import numpy as np import pycocotools.mask as maskUtils from transformers import CLIPProcessor, CLIPModel from transformers import AutoProcessor, CLIP...
null
19,554
import torch.nn.functional as F def segformer_segmentation(image, processor, model, rank): h, w, _ = image.shape inputs = processor(images=image, return_tensors="pt").to(rank) outputs = model(**inputs) logits = outputs.logits logits = F.interpolate(logits, size=(h, w), mode='bilinear', align_corner...
null
19,555
import torch import torch.nn as nn import torch.nn.functional as F from tqdm import tqdm from mmseg.core import add_prefix from mmseg.ops import resize from mmcv.utils import print_log import os import mmcv import argparse import numpy as np from collections import OrderedDict import pycocotools.mask as maskUtils from ...
null
19,556
import torch import torch.nn.functional as F def oneformer_cityscapes_segmentation(image, oneformer_cityscapes_processor, oneformer_cityscapes_model, rank): inputs = oneformer_cityscapes_processor(images=image, task_inputs=["semantic"], return_tensors="pt").to(rank) outputs = oneformer_cityscapes_model(**input...
null
19,557
import os import argparse import torch from segment_anything import sam_model_registry, SamAutomaticMaskGenerator from pipeline import semantic_segment_anything_inference, eval_pipeline, img_load from configs.ade20k_id2label import CONFIG as CONFIG_ADE20K_ID2LABEL from configs.cityscapes_id2label import CONFIG as CONFI...
null
19,558
import os import torch import torch.nn.functional as F from PIL import Image import mmcv from tqdm import tqdm from mmcv.utils import print_log from mmdet.core.visualization.image import imshow_det_bboxes from mmseg.core import intersect_and_union, pre_eval_to_metrics from collections import OrderedDict from prettytabl...
null
19,559
import os import torch import torch.nn.functional as F from PIL import Image import mmcv from tqdm import tqdm from mmcv.utils import print_log from mmdet.core.visualization.image import imshow_det_bboxes from mmseg.core import intersect_and_union, pre_eval_to_metrics from collections import OrderedDict from prettytabl...
null
19,560
import os import torch import torch.nn.functional as F from PIL import Image import mmcv from tqdm import tqdm from mmcv.utils import print_log from mmdet.core.visualization.image import imshow_det_bboxes from mmseg.core import intersect_and_union, pre_eval_to_metrics from collections import OrderedDict from prettytabl...
null
19,561
import os import torch import torch.nn.functional as F from PIL import Image import mmcv from tqdm import tqdm from mmcv.utils import print_log from mmdet.core.visualization.image import imshow_det_bboxes from mmseg.core import intersect_and_union, pre_eval_to_metrics from collections import OrderedDict from prettytabl...
null
19,562
import os import torch import argparse from pipeline import semantic_annotation_pipeline from transformers import CLIPProcessor, CLIPModel from transformers import AutoProcessor, CLIPSegForImageSegmentation from transformers import OneFormerProcessor, OneFormerForUniversalSegmentation from transformers import BlipProce...
null
19,563
import os import numpy from setuptools import find_packages, setup, Extension def read(rel_path: str) -> str: here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, rel_path), encoding="utf-8") as fp: return fp.read() def get_version(rel_path: str) -> str: for line in read(r...
null
19,564
from ...data.dataset.handler import DataHandlerLP from ...data.dataset.processor import Processor from ...utils import get_callable_kwargs from ...data.dataset import processor as processor_module from inspect import getfullargspec class Processor(Serializable): def fit(self, df: pd.DataFrame = None): """ ...
null
19,565
import copy import torch import warnings import numpy as np import pandas as pd from qlib.data.dataset import DatasetH device = "cuda" if torch.cuda.is_available() else "cpu" def _to_tensor(x): if not isinstance(x, torch.Tensor): return torch.tensor(x, dtype=torch.float, device=device) # pylint: disable=E...
null
19,566
import copy import torch import warnings import numpy as np import pandas as pd from qlib.data.dataset import DatasetH The provided code snippet includes necessary dependencies for implementing the `_create_ts_slices` function. Write a Python function `def _create_ts_slices(index, seq_len)` to solve the following prob...
create time series slices from pandas index Args: index (pd.MultiIndex): pandas multiindex with <instrument, datetime> order seq_len (int): sequence length
19,567
import copy import torch import warnings import numpy as np import pandas as pd from qlib.data.dataset import DatasetH The provided code snippet includes necessary dependencies for implementing the `_get_date_parse_fn` function. Write a Python function `def _get_date_parse_fn(target)` to solve the following problem: g...
get date parse function This method is used to parse date arguments as target type. Example: get_date_parse_fn('20120101')('2017-01-01') => '20170101' get_date_parse_fn(20120101)('2017-01-01') => 20170101
19,568
import copy import torch import warnings import numpy as np import pandas as pd from qlib.data.dataset import DatasetH The provided code snippet includes necessary dependencies for implementing the `_maybe_padding` function. Write a Python function `def _maybe_padding(x, seq_len, zeros=None)` to solve the following pr...
padding 2d <time * feature> data with zeros Args: x (np.ndarray): 2d data with shape <time * feature> seq_len (int): target sequence length zeros (np.ndarray): zeros with shape <seq_len * feature>
19,569
import pandas as pd from typing import Dict, Iterable, Union import builtins def align_index(df_dict, join): res = {} for k, df in df_dict.items(): if join is not None and k != join: df = df.reindex(df_dict[join].index) res[k] = df return res
null
19,570
import pandas as pd from typing import Dict, Iterable, Union class SepDataFrame: """ (Sep)erate DataFrame We usually concat multiple dataframe to be processed together(Such as feature, label, weight, filter). However, they are usually be used separately at last. This will result in extra cost for co...
null
19,571
import argparse import importlib import os import yaml from .config import TunerConfigManager TUNER_CONFIG_MANAGER = TunerConfigManager(args.config_path) def run(): # 1. Get pipeline class. tuner_pipeline_class = getattr(importlib.import_module(".pipeline", package="qlib.contrib.tuner"), "Pipeline") # 2. I...
null
19,572
import pathlib import pickle import yaml import pandas as pd from ...data import D from ...config import C from ...log import get_module_logger from ...utils import get_next_trading_date from ...backtest.exchange import Exchange The provided code snippet includes necessary dependencies for implementing the `load_insta...
load a pickle file Parameter file_path : string / pathlib.Path() path of file to be loaded :return An instance loaded from file
19,573
import pathlib import pickle import yaml import pandas as pd from ...data import D from ...config import C from ...log import get_module_logger from ...utils import get_next_trading_date from ...backtest.exchange import Exchange C = QlibConfig(_default_config) The provided code snippet includes necessary dependencies...
save(dump) an instance to a pickle file Parameter instance : data to be dumped file_path : string / pathlib.Path() path of file to be dumped
19,574
import pathlib import pickle import yaml import pandas as pd from ...data import D from ...config import C from ...log import get_module_logger from ...utils import get_next_trading_date from ...backtest.exchange import Exchange def create_user_folder(path): path = pathlib.Path(path) if path.exists(): ...
null
19,575
import pathlib import pickle import yaml import pandas as pd from ...data import D from ...config import C from ...log import get_module_logger from ...utils import get_next_trading_date from ...backtest.exchange import Exchange log = get_module_logger("utils") def get_next_trading_date(trading_date, future=False): ...
1. Get the dates that need to do trading till today for user {user_id} dates[0] indicate the latest trading date of User{user_id}, if User{user_id} haven't do trading before, than dates[0] presents the init date of User{user_id}. 2. Set the exchange with exchange_config file Parameter um : UserManager() today : pd.Time...