id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
145,679 | from PIL import ImageGrab
import win32clipboard
import win32process
import win32gui
import win32api
import win32con
import pyperclip
from ctypes import (
Structure,
c_uint,
c_long,
c_int,
c_bool,
sizeof
)
import psutil
import shutil
import time
import os
def GetAllControl(ele):
def find... | null |
145,680 | from PIL import ImageGrab
import win32clipboard
import win32process
import win32gui
import win32api
import win32con
import pyperclip
from ctypes import (
Structure,
c_uint,
c_long,
c_int,
c_bool,
sizeof
)
import psutil
import shutil
import time
import os
matedata = bytes(pDropFiles)
def SetClip... | null |
145,681 | from PIL import ImageGrab
import win32clipboard
import win32process
import win32gui
import win32api
import win32con
import pyperclip
from ctypes import (
Structure,
c_uint,
c_long,
c_int,
c_bool,
sizeof
)
import psutil
import shutil
import time
import os
def PasteFile(folder):
folder = os.p... | null |
145,682 | from PIL import ImageGrab
import win32clipboard
import win32process
import win32gui
import win32api
import win32con
import pyperclip
from ctypes import (
Structure,
c_uint,
c_long,
c_int,
c_bool,
sizeof
)
import psutil
import shutil
import time
import os
def GetText(HWND):
length = win32gui.... | null |
145,683 | from PIL import ImageGrab
import win32clipboard
import win32process
import win32gui
import win32api
import win32con
import pyperclip
from ctypes import (
Structure,
c_uint,
c_long,
c_int,
c_bool,
sizeof
)
import psutil
import shutil
import time
import os
def FindWindow(classname=None, name=None... | null |
145,684 | from PIL import ImageGrab
import win32clipboard
import win32process
import win32gui
import win32api
import win32con
import pyperclip
from ctypes import (
Structure,
c_uint,
c_long,
c_int,
c_bool,
sizeof
)
import psutil
import shutil
import time
import os
def GetText(HWND):
length = win32gui.... | null |
145,685 | from PIL import ImageGrab
import win32clipboard
import win32process
import win32gui
import win32api
import win32con
import pyperclip
from ctypes import (
Structure,
c_uint,
c_long,
c_int,
c_bool,
sizeof
)
import psutil
import shutil
import time
import os
def ClipboardFormats(unit=0, *units):
... | null |
145,686 | import logging
def _get_library_root_logger() -> logging.Logger:
"""
Return the root logger of the library.
"""
return logging.getLogger(_get_library_name())
import logging
The provided code snippet includes necessary dependencies for implementing the `enable_explicit_format` function. Write a Python ... | Enable explicit formatting for every MTEB's logger. The explicit formatter is as follows: ``` [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE ``` All handlers currently bound to the root logger are affected by this method. |
145,687 | import datasets
from ...abstasks import AbsTaskBitextMining, CrosslingualTask
_LANGUAGES = [
"ace_Arab",
"bam_Latn",
"dzo_Tibt",
"hin_Deva",
"khm_Khmr",
"mag_Deva",
"pap_Latn",
"sot_Latn",
"tur_Latn",
"ace_Latn",
"ban_Latn",
"ell_Grek",
"hne_Deva",
"kik_Latn",
... | null |
145,688 | from collections import defaultdict
from datasets import load_dataset, DatasetDict
from ...abstasks.AbsTaskRetrieval import AbsTaskRetrieval
def load_retrieval_data(hf_hub_name, eval_splits):
eval_split = eval_splits[0]
dataset = load_dataset(hf_hub_name)
qrels = load_dataset(hf_hub_name + '-qrels')[eval_s... | null |
145,689 | import datasets
from ...abstasks import MultilingualTask
from ...abstasks.AbsTaskRetrieval import AbsTaskRetrieval
def _load_xpqa_data(path: str, langs: list, split: str, cache_dir: str = None, revision: str = None):
queries = {lang: {split: {}} for lang in langs}
corpus = {lang: {split: {}} for lang in langs}... | null |
145,690 | from ...abstasks import MultilingualTask
from ...abstasks.AbsTaskRetrieval import AbsTaskRetrieval
import datasets
def _load_xmarket_data(path: str, langs: list, split: str, cache_dir: str=None, revision: str=None):
corpus = {lang: {split: None} for lang in langs}
queries = {lang: {split: None} for lang in lan... | null |
145,691 | from collections import defaultdict
from datasets import load_dataset, DatasetDict
from ...abstasks.AbsTaskRetrieval import AbsTaskRetrieval
def load_retrieval_data(hf_hub_name, eval_splits):
eval_split = eval_splits[0]
corpus_dataset = load_dataset(hf_hub_name, 'corpus')
queries_dataset = load_dataset(hf_... | null |
145,692 | import datasets
from ...abstasks import MultilingualTask, AbsTaskRetrieval
from ...abstasks.AbsTaskRetrieval import *
from datasets import load_dataset, Value, Features
def load_mldr_data(path: str, langs: list, eval_splits: list, cache_dir: str=None):
corpus = {lang: {split: None for split in eval_splits} for la... | null |
145,693 | import datasets
from ...abstasks import MultilingualTask
from ...abstasks.AbsTaskRetrieval import AbsTaskRetrieval
def _load_mintaka_data(path: str, langs: list, split: str, cache_dir: str = None, revision: str = None):
queries = {lang: {split: {}} for lang in langs}
corpus = {lang: {split: {}} for lang in lan... | null |
145,694 | import datasets
from ...abstasks import MultilingualTask
from ...abstasks.AbsTaskRetrieval import AbsTaskRetrieval
def _load_miracl_data(path: str, langs: list, split: str, cache_dir: str = None, revision: str = None):
queries = {lang: {split: {}} for lang in langs}
corpus = {lang: {split: {}} for lang in lang... | null |
145,695 | import logging
from typing import List, Dict, Union, Tuple
import torch
The provided code snippet includes necessary dependencies for implementing the `cos_sim` function. Write a Python function `def cos_sim(a, b)` to solve the following problem:
Computes the cosine similarity cos_sim(a[i], b[j]) for all i and j. :ret... | Computes the cosine similarity cos_sim(a[i], b[j]) for all i and j. :return: Matrix with res[i][j] = cos_sim(a[i], b[j]) |
145,696 | import logging
from typing import List, Dict, Union, Tuple
import torch
The provided code snippet includes necessary dependencies for implementing the `dot_score` function. Write a Python function `def dot_score(a: torch.Tensor, b: torch.Tensor)` to solve the following problem:
Computes the dot-product dot_prod(a[i], ... | Computes the dot-product dot_prod(a[i], b[j]) for all i and j. :return: Matrix with res[i][j] = dot_prod(a[i], b[j]) |
145,697 | import logging
from typing import List, Dict, Union, Tuple
import torch
def mrr(qrels: Dict[str, Dict[str, int]],
results: Dict[str, Dict[str, float]],
k_values: List[int]) -> Tuple[Dict[str, float]]:
MRR = {}
for k in k_values:
MRR[f"MRR@{k}"] = 0.0
k_max, top_hits... | null |
145,698 | import logging
from typing import List, Dict, Union, Tuple
import torch
def recall_cap(qrels: Dict[str, Dict[str, int]],
results: Dict[str, Dict[str, float]],
k_values: List[int]) -> Tuple[Dict[str, float]]:
capped_recall = {}
for k in k_values:
capped_recall[f... | null |
145,699 | import logging
from typing import List, Dict, Union, Tuple
import torch
def hole(qrels: Dict[str, Dict[str, int]],
results: Dict[str, Dict[str, float]],
k_values: List[int]) -> Tuple[Dict[str, float]]:
Hole = {}
for k in k_values:
Hole[f"Hole@{k}"] = 0.0
... | null |
145,700 | import logging
from typing import List, Dict, Union, Tuple
import torch
def top_k_accuracy(
qrels: Dict[str, Dict[str, int]],
results: Dict[str, Dict[str, float]],
k_values: List[int]) -> Tuple[Dict[str, float]]:
top_k_acc = {}
for k in k_values:
top_k_acc[f"Accuracy... | null |
145,701 | import logging
import heapq
from typing import Dict, List, Tuple
import pytrec_eval
from sentence_transformers import SentenceTransformer
from sentence_transformers.models import Transformer, WordEmbeddings
import torch
from .Evaluator import Evaluator
from .utils import cos_sim, dot_score, mrr, recall_cap, hole, top_k... | null |
145,702 | import gzip
import os
import datasets
import numpy as np
from tqdm import tqdm
import jsonlines
np.random.seed(28042000)
def cluster_stats(labels):
(unique, counts) = np.unique(labels, return_counts=True)
for u, c in zip(unique, counts):
print(u, c) | null |
145,703 | import gzip
import os
import datasets
import numpy as np
from tqdm import tqdm
import jsonlines
def get_text(record):
return " ".join(record["texts"]) | null |
145,704 | import gzip
import json
import re
from huggingface_hub import upload_file
def process_sentence(x):
x = re.sub("\n", "", x).strip()
return x.split("\t")[1] | null |
145,705 | import gzip
import json
import re
from huggingface_hub import upload_file
def process_gold(x):
id1, id2 = x.strip().split("\t")
id1 = id1.split("-")[1]
id2 = id2.split("-")[1]
return int(id1), int(id2) | null |
145,706 | import os
import pandas as pd
df_news = pd.read_csv("scripts/mind/data/MINDsmall_train/news.tsv", sep="\t", header=None)
df_news = df_news[[0, 3]]
df_news.columns = ["id", "text"]
df_news.index = df_news["id"]
def proc_row(row):
docs = row["data"].split()
positives, negatives = [], []
for doc in docs:
... | null |
145,707 | import gzip
import os
from collections import Counter
import datasets
import numpy as np
from tqdm import tqdm
import jsonlines
np.random.seed(28042000)
def cluster_stats(labels):
(unique, counts) = np.unique(labels, return_counts=True)
for u, c in zip(unique, counts):
print(u, c) | null |
145,708 | import gzip
import os
from collections import Counter
import datasets
import numpy as np
from tqdm import tqdm
import jsonlines
def get_text(record, type="s2s"):
if type == "s2s":
return record["title"]
elif type == "p2p":
return record["title"] + " " + record["abstract"]
raise ValueError | null |
145,709 | import gzip
import os
from collections import Counter
import datasets
import numpy as np
from tqdm import tqdm
import jsonlines
def match_main_category(category):
for main_cat in main_categories:
if main_cat in category:
return main_cat
return "other"
for main_cat in tqdm(main_categories):
... | null |
145,710 | import gzip
import os
from collections import Counter
import datasets
import numpy as np
from tqdm import tqdm
import jsonlines
def sub_category(category_string):
category_list = category_string.split(" ")
return category_list[0] | null |
145,711 | import json
import os
from huggingface_hub import create_repo, upload_file
import datasets
import requests
HEADERS = {
'Authorization': f"DeepL-Auth-Key {DEEPL_API_KEY}",
'Content-Type': 'application/x-www-form-urlencoded',
}
def translate_with_deepl(text: str) -> str:
data = {
'text': text,
... | null |
145,713 | import gzip
import os
import datasets
import numpy as np
from tqdm import tqdm
import jsonlines
def get_text(record, type="s2s"):
if type == "s2s":
return record["title"]
elif type == "p2p":
return record["title"] + " " + record["abstract"]
raise ValueError | null |
145,716 | import os
from mteb import MTEB
LEN_KEYS = {
"text",
"sentences",
"sentence1",
"sentence2",
"sent1",
"sent2" "query",
"positive",
"negative" "queries",
"corpus",
"machine_summaries",
"human_summaries",
}
def load_data(hf_hub_name, subset=None):
"""
Load dataset from H... | Not used as some BEIR datasets are still missing on the Hub |
145,717 | import os
from mteb import MTEB
DATAPATH = "/gpfsscratch/rech/six/commun/commun/experiments/muennighoff/mteb"
def get_ds_stats_beir(hf_hub_name):
from beir.datasets.data_loader import GenericDataLoader as BeirDataLoader
path = os.path.join(DATAPATH, hf_hub_name)
if not os.path.exists(path):
from b... | null |
145,718 | import os
from mteb import MTEB
LEN_KEYS = {
"text",
"sentences",
"sentence1",
"sentence2",
"sent1",
"sent2" "query",
"positive",
"negative" "queries",
"corpus",
"machine_summaries",
"human_summaries",
}
def load_data(hf_hub_name, subset=None):
def get_ds_stats(hf_hub_name):... | null |
145,719 | import os
import pathlib
import time
import requests
os.chdir(path)
def log(msg):
print(msg)
if msg.startswith("[-] "):
icon = "dialog-error"
else:
icon = "dialog-information"
os.system("notify-send `hostname` %r --icon=%s" % (msg[4:], icon)) | null |
145,720 | import os
import base64
import sys
import requests
import json
from datetime import datetime
with open(image_path, 'r') as f:
content = image_encode_to_base64(image_path)
print('try to upload')
TRILIUM_URL = "https://你的域名/custom/create-image-note"
resp = requests.post(TRILIUM_URL,
... | image data to base64 |
145,721 | import re
import time
MEANINGLESS_WORDS = ['<pad>', '</s>', '<|endoftext|>']
def clean_response(response):
for word in MEANINGLESS_WORDS:
response = response.replace(word, "")
response = response.strip("\n")
return response | null |
145,722 | import argparse
from shutil import copyfile
import boto3
import botocore
import glob
import gzip
import os
import re
import requests
import shutil
import subprocess
import sys
from urllib.parse import urlparse
def is_huggingface_git_url(url):
# Regular expression pattern for Hugging Face git URLs
hf_git_pattern... | null |
145,723 | from transformers import AutoTokenizer, GPT2TokenizerFast, DebertaV2Tokenizer
def build_tokenizer(args):
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
return tokenizer | null |
145,724 | from transformers import AutoTokenizer, GPT2TokenizerFast, DebertaV2Tokenizer
def build_gpt2_tokenizer(args):
tokenizer = GPT2TokenizerFast.from_pretrained(args.tokenizer_name)
tokenizer.pad_token = tokenizer.eos_token
return tokenizer | null |
145,725 | from transformers import AutoTokenizer, GPT2TokenizerFast, DebertaV2Tokenizer
def build_deberta_tokenizer(args):
tokenizer = DebertaV2Tokenizer.from_pretrained(args.tokenizer_name)
return tokenizer | null |
145,726 | import os
from typing import List, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
from torch.utils.checkpoint import checkpoint
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPas... | Make causal mask used for bi-directional self-attention. |
145,727 | import os
from typing import List, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
from torch.utils.checkpoint import checkpoint
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPas... | null |
145,728 | import os
from typing import List, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
from torch.utils.checkpoint import checkpoint
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPas... | null |
145,729 | import torch
import numpy as np
import math
from torch import nn
from torch.nn import functional
from torch.utils.checkpoint import checkpoint
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
def make_log_bucket_position(relative_pos, bu... | null |
145,730 | import os
import torch
import math
import numpy as np
from torch import nn
from torch.nn import functional
from torch.utils.checkpoint import checkpoint
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from transformers.models.gptj.model... | null |
145,731 | import os
import torch
import math
import numpy as np
from torch import nn
from torch.nn import functional
from torch.utils.checkpoint import checkpoint
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from transformers.models.gptj.model... | null |
145,732 | import torch
import math
import numpy as np
from torch import nn
from torch.nn import functional
from torch.utils.checkpoint import checkpoint
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from transformers.models.gpt2.modeling_gpt2 i... | null |
145,733 | import os
import torch
import numpy as np
from torch import nn
from torch.nn import functional
from torch.utils.checkpoint import checkpoint
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from transformers.models.gpt_neox.modeling_gpt_... | null |
145,734 | from typing import List, Optional, Tuple, Union
import os
import torch
from torch import nn
from torch.utils.checkpoint import checkpoint
import torch.nn.functional as F
from transformers.models.opt.modeling_opt import ACT2FN
from transformers.models.opt.modeling_opt import OPTDecoderLayer
from transformers.models.opt.... | null |
145,735 | import argparse
import time
import random
import numpy as np
import torch
import torch.autograd.profiler as profiler
from tasks.data_loaders.data_utils import get_train_data_loader, get_eval_data_loader
from modules.utils import gpt_loss_func
from modules.tokenizer import build_tokenizer
from pipeline_parallel.dist_pp_... | null |
145,736 | import argparse
import time
import random
import numpy as np
import torch
import torch.autograd.profiler as profiler
from tasks.data_loaders.data_utils import get_train_data_loader, get_eval_data_loader
from modules.utils import gpt_loss_func
from modules.tokenizer import build_tokenizer
from pipeline_parallel.dist_pp_... | null |
145,737 | import time
import json
import torch.nn.functional
from torch import optim
from comm.comm_utils import *
from modules.dist_gpt_pp_module import *
from utils.logging_utils import *
from data_parallel.dist_dp_utils import get_dp_module
from optimizer.optimizer import get_fp16_optimizer
import os
import cupy
from transfor... | null |
145,738 | from .dist_gpipe_pipeline_async import GpipeAsync
class GpipeAsync:
r"""
Async implementation of Gpipe.
The current implementation leave the computation on the PyTorch default stream and the communication on a different
stream, there is:
a group of events to check if recv (from rank i-1) finish... | null |
145,739 | import torch
from .grad_scalar import *
import torch
def _has_overflow_serial(grads):
def _has_inf_or_nan(x):
try:
# if x is half, the .float() incurs an additional deep copy, but it's necessary if
# Pytorch's .sum() creates a one-element tensor of the same type as x
#... | null |
145,740 | import torch
from .grad_scalar import *
The provided code snippet includes necessary dependencies for implementing the `_zero_grad_group` function. Write a Python function `def _zero_grad_group(group, set_to_none)` to solve the following problem:
Zero out the gradient for a group of parameters. Note: copied from torch... | Zero out the gradient for a group of parameters. Note: copied from torch.optim.optimizer. |
145,741 | import torch
from .grad_scalar import *
class Fp16Optimizer:
# If offload is set to true, the fp32 copy is stored on CPU.
def __init__(self, optimizer, grad_scaler, device, offload=False):
self.offload = offload
if self.offload:
self.cpu_to_gpu_stream = torch.cuda.Stream(device=devic... | null |
145,742 | from .torch_backend import *
from .nccl_backend import *
import threading
_LOCK = threading.RLock()
def get_lock():
return _LOCK | null |
145,743 | from .torch_backend import *
from .nccl_backend import *
_DATA_PARALLEL_COMM = None
import threading
class NCCLCommunicator:
def __init__(self,
comm_rank: int,
cuda_id: int,
comm_group_size: int,
comm_name: str):
def barrier(... | null |
145,744 | from .torch_backend import *
from .nccl_backend import *
_DATA_PARALLEL_RANK = None
import threading
def get_data_parallel_rank() -> int:
assert _DATA_PARALLEL_RANK is not None
return _DATA_PARALLEL_RANK | null |
145,745 | from .torch_backend import *
from .nccl_backend import *
_DATA_PARALLEL_WORLD_SIZE = None
import threading
def get_data_parallel_world_size() -> int:
assert _DATA_PARALLEL_WORLD_SIZE is not None
return _DATA_PARALLEL_WORLD_SIZE | null |
145,746 | from .torch_backend import *
from .nccl_backend import *
_PIPELINE_PARALLEL_COMM = None
import threading
class NCCLCommunicator:
def __init__(self,
comm_rank: int,
cuda_id: int,
comm_group_size: int,
comm_name: str):
self.comm_rank = comm_... | null |
145,747 | from .torch_backend import *
from .nccl_backend import *
_PIPELINE_PARALLEL_RANK = None
import threading
def get_pipeline_parallel_rank() -> int:
assert _PIPELINE_PARALLEL_RANK is not None
return _PIPELINE_PARALLEL_RANK | null |
145,748 | from .torch_backend import *
from .nccl_backend import *
_PIPELINE_PARALLEL_WORLD_SIZE = None
import threading
def get_pipeline_parallel_world_size() -> int:
assert _PIPELINE_PARALLEL_WORLD_SIZE is not None
return _PIPELINE_PARALLEL_WORLD_SIZE | null |
145,749 | from .torch_backend import *
from .nccl_backend import *
_TENSOR_PARALLEL_COMM = None
import threading
class NCCLCommunicator:
def __init__(self,
comm_rank: int,
cuda_id: int,
comm_group_size: int,
comm_name: str):
self.comm_rank = comm_ra... | null |
145,750 | from .torch_backend import *
from .nccl_backend import *
_TENSOR_PARALLEL_RANK = None
import threading
def get_megatron_tensor_parallel_rank() -> int:
assert _TENSOR_PARALLEL_RANK is not None
return _TENSOR_PARALLEL_RANK | null |
145,751 | from .torch_backend import *
from .nccl_backend import *
_TENSOR_PARALLEL_WORLD_SIZE = None
import threading
def get_megatron_tensor_parallel_world_size() -> int:
assert _TENSOR_PARALLEL_WORLD_SIZE is not None
return _TENSOR_PARALLEL_WORLD_SIZE | null |
145,752 | from .torch_backend import *
from .nccl_backend import *
_DATA_PARALLEL_COMM = None
_DATA_PARALLEL_RANK = None
_DATA_PARALLEL_WORLD_SIZE = None
_PIPELINE_PARALLEL_COMM = None
_PIPELINE_PARALLEL_RANK = None
_PIPELINE_PARALLEL_WORLD_SIZE = None
import threading
def default_init(args):
import datetime
import time... | null |
145,753 | from .torch_backend import *
from .nccl_backend import *
_DATA_PARALLEL_COMM = None
_DATA_PARALLEL_RANK = None
_DATA_PARALLEL_WORLD_SIZE = None
_PIPELINE_PARALLEL_COMM = None
_PIPELINE_PARALLEL_RANK = None
_PIPELINE_PARALLEL_WORLD_SIZE = None
import threading
def default_init(args):
import datetime
import time... | null |
145,754 | import torch
import numpy as np
import cupy
import cupy.cuda.nccl
import torch.distributed as dist
from typing import List
def _type_torch_to_cupy(torch_type: torch.dtype):
# print(torch_type)
mappings = {
torch.uint8: cupy.cuda.nccl.NCCL_UINT8,
torch.int32: cupy.cuda.nccl.NCCL_INT32,
t... | null |
145,755 | import os
import re
import torch
import json
import numpy as np
from torch.utils.data import IterableDataset, DataLoader
from itertools import cycle, islice
import random
from datasets import Dataset
from datasets import load_dataset, load_from_disk
from comm.comm_utils import *
from itertools import islice
from random... | null |
145,756 | import os
import re
import torch
import json
import numpy as np
from torch.utils.data import IterableDataset, DataLoader
from itertools import cycle, islice
import random
from datasets import Dataset
from datasets import load_dataset, load_from_disk
from comm.comm_utils import *
from itertools import islice
from random... | null |
145,757 | import os
import re
import torch
import json
import numpy as np
from torch.utils.data import IterableDataset, DataLoader
from itertools import cycle, islice
import random
from datasets import Dataset
from datasets import load_dataset, load_from_disk
from comm.comm_utils import *
from itertools import islice
from random... | null |
145,758 | import os
import re
import torch
import json
import numpy as np
from torch.utils.data import IterableDataset, DataLoader
from itertools import cycle, islice
import random
from datasets import Dataset
from datasets import load_dataset, load_from_disk
from comm.comm_utils import *
from itertools import islice
from random... | null |
145,759 | from .dist_dp_allreduce import AllReduceDP
from .dist_dp_sharded_ps import ShardedPSDP
from .dist_dp_local import LocalDP
class AllReduceDP:
def __init__(self, args, device, module: torch.nn.Module, optimizer: torch.optim.Optimizer = None, flatten=True):
self.flatten = flatten
self.global_rank = ar... | null |
145,760 | import torch
def _assert_contiguous(tensors):
data_ptr = None
for t in tensors:
if data_ptr is not None:
assert t.data_ptr() == data_ptr
data_ptr = t.data_ptr() + t.numel() * t.element_size()
def flatten_params(param_set, chunk=None):
params = [p for p in param_set]
weights ... | null |
145,761 | import torch
def flatten_tensors(tensor_set, chunk=None):
tensors = [p for p in tensor_set]
weights = [p.data for p in tensors]
sizes = [p.numel() for p in tensors]
total_size = sum(sizes)
if chunk:
total_size = ((total_size+chunk-1)//chunk)*chunk
flatten_weights_tensor = torch.zeros(t... | null |
145,762 | import os
import json
import torch
import transformers
import torch.nn as nn
import bitsandbytes as bnb
from datasets import Dataset
from peft import LoraConfig, get_peft_model
from transformers import AutoTokenizer, AutoConfig, AutoModelForCausalLM
for param in model.parameters():
param.requires_grad = False # free... | Prints the number of trainable parameters in the model. |
145,763 | import argparse
import time
import random
import numpy as np
import torch
import torch.autograd.profiler as profiler
from tasks.data_loaders.data_utils import get_ul2r_train_data_loader
from modules.utils import gpt_loss_func
from modules.tokenizer import build_tokenizer
from pipeline_parallel.dist_pp_utils import get_... | null |
145,764 | import os
try:
import wandb
_has_wandb = True
except:
_has_wandb = False
print("wandb is not installed.")
try:
import loguru
_has_loguru = True
except:
_has_loguru = False
print("loguru is not installed.")
train_log_backend = None
def init_train_logger(args):
global train_log_b... | null |
145,765 | import os
try:
import wandb
_has_wandb = True
except:
_has_wandb = False
print("wandb is not installed.")
try:
import loguru
_has_loguru = True
except:
_has_loguru = False
print("loguru is not installed.")
train_log_backend = None
def train_log(x, *args, **kargs):
if train_log_... | null |
145,766 | import os
import time
import random
import json
import numpy as np
import torch
from comm.comm_utils import *
def load_checkpoint(pipe, args):
if os.path.isfile(os.path.join(args.checkpoint_path, 'latest')):
with open(os.path.join(args.checkpoint_path, 'latest')) as f:
latest_step = int(f.... | null |
145,767 | import os
import time
import random
import json
import numpy as np
import torch
from comm.comm_utils import *
def save_checkpoint(pipe, args) -> str:
latest_step = pipe.global_step
checkpoint_step_path = os.path.join(args.checkpoint_path, f"checkpoint_{latest_step}")
os.makedirs(checkpoint_step_p... | null |
145,768 | import os
import time
import random
import json
import numpy as np
import torch
from comm.comm_utils import *
def save_stream_dataloader_state_dict(dataloader, pipe, args):
latest_step = pipe.global_step
checkpoint_step_path = os.path.join(args.checkpoint_path, f"checkpoint_{latest_step}")
os.sys... | null |
145,769 | import os
import time
import random
import json
import numpy as np
import torch
from comm.comm_utils import *
def load_stream_dataloader_state_dict(dataloader, pipe, args):
latest_step = pipe.global_step
checkpoint_step_path = os.path.join(args.checkpoint_path, f"checkpoint_{latest_step}")
try:
... | null |
145,770 | import argparse
import boto3
import concurrent.futures
import os
import re
import sys
import time
from utils.event_report import *
def add_aws_arguments(parser: argparse.ArgumentParser):
parser.add_argument('--aws-endpoint-url', help='AWS endpoint URL')
parser.add_argument('--aws-access-key-id', help='AWS acce... | null |
145,771 | import argparse
import boto3
import concurrent.futures
import os
import re
import sys
import time
from utils.event_report import *
def aws_process_args(args: argparse.Namespace, required: bool = False):
if args.aws_endpoint_url is None:
args.aws_endpoint_url = os.environ.get('AWS_ENDPOINT_URL', 'https://s3... | null |
145,772 | import argparse
import json
import requests
import sys
import time
def add_entry_reporter_arguments(parser):
parser.add_argument('--event-host', type=str, required=False,
metavar='endpoint:port', help='Event reporting entrypoint URL')
parser.add_argument('--event-auth-token', type=str, ... | null |
145,773 |
def add_device_arguments(parser):
parser.add_argument('--use-cuda', default=True, type=lambda x: (str(x).lower() == 'true'),
help='if this is set to True, will use cuda to train')
parser.add_argument('--cuda-id', type=int, default=0, metavar='N',
help='cuda inde... | null |
145,774 |
def add_torch_distributed_arguments(parser):
parser.add_argument('--dist-backend', type=str, default='cupy_nccl', metavar='S',
help='backend type for distributed PyTorch (default: cupy_nccl)')
parser.add_argument('--dp-backend', type=str, default='nccl', metavar='S',
... | null |
145,775 |
def add_task_arguments(parser):
parser.add_argument('--train-data', nargs='+', default=['./glue_dataset/data/QQP/train.tsv'], metavar='S',
help='path to the training data')
parser.add_argument('--valid-data', nargs='+', default=['./glue_dataset/data/QQP/test.tsv'], metavar='S',
... | null |
145,776 |
def add_model_arguments(parser):
parser.add_argument('--seq-length', type=int, default=1024, metavar='N',
help='-')
parser.add_argument('--embedding-dim', type=int, default=768, metavar='N',
help='-')
parser.add_argument('--num-layers', type=int, default=4, ... | null |
145,777 |
def add_training_hyper_parameter_arguments(parser):
parser.add_argument('--train-log-backend', type=str, default='print', metavar='N',
help='-')
parser.add_argument('--project-name', type=str, default='test', metavar='N',
help='-')
parser.add_argument('--bat... | null |
145,778 |
def add_mixed_precision_arguments(parser):
parser.add_argument('--fp16', action='store_true',
help='Run model in fp16 mode.')
parser.add_argument('--loss-scale', type=float, default=0,
help='Static loss scaling, positive power of 2 values can improve fp16 conver... | null |
145,779 |
def add_parallel_schema_arguments(parser):
parser.add_argument('--pp-mode', type=str, default='gpipe', metavar='S',
help='use which pipeline parallel mode: gpipe or 1f1b.')
parser.add_argument('--dp-mode', type=str, default='allreduce', metavar='S',
help='use wh... | null |
145,780 |
def get_model_arguments_str(args):
return '_l' + str(args.seq_length) + '_m' + str(args.embedding_dim) | null |
145,781 |
def get_dist_arguments_str(args, add_rank=True):
dist_str = '_w' + str(args.world_size) + '_p' + str(args.pipeline_group_size) + "_" + \
str(args.gradient_accumulate_step) + '_d' + str(args.data_group_size)
if add_rank:
dist_str = dist_str + '_' + str(args.rank)
return dist_str | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.