id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
26,089
import torch import torch.nn as nn import math import torch.utils.model_zoo as model_zoo model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 'resnet152': 'https://download.pytorch.org/models/resnet...
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
26,090
import torch import torch.nn as nn import math import torch.utils.model_zoo as model_zoo model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 'resnet152': 'https://download.pytorch.org/models/resnet...
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
26,091
import torch import torch.nn as nn import math import torch.utils.model_zoo as model_zoo model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 'resnet152': 'https://download.pytorch.org/models/resnet...
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
26,092
import math import torch from torch import nn The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1)` to solve the following problem: 3x3 convolution with padding Here is the function: def conv3x3(in_pla...
3x3 convolution with padding
26,093
import os def gen_train_file(data_root, train_file): train_file_buf = open(train_file, 'w') id_list = os.listdir(data_root) id_list.sort() for label, id_name in enumerate(id_list): cur_id_folder = os.path.join(data_root, id_name) cur_img_list = os.listdir(cur_id_folder) cur_img_...
null
26,094
import os import sys import shutil import argparse import logging as logger import torch from torch import optim from torch.utils.data import DataLoader from loss_def import MVFace from utils.dataset import ImageDataset from utils.AverageMeter import AverageMeter from utils.make_transform import make_transform def trai...
null
26,095
import os import random import cv2 import torch import numpy as np from torch.utils.data import Dataset from PIL import Image, ImageFile The provided code snippet includes necessary dependencies for implementing the `read_image` function. Write a Python function `def read_image(img_path)` to solve the following proble...
Keep reading image until succeed. This can avoid IOError incurred by heavy IO process.
26,096
import os import gc import argparse import numpy as np import logging as logger import torch import torch.nn as nn import torch.backends.cudnn as cudnn from datasets import make_dataloader from config import config as cfg from models import make_model from losses import SoftLoss, SP_KD_Loss from utils import write_conf...
null
26,097
import os import gc import argparse import numpy as np import logging as logger import torch import torch.nn as nn import torch.backends.cudnn as cudnn from datasets import make_dataloader from config import config as cfg from models import make_model from losses import SoftLoss, SP_KD_Loss from utils import write_conf...
Computes the precision@k for the specified values of k
26,098
import os from PIL import Image import torch import torch.nn.functional as F import torchvision.transforms as T from models.make_target_model import make_target_model cfg = Config() cfg.ori_shape = (256, 256) cfg.image_crop_size = (224, 224) cfg.normalize_mean = [0.5, 0.5, 0.5] cfg.normalize_std = [0.5, 0.5, 0.5] cfg.l...
null
26,099
import os import getpass def parse_lb_txt(filename): lines = open(filename, 'r').readlines() train_dataset, test_dataset = [], [] for line in lines: key, label = line.split(' ')[0], line[-2] label = int(label) mode, img_path = key.split('_') # if mode == 'train': ...
null
26,100
import os import gc import argparse import numpy as np import logging as logger import argparse import torch import torch.nn as nn import torch.distributed as dist import torch.utils.data.distributed import torch.backends.cudnn as cudnn from apex.parallel import DistributedDataParallel from apex.parallel import convert...
null
26,101
import os import gc import argparse import numpy as np import logging as logger import argparse import torch import torch.nn as nn import torch.distributed as dist import torch.utils.data.distributed import torch.backends.cudnn as cudnn from apex.parallel import DistributedDataParallel from apex.parallel import convert...
Computes the precision@k for the specified values of k
26,102
import os import gc import argparse import numpy as np import logging as logger import argparse import torch import torch.nn as nn import torch.distributed as dist import torch.utils.data.distributed import torch.backends.cudnn as cudnn from apex.parallel import DistributedDataParallel from apex.parallel import convert...
null
26,103
import torch from torch.nn.functional import interpolate from torchvision.transforms import functional as F from torchvision.ops.boxes import batched_nms from PIL import Image import numpy as np import os import math def fixed_batch_process(im_data, model): batch_size = 512 out = [] for i in range(0, len(im...
null
26,104
import torch from torch.nn.functional import interpolate from torchvision.transforms import functional as F from torchvision.ops.boxes import batched_nms from PIL import Image import numpy as np import os import math def crop_resize(img, box, image_size): if isinstance(img, np.ndarray): img = img[box[1]:box...
Extract face + margin from PIL Image given bounding box. Arguments: img {PIL.Image} -- A PIL Image. box {numpy.ndarray} -- Four-element bounding box. image_size {int} -- Output image size in pixels. The image will be square. margin {int} -- Margin to add to bounding box, in terms of pixels in the final image. Note that...
26,105
import torch from torch import nn import numpy as np import os from .detect_face import detect_face, extract_face def fixed_image_standardization(image_tensor): processed_tensor = (image_tensor - 127.5) / 128.0 return processed_tensor
null
26,106
import torch from torch import nn import numpy as np import os from .detect_face import detect_face, extract_face def prewhiten(x): mean = x.mean() std = x.std() std_adj = std.clamp(min=1.0/(float(x.numel())**0.5)) y = (x - mean) / std_adj return y
null
26,107
import os import cv2 import numpy as np from tqdm import tqdm from PIL import Image from mtcnn import MTCNN def mtcnn_detect(mtcnn, image): boxes, probs = mtcnn.detect(image, landmarks=False) if boxes is not None: if boxes[0][0] < 0: boxes[0][0] = 0 if boxes[0][1] < 0: bo...
null
26,108
import sys import os import random import glob import torch from skimage import io from skimage import transform as ski_transform from skimage.color import rgb2gray import scipy.io as sio from scipy import interpolate import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader fr...
null
26,110
import matplotlib import math import torch import copy import time from torch.autograd import Variable import shutil from skimage import io import numpy as np from utils.utils import fan_NME, show_landmarks, get_preds_fromhm from PIL import Image, ImageDraw import os import sys import cv2 import matplotlib.pyplot as pl...
null
26,111
import torch import torch.nn as nn import torch.nn.functional as F import math from .coord_conv import CoordConvTh The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, strd=1, padding=1, bias=False,dil...
3x3 convolution with padding
26,112
import matplotlib import math import torch import copy import time from torch.autograd import Variable import shutil from skimage import io import numpy as np from .utils.utils import fan_NME, show_landmarks, get_preds_fromhm from PIL import Image, ImageDraw from pylab import * import os import sys import cv2 import ma...
null
26,113
import matplotlib import math import torch import copy import time from torch.autograd import Variable import shutil from skimage import io import numpy as np from .utils.utils import fan_NME, show_landmarks, get_preds_fromhm from PIL import Image, ImageDraw from pylab import * import os import sys import cv2 import ma...
null
26,114
from __future__ import print_function, division import os import sys import math import torch import cv2 from PIL import Image from skimage import io from skimage import transform as ski_transform from scipy import ndimage import numpy as np import matplotlib import matplotlib.pyplot as plt from torch.utils.data import...
null
26,115
from __future__ import print_function, division import os import sys import math import torch import cv2 from PIL import Image from skimage import io from skimage import transform as ski_transform from scipy import ndimage import numpy as np import matplotlib import matplotlib.pyplot as plt from torch.utils.data import...
null
26,116
from __future__ import print_function, division import os import sys import math import torch import cv2 from PIL import Image from skimage import io from skimage import transform as ski_transform from scipy import ndimage import numpy as np import matplotlib import matplotlib.pyplot as plt from torch.utils.data import...
Show image with pred_landmarks
26,117
from __future__ import print_function, division import os import sys import math import torch import cv2 from PIL import Image from skimage import io from skimage import transform as ski_transform from scipy import ndimage import numpy as np import matplotlib import matplotlib.pyplot as plt from torch.utils.data import...
Calculate total NME for a batch of data Args: pred_heatmaps: torch tensor of size [batch, points, height, width] gt_landmarks: torch tesnsor of size [batch, points, x, y] Returns: nme: sum of nme for this batch
26,118
from __future__ import print_function, division import os import sys import math import torch import cv2 from PIL import Image from skimage import io from skimage import transform as ski_transform from scipy import ndimage import numpy as np import matplotlib import matplotlib.pyplot as plt from torch.utils.data import...
null
26,119
from __future__ import print_function, division import os import sys import math import torch import cv2 from PIL import Image from skimage import io from skimage import transform as ski_transform from scipy import ndimage import numpy as np import matplotlib import matplotlib.pyplot as plt from torch.utils.data import...
null
26,120
from __future__ import print_function, division import os import sys import math import torch import cv2 from PIL import Image from skimage import io from skimage import transform as ski_transform from scipy import ndimage import numpy as np import matplotlib import matplotlib.pyplot as plt from torch.utils.data import...
null
26,121
from __future__ import print_function, division import os import sys import math import torch import cv2 from PIL import Image from skimage import io from skimage import transform as ski_transform from scipy import ndimage import numpy as np import matplotlib import matplotlib.pyplot as plt from torch.utils.data import...
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGBA values
26,122
import os import argparse from collections import OrderedDict import torch def convert(ori_path, dst_path, num_classes): num_branches = num_classes + 1 state_dict = torch.load(ori_path, map_location=lambda storage,loc: storage.cpu()) new_state_dict = OrderedDict() for key in state_dict: if 'lay...
null
26,123
import cv2 import numpy as np def add_gaussian_noise(image_array, mean=0.0, var=30): std = var**0.5 noisy_img = image_array + np.random.normal(mean, std, image_array.shape) noisy_img_clipped = np.clip(noisy_img, 0, 255).astype(np.uint8) return noisy_img_clipped
null
26,124
import cv2 import numpy as np def flip_image(image_array): return cv2.flip(image_array, 1)
null
26,125
import cv2 import numpy as np def color2gray(image_array): gray = cv2.cvtColor(image_array, cv2.COLOR_RGB2GRAY) gray_img_3d = image_array.copy() gray_img_3d[:, :, 0] = gray gray_img_3d[:, :, 1] = gray gray_img_3d[:, :, 2] = gray return gray_img_3d
null
26,126
import os import lmdb import random import numpy as np from torch.utils.data import Dataset from .image_utils import add_gaussian_noise The provided code snippet includes necessary dependencies for implementing the `read_lmdb` function. Write a Python function `def read_lmdb(key, txn)` to solve the following problem: ...
Keep reading image until succeed. This can avoid IOError incurred by heavy IO process.
26,127
import torch import torch.nn as nn from .resnet import ResNet, BasicBlock, Bottleneck from .resnet_ibn_a import ResNet_IBN, Bottleneck_IBN class Backbone(nn.Module): def __init__(self, cfg): super(Backbone, self).__init__() last_stride = cfg.last_stride model_name = cfg.backbone self...
null
26,129
import math import torch import torch.nn as nn class Bottleneck_IBN(nn.Module): expansion = 4 def __init__(self, inplanes, planes, ibn=False, stride=1, downsample=None): super(Bottleneck_IBN, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) if ibn: ...
Constructs a ResNet-50 model.
26,130
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter from .resnet_multibranch import ResNet, BasicBlock, Bottleneck from .resnet_ibn_multibranch import resnet50_ibn_a def weights_init_kaiming(m): classname = m.__class__.__name__ if classname.find('Linear')...
null
26,131
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter from .resnet_multibranch import ResNet, BasicBlock, Bottleneck from .resnet_ibn_multibranch import resnet50_ibn_a def weights_init_classifier(m): classname = m.__class__.__name__ if classname.find('Linea...
null
26,133
import os def write_config_into_log(cfg): attrs = dir(cfg) no_print_attributes = ['ckpt_root_dir', 'default_seed', 'get_lr', 'tb_dump_interval', 'iter_per_epoch', 'program_name', 'this_model_dir', 'train_data_num_thread', 'train_dp_name', ...
null
26,134
import math def ramp_up(epoch, alpha, lamda=1): if epoch > alpha: return lamda else: w = lamda * math.exp(-5*math.pow((1-epoch/alpha), 2)) return w
null
26,135
import math def ramp_down(epoch, alpha, lamda=1): if epoch < alpha: return lamda else: w = lamda * math.exp(-1*math.pow((1-alpha/epoch), 2)) return w
null
26,136
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, ReLU, Sigmoid, Dropout2d, Dropout, AvgPool2d, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module, Parameter import torch.nn.functional as F import torch from collections import namedtuple def get_block(in_channel, depth, num_units, stride = 2): retur...
null
26,137
import os import sys import shutil import argparse import logging as logger import torch from torch import optim from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from backbone.backbone_def import BackboneFactory from utils.AverageMeter import AverageMeter from data_processor.train_dataset ...
Total training procedure.
26,138
import os import sys import shutil import argparse import logging as logger import torch from torch import optim from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from backbone.backbone_def import BackboneFactory from loss.loss_def import KDLossFactory from utils.AverageMeter import Average...
Total training procedure.
26,139
import os The provided code snippet includes necessary dependencies for implementing the `gen_train_file` function. Write a Python function `def gen_train_file(data_root, train_file)` to solve the following problem: Generate the train file, which has the following format. relative_path0 label0 relative_path1 label1 re...
Generate the train file, which has the following format. relative_path0 label0 relative_path1 label1 relative_path2 label2
26,140
import os os.environ["OMP_NUM_THREADS"] = "1" os.environ["MKL_NUM_THREADS"] = "1" os.environ["OPENBLAS_NUM_THREADS"] = "1" os.environ["VECLIB_MAXIMUM_THREADS"] = "1" os.environ["NUMEXPR_NUM_THREADS"] = "1" os.environ["TOKENIZERS_PARALLELISM"] = "false" import argparse import gc import logging import sys import time fro...
Runs the routine. Args: cfg: config object with all the hyperparameters
26,141
import logging import os from llm_studio.app_utils.sections.chat_update import is_app_blocked_while_streaming from llm_studio.src.utils.logging_utils import initialize_logging from h2o_wave import Q, app, copy_expando, main, ui from llm_studio.app_utils.handlers import handle from llm_studio.app_utils.initializers imp...
null
26,142
import logging import os from llm_studio.app_utils.sections.chat_update import is_app_blocked_while_streaming from llm_studio.src.utils.logging_utils import initialize_logging from h2o_wave import Q, app, copy_expando, main, ui from llm_studio.app_utils.handlers import handle from llm_studio.app_utils.initializers imp...
Serving function.
26,143
import asyncio import collections import contextlib import dataclasses import glob import json import logging import math import os import random import re import shutil import socket import string import subprocess import time import uuid import zipfile from collections import defaultdict from contextlib import closin...
null
26,144
import os import random import re import uuid import pandas as pd from datasets import load_dataset from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `extract_anthropic_prompt` function. Write a Python function `def extract_anthropic_prompt(prompt_and_response)` to so...
Extract the anthropic prompt from a prompt and response pair.
26,145
import os import random import re import uuid import pandas as pd from datasets import load_dataset from tqdm import tqdm def _parse_row(prompt_and_response): """Extract the anthropic prompt from a prompt and response pair.""" search_term = "\n\nAssistant:" search_term_idx = prompt_and_response["chosen"].rf...
Adapted from https://github.com/eric-mitchell/direct-preference-optimization/blob/main/preference_datasets.py
26,146
import os import socket from types import SimpleNamespace def get_size(x): try: if x.endswith("TB"): return float(x.replace("TB", "")) * (2**40) if x.endswith("GB"): return float(x.replace("GB", "")) * (2**30) if x.endswith("MB"): return float(x.replace("...
null
26,147
import glob import logging import os import shutil import time import zipfile from pathlib import Path from typing import Callable, List, Optional, Set import accelerate import einops import huggingface_hub import numpy as np import pandas as pd import torch import transformers import yaml from h2o_wave import Q, data,...
null
26,148
import hashlib import logging from typing import List from h2o_wave import Q, ui from llm_studio.app_utils.cards import card_zones from llm_studio.app_utils.config import default_cfg async def info_dialog(q: Q, title: str, message: str): q.page["meta"].dialog = ui.dialog( title, items=[ ...
null
26,149
import errno import functools import logging import os import pickle import signal import traceback from typing import Any, List import keyring import yaml from h2o_wave import Q, ui from keyring.errors import KeyringLocked, PasswordDeleteError from llm_studio.app_utils.config import default_cfg from llm_studio.app_uti...
null
26,150
import errno import functools import logging import os import pickle import signal import traceback from typing import Any, List import keyring import yaml from h2o_wave import Q, ui from keyring.errors import KeyringLocked, PasswordDeleteError from llm_studio.app_utils.config import default_cfg from llm_studio.app_uti...
Test if keyring is working. On misconfigured machines, Keyring may hang up to 2 minutes with the following error: jeepney.wrappers.DBusErrorResponse: [org.freedesktop.DBus.Error.TimedOut] ("Failed to activate service 'org.freedesktop.secrets': timed out (service_start_timeout=120000ms)",) To avoid waiting for 2 minutes...
26,151
from typing import List, Optional from h2o_wave import ui The provided code snippet includes necessary dependencies for implementing the `card_wait` function. Write a Python function `def card_wait(msg: str, box: str) -> ui.FormCard` to solve the following problem: Return a form card for displaying waiting status Args...
Return a form card for displaying waiting status Args: msg: message to display box: box for card Returns: Form card
26,152
import glob import re from dataclasses import dataclass from typing import Dict The provided code snippet includes necessary dependencies for implementing the `read_tooltip_file` function. Write a Python function `def read_tooltip_file(path: str) -> str` to solve the following problem: Reads all lines of a text file. ...
Reads all lines of a text file. Args: filename: path to the file Returns: str: the text of the file
26,153
import glob import re from dataclasses import dataclass from typing import Dict CLEANR = re.compile("<[^<]+?>") The provided code snippet includes necessary dependencies for implementing the `cleanhtml` function. Write a Python function `def cleanhtml(raw_html: str) -> str` to solve the following problem: Removes html...
Removes html tags from a string. Args: raw_html: the string to clean Returns: str: the cleaned string
26,154
import glob import re from dataclasses import dataclass from typing import Dict The provided code snippet includes necessary dependencies for implementing the `clean_docusaurus_tags` function. Write a Python function `def clean_docusaurus_tags(text: str) -> str` to solve the following problem: Removes docusaurus tags ...
Removes docusaurus tags from a string. Args: text: the string to clean Returns: str: the cleaned string
26,155
import glob import re from dataclasses import dataclass from typing import Dict The provided code snippet includes necessary dependencies for implementing the `clean_md_links` function. Write a Python function `def clean_md_links(text: str) -> str` to solve the following problem: Removes markdown links from a string. ...
Removes markdown links from a string. Args: text: the string to clean Returns: str: the cleaned string
26,156
from typing import Iterable, List, Optional class Order: def __init__(self, keys: Optional[List[str]] = None): def _unique_guard(self, *keys: str): def append(self, key: str): def extend(self, keys: Iterable[str]): def insert( self, *keys: str, before: Optional[str] = None, after: O...
null
26,157
import logging from typing import Any, Dict, List, Tuple, Union import numpy as np import pandas as pd from numpy.typing import NDArray from scipy.special import softmax from sklearn.metrics import log_loss, roc_auc_score def accuracy_score( cfg: Any, results: Dict, val_df: pd.DataFrame, raw_results: b...
null
26,158
import logging from typing import Any, Dict, List, Tuple, Union import numpy as np import pandas as pd from numpy.typing import NDArray from scipy.special import softmax from sklearn.metrics import log_loss, roc_auc_score def auc_score( cfg: Any, results: Dict, val_df: pd.DataFrame, raw_results: bool =...
null
26,159
import logging from typing import Any, Dict, List, Tuple, Union import numpy as np import pandas as pd from numpy.typing import NDArray from scipy.special import softmax from sklearn.metrics import log_loss, roc_auc_score def logloss_score( cfg: Any, results: Dict, val_df: pd.DataFrame, raw_results: bo...
null
26,160
import logging import os from functools import partial from typing import Any, Dict, List, Tuple, Union import numpy as np import pandas as pd import torch from joblib import Parallel, delayed from numpy.typing import NDArray from openai import AzureOpenAI, OpenAI from sacrebleu import BLEU from sacrebleu.metrics.base ...
null
26,161
import logging import os from functools import partial from typing import Any, Dict, List, Tuple, Union import numpy as np import pandas as pd import torch from joblib import Parallel, delayed from numpy.typing import NDArray from openai import AzureOpenAI, OpenAI from sacrebleu import BLEU from sacrebleu.metrics.base ...
null
26,162
import logging import os from functools import partial from typing import Any, Dict, List, Tuple, Union import numpy as np import pandas as pd import torch from joblib import Parallel, delayed from numpy.typing import NDArray from openai import AzureOpenAI, OpenAI from sacrebleu import BLEU from sacrebleu.metrics.base ...
null
26,163
import hashlib import os from typing import Any, Dict import pandas as pd from llm_studio.src.datasets.conversation_chain_handler import get_conversation_chains from llm_studio.src.datasets.text_utils import get_tokenizer from llm_studio.src.utils.data_utils import read_dataframe_drop_missing_labels from llm_studio.src...
null
26,164
import hashlib import os from typing import Any, Dict import pandas as pd from llm_studio.src.datasets.conversation_chain_handler import get_conversation_chains from llm_studio.src.datasets.text_utils import get_tokenizer from llm_studio.src.utils.data_utils import read_dataframe_drop_missing_labels from llm_studio.src...
null
26,165
import dataclasses import logging import os from typing import Any, Dict, List, Optional import numpy as np from sqlitedict import SqliteDict from llm_studio.src.utils.plot_utils import PLOT_ENCODINGS The provided code snippet includes necessary dependencies for implementing the `get_cfg` function. Write a Python func...
Returns simplified config elements Args: cfg: configuration Returns: Dict of config elements
26,166
import os from abc import abstractmethod from dataclasses import dataclass from typing import Any, Callable, List, Optional, Sequence, Set, Tuple, Union from llm_studio.src.nesting import Dependency The provided code snippet includes necessary dependencies for implementing the `_scan_dirs` function. Write a Python fun...
Scans a directory for subfolders Args: dirname: directory name Returns: List of subfolders
26,167
import os from abc import abstractmethod from dataclasses import dataclass from typing import Any, Callable, List, Optional, Sequence, Set, Tuple, Union from llm_studio.src.nesting import Dependency The provided code snippet includes necessary dependencies for implementing the `_scan_files` function. Write a Python fu...
Scans a directory for files with given extension Args: dirname: directory name extensions: extensions to consider Returns: List of files
26,168
import os from abc import abstractmethod from dataclasses import dataclass from typing import Any, Callable, List, Optional, Sequence, Set, Tuple, Union from llm_studio.src.nesting import Dependency The provided code snippet includes necessary dependencies for implementing the `strip_prefix` function. Write a Python f...
Strips the common prefix of all the given paths. Args: paths: the paths to strip ignore_set: set of path names to ignore when computing the prefix. Returns: List with the same length as `paths` without common prefixes.
26,169
from typing import Any, List from transformers import ( get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_linear_schedule_with_warmup, ) def constant_schedule_with_warmup(optimizer, num_warmup_steps, **kwargs): return get_constant_schedule_with_warmup( optimizer=optimizer,...
null
26,170
import logging from typing import Any, Dict import numpy as np import pandas as pd import torch from llm_studio.src.datasets.text_causal_language_modeling_ds import ( CustomDataset as TextCausalLanguageModelingCustomDataset, ) from llm_studio.src.utils.exceptions import LLMDataException def is_castable_to_int(s): ...
null
26,171
import logging from typing import Any, Dict import torch from torch import nn from transformers import AutoModelForCausalLM from llm_studio.src.losses.text_causal_language_modeling_losses import ( SampleAveragedCrossEntropyLoss, ) from llm_studio.src.losses.text_dpo_modeling_losses import LOSS_REDUCTION from llm_st...
Based upon the official implementation of DPO: https://github.com/eric-mitchell/direct-preference-optimization Compute the log probabilities of the given labels under the given logits. Args: logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) labels: Labels for which to compute ...
26,172
import logging import os import pickle import random import zipfile from typing import Any import numpy as np import psutil import torch The provided code snippet includes necessary dependencies for implementing the `kill_ddp_processes` function. Write a Python function `def kill_ddp_processes() -> None` to solve the ...
Killing all DDP processes from a single process. Firstly kills all children of a single DDP process (dataloader workers) Then kills all other DDP processes Then kills main parent DDP process
26,173
from typing import Any, Union import numpy as np import torch def is_cuda_out_of_memory(exception: BaseException) -> bool: return ( isinstance(exception, RuntimeError) and len(exception.args) == 1 and "CUDA" in exception.args[0] and "out of memory" in exception.args[0] ) def is_o...
null
26,174
import html import re from dataclasses import dataclass from typing import List def get_line_separator_html(): return ( "<div style='height: 1px; width: 100%; margin: 1em 0; " "background-color: white; background-color: var(--text);'></div>" )
null
26,175
import html import re from dataclasses import dataclass from typing import List The provided code snippet includes necessary dependencies for implementing the `decode_bytes` function. Write a Python function `def decode_bytes(chunks: List[bytes])` to solve the following problem: Decodes bytes to string Args: chunks: b...
Decodes bytes to string Args: chunks: byte chunks Returns: list of decoded strings
26,176
import gc import logging import os import re import shutil from collections import OrderedDict from typing import Any, Dict import coolname import deepspeed import numpy as np import torch from deepspeed.runtime.dataloader import DeepSpeedDataLoader from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero...
Generates a random human-readable experiment name in kebab-case. Returns: The random name.
26,177
import gc import logging import os import re import shutil from collections import OrderedDict from typing import Any, Dict import coolname import deepspeed import numpy as np import torch from deepspeed.runtime.dataloader import DeepSpeedDataLoader from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero...
Reduces metric and return metric score (number) Args: output: output of the model reduce: how to reduce the metric over the sample dimension Returns: score: single number score (using config threshold for threshold metrics) or non-reduced array of scores per sample.
26,178
import gc import logging import os import re import shutil from collections import OrderedDict from typing import Any, Dict import coolname import deepspeed import numpy as np import torch from deepspeed.runtime.dataloader import DeepSpeedDataLoader from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero...
Creates a backbone model for NLP tasks. This is needed for Gradient Checkpointing in DDP mode.
26,179
import gc import logging import os import re import shutil from collections import OrderedDict from typing import Any, Dict import coolname import deepspeed import numpy as np import torch from deepspeed.runtime.dataloader import DeepSpeedDataLoader from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero...
null
26,180
import dataclasses import logging from dataclasses import dataclass, fields from typing import Any, Dict, List, Optional, Sequence, Set, Tuple from llm_studio.src import possible_values from llm_studio.src.nesting import Dependency, Nesting from llm_studio.src.order import Order from llm_studio.src.tooltips import tool...
null
26,181
import os from llm_studio.src.utils.config_utils import load_config_yaml import argparse import numpy as np import torch from llm_studio.src.datasets.text_utils import get_tokenizer from llm_studio.src.utils.modeling_utils import load_checkpoint def parse_param(cfg, prompt): prompt = prompt.replace("--", "") p...
null
26,182
import os import argparse import logging import sys import time import psutil The provided code snippet includes necessary dependencies for implementing the `check_for_done` function. Write a Python function `def check_for_done(process_queue)` to solve the following problem: Checks for finished process ids Args: proce...
Checks for finished process ids Args: process_queue: list of process ids Returns: (True, process_idx) if there is any finished process (False, False) if there is not finished processes
26,183
from threading import Timer import re import shutil import json import subprocess import tempfile from urllib.error import HTTPError import requests import requests.adapters import time from transformers import __version__ as transformers_version from transformers import PreTrainedModel import packaging.version from tq...
null
26,184
from threading import Timer import re import shutil import json import subprocess import tempfile from urllib.error import HTTPError import requests import requests.adapters import time from transformers import __version__ as transformers_version from transformers import PreTrainedModel import packaging.version from tq...
null
26,185
import contextlib from functools import reduce import itertools import zipfile import pickle import torch import numpy as np import collections import _codecs import utils import os from torch.nn import Module from typing import Any, Callable, Dict, Optional, Tuple, Type, Union class RestrictedUnpickler(pickle.Unpickle...
null
26,186
import abc import os import sys import math import numpy as np import termcolor import contextlib import traceback import random import zipfile import json import uuid import datetime import base64 import pickle import hashlib import itertools import functools import bisect import eventlet import packaging import gc im...
null
26,187
import abc import os import sys import math import numpy as np import termcolor import contextlib import traceback import random import zipfile import json import uuid import datetime import base64 import pickle import hashlib import itertools import functools import bisect import eventlet import packaging import gc im...
null
26,188
import abc import os import sys import math import numpy as np import termcolor import contextlib import traceback import random import zipfile import json import uuid import datetime import base64 import pickle import hashlib import itertools import functools import bisect import eventlet import packaging import gc im...
null
26,189
import abc import os import sys import math import numpy as np import termcolor import contextlib import traceback import random import zipfile import json import uuid import datetime import base64 import pickle import hashlib import itertools import functools import bisect import eventlet import packaging import gc im...
null
26,190
import utils import multiprocessing from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, TypeVar import progressbar import time import os import sys import json import zipfile import requests import random import jax import jax.dlpack from jax.config import config from jax.experimental import maps...
null
26,191
import utils import multiprocessing from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, TypeVar import progressbar import time import os import sys import json import zipfile import requests import random import jax import jax.dlpack from jax.config import config from jax.experimental import maps...
null