id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
145,477
from beir import util, LoggingHandler from beir.datasets.data_loader import GenericDataLoader import pathlib, os, csv, random import sys import logging import argparse from tqdm import tqdm def preprocess(text): return text.replace("\r", " ").replace("\t", " ").replace("\n", " ")
null
145,478
import os import random import time import torch import torch.nn as nn from itertools import accumulate from math import ceil from colbert.utils.runs import Run from colbert.utils.utils import print_message from colbert.evaluation.metrics import Metrics from colbert.evaluation.ranking_logger import RankingLogger from c...
null
145,479
import os import ujson import torch import random from collections import defaultdict, OrderedDict from transformers import BertConfig from colbert.parameters import DEVICE from colbert.modeling.colbert import ColBERT from colbert.modeling.prefix import PrefixColBERT from colbert.utils.utils import print_message, load_...
null
145,480
import os def slow_rerank(args, query, pids, passages): colbert = args.colbert inference = args.inference Q = inference.queryFromText([query]) D_ = inference.docFromText(passages, bsize=args.bsize) scores = colbert.score(Q, D_).cpu() scores = scores.sort(descending=True) ranked = scores....
null
145,481
import os import ujson import torch import random from collections import defaultdict, OrderedDict from colbert.parameters import DEVICE from colbert.modeling.colbert import ColBERT from colbert.utils.utils import print_message, load_checkpoint from colbert.evaluation.load_model import load_model from colbert.utils.run...
null
145,482
import os import ujson import torch import random from collections import defaultdict, OrderedDict from colbert.parameters import DEVICE from colbert.modeling.colbert import ColBERT from colbert.utils.utils import print_message, load_checkpoint from colbert.evaluation.load_model import load_model from colbert.utils.run...
null
145,483
import os import ujson import torch import random from collections import defaultdict, OrderedDict from colbert.parameters import DEVICE from colbert.modeling.colbert import ColBERT from colbert.utils.utils import print_message, load_checkpoint from colbert.evaluation.load_model import load_model from colbert.utils.run...
null
145,484
import os import ujson import torch import random from collections import defaultdict, OrderedDict from colbert.parameters import DEVICE from colbert.modeling.colbert import ColBERT from colbert.utils.utils import print_message, load_checkpoint from colbert.evaluation.load_model import load_model from colbert.utils.run...
null
145,485
import os import ujson import torch import random from collections import defaultdict, OrderedDict from colbert.parameters import DEVICE from colbert.modeling.colbert import ColBERT from colbert.utils.utils import print_message, load_checkpoint from colbert.evaluation.load_model import load_model from colbert.utils.run...
null
145,486
import os import ujson import torch import random from collections import defaultdict, OrderedDict from colbert.parameters import DEVICE from colbert.modeling.colbert import ColBERT from colbert.utils.utils import print_message, load_checkpoint from colbert.evaluation.load_model import load_model from colbert.utils.run...
null
145,487
import ujson from collections import defaultdict from colbert.utils.runs import Run def evaluate_recall(qrels, queries, topK_pids): if qrels is None: return assert set(qrels.keys()) == set(queries.keys()) recall_at_k = [len(set.intersection(set(qrels[qid]), set(topK_pids[qid]))) / max(1.0, len(qre...
null
145,488
import os import time import faiss import random import torch from colbert.utils.runs import Run from multiprocessing import Pool from colbert.modeling.inference import ModelInference from colbert.evaluation.ranking_logger import RankingLogger from colbert.utils.utils import print_message, batch from colbert.ranking.fa...
null
145,489
import os import time import faiss import random import torch import itertools import shutil from colbert.utils.runs import Run from multiprocessing import Pool from colbert.modeling.inference import ModelInference from colbert.evaluation.ranking_logger import RankingLogger from colbert.utils.utils import print_message...
null
145,490
import os import math import torch import ujson import traceback from itertools import accumulate from colbert.parameters import DEVICE from colbert.utils.utils import print_message, dotdict, flatten def torch_percentile(tensor, p): assert p in range(1, 100+1) assert tensor.dim() == 1 return tensor.kthval...
null
145,491
import os import time import faiss import random import torch from colbert.utils.runs import Run from multiprocessing import Pool from colbert.modeling.inference import ModelInference from colbert.evaluation.ranking_logger import RankingLogger from colbert.utils.utils import print_message, batch from colbert.ranking.ra...
null
145,492
import os import time import faiss import random import torch from multiprocessing import Pool from colbert.modeling.inference import ModelInference from colbert.utils.utils import print_message, flatten, batch from colbert.indexing.loaders import load_doclens def uniq(l): return list(set(l))
null
145,493
import os import time import torch import queue import threading from collections import defaultdict from colbert.utils.runs import Run from colbert.modeling.inference import ModelInference from colbert.evaluation.ranking_logger import RankingLogger from colbert.utils.utils import print_message, flatten, zipstar from c...
null
145,494
import torch import faiss import numpy as np from colbert.utils.utils import print_message def load_index_part(filename, verbose=True): part = torch.load(filename) if type(part) == list: # for backward compatibility part = torch.cat(part) return part
null
145,495
import os import math import faiss import torch import numpy as np import threading import queue from colbert.utils.utils import print_message, grouper from colbert.indexing.loaders import get_parts from colbert.indexing.index_manager import load_index_part from colbert.indexing.faiss_index import FaissIndex def get_fa...
null
145,496
import os import time import torch import ujson import numpy as np import itertools import threading import queue from colbert.modeling.inference import ModelInference from colbert.evaluation.loaders import load_colbert from colbert.utils.utils import print_message from colbert.indexing.index_manager import IndexManage...
null
145,497
import os import torch import ujson from math import ceil from itertools import accumulate from colbert.utils.utils import print_message def get_parts(directory): extension = '.pt' parts = sorted([int(filename[: -1 * len(extension)]) for filename in os.listdir(directory) if filename.endswith...
null
145,498
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict def timestamp(): format_str = "%Y-%m-%d_%H.%M.%S" result = datetime.datetime.now().strftime(format_str) return result
null
145,499
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict def save_checkpoint(path, epoch_idx, mb_idx, model, optimizer, arguments=None, prefix=False): print(f"#> Saving a checkpoint to {path} ..") if hasattr(model, 'm...
null
145,500
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict def print_message(*s, condition=True): def load_checkpoint(path, model, optimizer=None, do_print=True): if do_print: print_message("#> Loading checkpoint", p...
null
145,501
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict def print_message(*s, condition=True): s = ' '.join([str(x) for x in s]) msg = "[{}] {}".format(datetime.datetime.now().strftime("%b %d, %H:%M:%S"), s) if con...
null
145,502
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict The provided code snippet includes necessary dependencies for implementing the `f7` function. Write a Python function `def f7(seq)` to solve the following problem: Sourc...
Source: https://stackoverflow.com/a/480227/1493011
145,503
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict def batch(group, bsize, provide_offset=False): offset = 0 while offset < len(group): L = group[offset: offset + bsize] yield ((offset, L) if prov...
null
145,504
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict def flatten(L): return [x for y in L for x in y]
null
145,505
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict def print_message(*s, condition=True): s = ' '.join([str(x) for x in s]) msg = "[{}] {}".format(datetime.datetime.now().strftime("%b %d, %H:%M:%S"), s) if con...
null
145,506
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict def zipstar(L, lazy=False): """ A much faster A, B, C = zip(*[(a, b, c), (a, b, c), ...]) May return lists or tuples. """ if len(L) == 0: retu...
null
145,507
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict def groupby_first_item(lst): groups = defaultdict(list) for first, *rest in lst: rest = rest[0] if len(rest) == 1 else rest groups[first].append...
null
145,508
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict The provided code snippet includes necessary dependencies for implementing the `process_grouped_by_first_item` function. Write a Python function `def process_grouped_by_...
Requires items in list to already be grouped by first item.
145,509
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict The provided code snippet includes necessary dependencies for implementing the `grouper` function. Write a Python function `def grouper(iterable, n, fillvalue=None)` to ...
Collect data into fixed-length chunks or blocks Example: grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" Source: https://docs.python.org/3/library/itertools.html#itertools-recipes
145,510
import os import tqdm import torch import datetime import itertools from multiprocessing import Pool from collections import OrderedDict, defaultdict def load_batch_backgrounds(args, qids): if args.qid2backgrounds is None: return None qbackgrounds = [] for qid in qids: back = args.qid2bac...
null
145,511
import os import random import torch import numpy as np def init(rank): nranks = 'WORLD_SIZE' in os.environ and int(os.environ['WORLD_SIZE']) nranks = max(1, nranks) is_distributed = nranks > 1 if rank == 0: print('nranks =', nranks, '\t num_gpus =', torch.cuda.device_count()) if is_distr...
null
145,512
import os import random import torch import numpy as np def barrier(rank): if rank >= 0: torch.distributed.barrier()
null
145,513
from colbert.utils.utils import print_message from utility.utils.dpr import DPR_normalize, has_answer def DPR_normalize(text): return DPR_tokenize(text).words(uncased=True) def tokenize_all_answers(args): qid, question, answers = args return qid, question, [DPR_normalize(ans) for ans in answers]
null
145,514
from colbert.utils.utils import print_message from utility.utils.dpr import DPR_normalize, has_answer def has_answer(tokenized_answers, text): def assign_label_to_passage(args): idx, (qid, pid, rank, passage, tokenized_answers) = args if idx % (1*1000*1000) == 0: print(idx) return qid, pid, rank...
null
145,515
from colbert.utils.utils import print_message from utility.utils.dpr import DPR_normalize, has_answer def check_sizes(qid2answers, qid2rankings): num_judged_queries = len(qid2answers) num_ranked_queries = len(qid2rankings) print_message('num_judged_queries =', num_judged_queries) print_message('num_ra...
null
145,516
from colbert.utils.utils import print_message from utility.utils.dpr import DPR_normalize, has_answer def compute_and_write_labels(output_path, qid2answers, qid2rankings): cutoffs = [1, 5, 10, 20, 30, 50, 100, 1000, 'all'] success = {cutoff: 0.0 for cutoff in cutoffs} counts = {cutoff: 0.0 for cutoff in cu...
null
145,517
import os import sys import git import tqdm import ujson import random from argparse import ArgumentParser from colbert.utils.utils import print_message, load_ranking, groupby_first_item, create_directory from utility.utils.save_metadata import save_metadata def sample_negatives(negatives, num_sampled, biased=None): ...
Requires that the ranks are sorted per qid.
145,518
import os import sys import git import tqdm import ujson import random from argparse import ArgumentParser from colbert.utils.utils import print_message, load_ranking, groupby_first_item def sample_negatives(negatives, num_sampled, biased=False): num_sampled = min(len(negatives), num_sampled) if biased: ...
Requires that the ranks are sorted per qid.
145,519
import os import math import ujson import random from multiprocessing import Pool from argparse import ArgumentParser from colbert.utils.utils import print_message The provided code snippet includes necessary dependencies for implementing the `process_page` function. Write a Python function `def process_page(inp)` to ...
Wraps around if we split: make sure last passage isn't too short. This is meant to be similar to the DPR preprocessing.
145,520
import string import spacy import regex import unicodedata def DPR_tokenize(text): return STokenizer.tokenize(unicodedata.normalize('NFD', text)) The provided code snippet includes necessary dependencies for implementing the `locate_answers` function. Write a Python function `def locate_answers(tokenized_answers, ...
Returns each occurrence of an answer as (offset, endpos) in terms of *characters*.
145,521
import string import spacy import regex import unicodedata The provided code snippet includes necessary dependencies for implementing the `strip_accents` function. Write a Python function `def strip_accents(text)` to solve the following problem: Strips accents from a piece of text. Here is the function: def strip_ac...
Strips accents from a piece of text.
145,522
import os import sys import git import time import copy import ujson import socket def get_metadata(args): args = copy.deepcopy(args) args.hostname = socket.gethostname() args.git_branch = git.Repo(search_parent_directories=True).active_branch.name args.git_hash = git.Repo(search_parent_directories=True...
null
145,523
import os import ujson from collections import defaultdict from colbert.utils.utils import print_message, file_tqdm def load_collection_(path, retain_titles): with open(path) as f: collection = [] for line in file_tqdm(f): _, passage, title = line.strip().split('\t') if re...
null
145,524
import os import ujson from collections import defaultdict from colbert.utils.utils import print_message, file_tqdm def load_qas_(path): print_message("#> Loading the reference QAs from", path) triples = [] with open(path) as f: for line in f: qa = ujson.loads(line) triple...
null
145,525
import argparse import os import csv import glob import json import os import pathlib import argparse import csv import logging import pickle from typing import List, Tuple import codecs from tqdm import tqdm import numpy as np import torch from torch import nn from dpr.models import init_encoder_components from dpr.op...
null
145,526
import argparse import os import csv import glob import json import os import pathlib import argparse import csv import logging import pickle from typing import List, Tuple import codecs from tqdm import tqdm import numpy as np import torch from torch import nn from dpr.models import init_encoder_components from dpr.op...
null
145,527
import json import os import sys key = { "webq": "psg_id", "nq": "passage_id", "trivia": "psg_id", "curatedtrec": "psg_id" } def convert(dataset): corpus = [] queries = [] qrels = [] data = json.load(open(f"data/retriever/{dataset}-dev.json", 'r')) for i, q in enumerate(data): ...
null
145,528
import argparse import glob import logging import math import os import random import time import torch from typing import Tuple from torch import nn from torch import Tensor as T from dpr.models import init_encoder_components from dpr.models.biencoder import BiEncoder, BiEncoderNllLoss, BiEncoderBatch from dpr.options...
null
145,529
import collections import json import logging import math import multiprocessing import pickle from functools import partial from typing import Tuple, List, Dict, Iterable, Optional import torch from torch import Tensor as T from tqdm import tqdm from dpr.utils.data_utils import Tensorizer logger = logging.getLogger() ...
Converts the file with dense retriever(or any compatible file format) results into the reader input data and serializes them into a set of files. Conversion splits the input data into multiple chunks and processes them in parallel. Each chunk results are stored in a separate file with name out_file_prefix.{number}.pkl ...
145,530
import collections import json import logging import math import multiprocessing import pickle from functools import partial from typing import Tuple, List, Dict, Iterable, Optional import torch from torch import Tensor as T from tqdm import tqdm from dpr.utils.data_utils import Tensorizer SpanPrediction = collections....
Finds the best answer span for the extractive Q&A model
145,531
import collections import logging import string import unicodedata from functools import partial from multiprocessing import Pool as ProcessPool from typing import Tuple, List, Dict import regex as re from dpr.utils.tokenizers import SimpleTokenizer def _normalize_answer(s): def remove_articles(text): retur...
null
145,532
import argparse import logging import os import random import socket import numpy as np import torch def add_tokenizer_params(parser: argparse.ArgumentParser): parser.add_argument("--do_lower_case", action='store_true', help="Whether to lower case the input text. True for uncased models, Fa...
null
145,533
import argparse import logging import os import random import socket import numpy as np import torch The provided code snippet includes necessary dependencies for implementing the `add_encoder_params` function. Write a Python function `def add_encoder_params(parser: argparse.ArgumentParser)` to solve the following pro...
Common parameters to initialize an encoder-based model
145,534
import argparse import logging import os import random import socket import numpy as np import torch def add_tuning_params(parser: argparse.ArgumentParser): # p-tuning v2 params parser.add_argument("--prefix", action="store_true") parser.add_argument("--pre_seq_len", type=int, default=8) parser.add_arg...
null
145,535
import argparse import logging import os import random import socket import numpy as np import torch def add_cuda_params(parser: argparse.ArgumentParser): parser.add_argument("--no_cuda", action='store_true', help="Whether not to use CUDA when available") parser.add_argument("--local_rank", type=int, default=-1...
Common parameters for training
145,536
import argparse import logging import os import random import socket import numpy as np import torch def add_reader_preprocessing_params(parser: argparse.ArgumentParser): parser.add_argument("--gold_passages_src", type=str, help="File with the original dataset passages (json format). Requir...
null
145,537
import argparse import logging import os import random import socket import numpy as np import torch def get_encoder_checkpoint_params_names(): return ['do_lower_case', 'pretrained_model_cfg', 'encoder_model_type', 'pretrained_file', 'projection_dim', 'sequence_length'] The provided code sn...
Selects the param values to be saved in a checkpoint, so that a trained model faile can be used for downstream tasks without the need to specify these parameter again :return: Dict of params to memorize in a checkpoint
145,538
import argparse import logging import os import random import socket import numpy as np import torch def set_seed(args): seed = args.seed random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(seed)
null
145,539
import argparse import logging import os import random import socket import numpy as np import torch logger = logging.getLogger() The provided code snippet includes necessary dependencies for implementing the `setup_args_gpu` function. Write a Python function `def setup_args_gpu(args)` to solve the following problem: ...
Setup arguments CUDA, GPU & distributed training
145,540
import argparse import logging import os import random import socket import numpy as np import torch logger = logging.getLogger() def print_args(args): logger.info(" **************** CONFIGURATION **************** ") for key, val in sorted(vars(args).items()): keystr = "{}".format(key) + (" " * (30 - l...
null
145,541
import os import time import logging import pickle from typing import List, Tuple, Iterator import faiss import numpy as np logger = logging.getLogger() def iterate_encoded_files(vector_files: list) -> Iterator[Tuple[object, np.array]]: for i, file in enumerate(vector_files): logger.info('Reading file %s',...
null
145,542
import logging from typing import Tuple import torch from torch import Tensor as T from torch import nn from transformers import AdamW, AutoConfig, BertConfig, BertModel, BertTokenizer, RobertaTokenizer from .prefix import BertPrefixModel, BertPromptModel from dpr.utils.data_utils import Tensorizer from .biencoder impo...
null
145,543
import logging from typing import Tuple import torch from torch import Tensor as T from torch import nn from transformers import AdamW, AutoConfig, BertConfig, BertModel, BertTokenizer, RobertaTokenizer from .prefix import BertPrefixModel, BertPromptModel from dpr.utils.data_utils import Tensorizer from .biencoder impo...
null
145,544
import logging from typing import Tuple import torch from torch import Tensor as T from torch import nn from transformers import AdamW, AutoConfig, BertConfig, BertModel, BertTokenizer, RobertaTokenizer from .prefix import BertPrefixModel, BertPromptModel from dpr.utils.data_utils import Tensorizer from .biencoder impo...
null
145,545
import collections import logging import random from typing import Tuple, List import numpy as np import torch import torch.nn.functional as F from torch import Tensor as T from torch import nn from dpr.utils.data_utils import Tensorizer from dpr.utils.data_utils import normalize_question The provided code snippet inc...
calculates q->ctx scores for every row in ctx_vector :param q_vector: :param ctx_vector: :return:
145,546
import collections import logging import random from typing import Tuple, List import numpy as np import torch import torch.nn.functional as F from torch import Tensor as T from torch import nn from dpr.utils.data_utils import Tensorizer from dpr.utils.data_utils import normalize_question def cosine_scores(q_vector: T...
null
145,548
import collections import logging from typing import List import numpy as np import torch import torch.nn as nn from torch import Tensor as T from torch.nn import CrossEntropyLoss from dpr.data.reader_data import ReaderSample, ReaderPassage from dpr.utils.model_utils import init_weights logger = logging.getLogger() Rea...
Creates a reader batch instance out of a list of ReaderSample-s :param pad_token_id: id of the padding token :param samples: list of samples to create the batch for :param passages_per_question: amount of passages for every question in a batch :param max_length: max model input sequence length :param max_n_answers: max...
145,549
import logging from typing import Tuple import torch from torch import Tensor as T from torch import nn from transformers import AdamW, BertConfig, BertModel, BertTokenizer, AutoConfig, AutoModelForSeq2SeqLM, AutoTokenizer from dpr.models.hf_models import get_optimizer, get_bert_tensorizer from dpr.utils.data_utils imp...
null
145,550
import json import logging import math import pickle import random from typing import List, Iterator, Callable from torch import Tensor as T logger = logging.getLogger() def read_serialized_data_from_files(paths: List[str]) -> List: results = [] for i, path in enumerate(paths): with open(path, "rb") as...
null
145,551
import json import logging import math import pickle import random from typing import List, Iterator, Callable from torch import Tensor as T logger = logging.getLogger() def read_data_from_json_files(paths: List[str], upsample_rates: List = None) -> List: results = [] if upsample_rates is None: upsampl...
null
145,552
import json import logging import math import pickle import random from typing import List, Iterator, Callable from torch import Tensor as T def normalize_question(question: str) -> str: if question[-1] == '?': question = question[:-1] return question
null
145,553
import collections import glob import logging import os from typing import List import torch from torch import nn from torch.optim.lr_scheduler import LambdaLR from torch.serialization import default_restore_location def move_to_cuda(sample): if len(sample) == 0: return {} def _move_to_cuda(maybe_tens...
null
145,554
import collections import glob import logging import os from typing import List import torch from torch import nn from torch.optim.lr_scheduler import LambdaLR from torch.serialization import default_restore_location The provided code snippet includes necessary dependencies for implementing the `get_schedule_linear` f...
Create a schedule with a learning rate that decreases linearly after linearly increasing during a warmup period.
145,556
import collections import glob import logging import os from typing import List import torch from torch import nn from torch.optim.lr_scheduler import LambdaLR from torch.serialization import default_restore_location logger = logging.getLogger() def get_model_file(args, file_prefix) -> str: if args.model_file and ...
null
145,557
import argparse import os import csv import glob import json import gzip import logging import pickle import time from typing import List, Tuple, Dict, Iterator import numpy as np import torch from torch import Tensor as T from torch import nn from dpr.data.qa_validation import calculate_matches from dpr.models import ...
null
145,558
import argparse import os import csv import glob import json import gzip import logging import pickle import time from typing import List, Tuple, Dict, Iterator import numpy as np import torch from torch import Tensor as T from torch import nn from dpr.data.qa_validation import calculate_matches from dpr.models import ...
null
145,559
import sys from pathlib import Path import logging import numpy as np from scipy.special import softmax from beir import LoggingHandler from sklearn.utils import column_or_1d from sklearn.utils.validation import check_consistent_length from sklearn.metrics._base import _check_pos_label_consistency from sklearn.calibrat...
null
145,560
import sys from pathlib import Path import logging import numpy as np from scipy.special import softmax from beir import LoggingHandler from sklearn.utils import column_or_1d from sklearn.utils.validation import check_consistent_length from sklearn.metrics._base import _check_pos_label_consistency from sklearn.calibrat...
null
145,561
import sys from pathlib import Path import logging import numpy as np from scipy.special import softmax from beir import LoggingHandler from sklearn.utils import column_or_1d from sklearn.utils.validation import check_consistent_length from sklearn.metrics._base import _check_pos_label_consistency from sklearn.calibrat...
null
145,562
import argparse import os import csv import glob import logging import time from scipy.special import softmax from utils import calibration_curve_with_ece from dpr.models import init_encoder_components from dpr.options import add_encoder_params, setup_args_gpu, print_args, set_encoder_params_from_state, \ add_toke...
null
145,563
import os import pathlib import argparse import csv import logging import pickle from typing import List, Tuple import codecs from tqdm import tqdm import numpy as np import torch from torch import nn from dpr.models import init_encoder_components from dpr.options import add_encoder_params, setup_args_gpu, print_args, ...
null
145,564
import argparse import os import csv import glob import json import os import pathlib import argparse import csv import logging import pickle from typing import List, Tuple import codecs from tqdm import tqdm import numpy as np import torch from torch import nn from dpr.models import init_encoder_components from dpr.op...
null
145,565
import argparse import os import csv import glob import json import os import pathlib import argparse import csv import logging import pickle from typing import List, Tuple import codecs from tqdm import tqdm import numpy as np import torch from torch import nn from dpr.models import init_encoder_components from dpr.op...
null
145,566
import argparse import os import csv import glob import json import gzip import logging import pickle import time from typing import List, Tuple, Dict, Iterator from tqdm import tqdm import numpy as np import torch from torch import Tensor as T from dpr.data.qa_validation import calculate_matches from dpr.options impor...
null
145,567
from enum import Enum import argparse import dataclasses from dataclasses import dataclass, field from typing import Optional from transformers import HfArgumentParser, TrainingArguments from tasks.utils import * class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model ...
Parse all the args.
145,568
import logging import os import sys import numpy as np from typing import Dict import datasets import transformers from transformers import set_seed, Trainer from transformers.trainer_utils import get_last_checkpoint from arguments import get_args from tasks.utils import * def train(trainer, resume_from_checkpoint=Non...
null
145,569
import logging import os import sys import numpy as np from typing import Dict import datasets import transformers from transformers import set_seed, Trainer from transformers.trainer_utils import get_last_checkpoint from arguments import get_args from tasks.utils import * logger = logging.getLogger(__name__) def eval...
null
145,570
import logging import os import sys import numpy as np from typing import Dict import datasets import transformers from transformers import set_seed, Trainer from transformers.trainer_utils import get_last_checkpoint from arguments import get_args from tasks.utils import * logger = logging.getLogger(__name__) def pred...
null
145,571
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...
145,572
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...
145,573
import logging import os import random import sys from transformers import ( AutoConfig, AutoTokenizer, ) from tasks.qa.dataset import SQuAD from training.trainer_qa import QuestionAnsweringTrainer from model.utils import get_model, TaskType class SQuAD: def __init__(self, tokenizer: AutoTokenizer, data_a...
null
145,574
import logging import os import random import sys from transformers import ( AutoConfig, AutoTokenizer, ) from tasks.srl.dataset import SRLDataset from training.trainer_exp import ExponentialTrainer from model.utils import get_model, TaskType from tasks.utils import ADD_PREFIX_SPACE, USE_FAST logger = logging.g...
null
145,575
import logging import os import random import sys from transformers import ( AutoConfig, AutoTokenizer, ) from tasks.ner.dataset import NERDataset from training.trainer_exp import ExponentialTrainer from model.utils import get_model, TaskType from tasks.utils import ADD_PREFIX_SPACE, USE_FAST logger = logging.g...
null
145,576
import re import string from collections import defaultdict, Counter def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def white_space_fix(text): return ' '.join(text.split()...
null
145,577
import re import string from collections import defaultdict, Counter def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def white_space_fix(text): return ' '.join(text.split()...
null
145,578
import re import string from collections import defaultdict, Counter def metric_max_over_ground_truths(metric_fn, prediction, ground_truths): scores_for_ground_truths = [] for ground_truth in ground_truths: score = metric_fn(prediction, ground_truth) scores_for_ground_truths.append(score) r...
null