code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def postprocess_qa_predictions(
examples,
features,
predictions: Tuple[np.ndarray, np.ndarray],
version_2_with_negative: bool = False,
n_best_size: int = 20,
max_answer_length: int = 30,
null_score_diff_threshold: float = 0.0,
output_dir: Optional[str] = None,
prefix: Optional[str] =... |
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 mo... | postprocess_qa_predictions | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/flax/question-answering/utils_qa.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/flax/question-answering/utils_qa.py | Apache-2.0 |
def postprocess_qa_predictions_with_beam_search(
examples,
features,
predictions: Tuple[np.ndarray, np.ndarray],
version_2_with_negative: bool = False,
n_best_size: int = 20,
max_answer_length: int = 30,
start_n_top: int = 5,
end_n_top: int = 5,
output_dir: Optional[str] = None,
... |
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: Th... | postprocess_qa_predictions_with_beam_search | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/flax/question-answering/utils_qa.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/flax/question-answering/utils_qa.py | Apache-2.0 |
def load_rocstories_dataset(dataset_path):
"""Output a list of tuples(story, 1st continuation, 2nd continuation, label)"""
with open(dataset_path, encoding="utf_8") as f:
f = csv.reader(f)
output = []
next(f) # skip the first line
for line in tqdm(f):
output.append((... | Output a list of tuples(story, 1st continuation, 2nd continuation, label) | load_rocstories_dataset | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/run_openai_gpt.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/run_openai_gpt.py | Apache-2.0 |
def convert_examples_to_features(
examples: List[InputExample],
label_list: List[str],
max_length: int,
tokenizer: PreTrainedTokenizer,
) -> List[InputFeatures]:
"""
Loads a data file into a list of `InputFeatures`
"""
label_map = {label: i for i, label in enumerate(label_list)}
fe... |
Loads a data file into a list of `InputFeatures`
| convert_examples_to_features | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/multiple_choice/utils_multiple_choice.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/multiple_choice/utils_multiple_choice.py | Apache-2.0 |
def configure_optimizers(self):
"""Prepare optimizer and schedule (linear warmup and decay)"""
model = self.model
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in model.named_parameters() if not any(nd in n fo... | Prepare optimizer and schedule (linear warmup and decay) | configure_optimizers | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/pytorch-lightning/lightning_base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/pytorch-lightning/lightning_base.py | Apache-2.0 |
def total_steps(self) -> int:
"""The number of total training steps that will be run. Used for lr scheduler purposes."""
num_devices = max(1, self.hparams.gpus) # TODO: consider num_tpu_cores
effective_batch_size = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devic... | The number of total training steps that will be run. Used for lr scheduler purposes. | total_steps | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/pytorch-lightning/lightning_base.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/pytorch-lightning/lightning_base.py | Apache-2.0 |
def prepare_data(self):
"Called to initialize data. Use the call to construct features"
args = self.hparams
processor = processors[args.task]()
self.labels = processor.get_labels()
for mode in ["train", "dev"]:
cached_features_file = self._feature_file(mode)
... | Called to initialize data. Use the call to construct features | prepare_data | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/pytorch-lightning/run_glue.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/pytorch-lightning/run_glue.py | Apache-2.0 |
def get_dataloader(self, mode: str, batch_size: int, shuffle: bool = False) -> DataLoader:
"Load datasets. Called after prepare data."
# We test on dev set to compare to benchmarks without having to submit to GLUE server
mode = "dev" if mode == "test" else mode
cached_features_file = s... | Load datasets. Called after prepare data. | get_dataloader | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/pytorch-lightning/run_glue.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/pytorch-lightning/run_glue.py | Apache-2.0 |
def _eval_end(self, outputs):
"Evaluation called for both Val and Test"
val_loss_mean = torch.stack([x["val_loss"] for x in outputs]).mean()
preds = np.concatenate([x["pred"] for x in outputs], axis=0)
preds = np.argmax(preds, axis=2)
out_label_ids = np.concatenate([x["target"] f... | Evaluation called for both Val and Test | _eval_end | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/pytorch-lightning/run_ner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/pytorch-lightning/run_ner.py | Apache-2.0 |
def convert(src_path: str, map_location: str = "cpu", save_path: Union[str, None] = None) -> None:
"""Convert a pytorch_model.bin or model.pt file to torch.float16 for faster downloads, less disk space."""
state_dict = torch.load(src_path, map_location=map_location)
for k, v in tqdm(state_dict.items()):
... | Convert a pytorch_model.bin or model.pt file to torch.float16 for faster downloads, less disk space. | convert | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/convert_model_to_fp16.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/convert_model_to_fp16.py | Apache-2.0 |
def download_wmt_dataset(src_lang="ro", tgt_lang="en", dataset="wmt16", save_dir=None) -> None:
"""Download a dataset using the datasets package and save it to the format expected by finetune.py
Format of save_dir: train.source, train.target, val.source, val.target, test.source, test.target.
Args:
... | Download a dataset using the datasets package and save it to the format expected by finetune.py
Format of save_dir: train.source, train.target, val.source, val.target, test.source, test.target.
Args:
src_lang: <str> source language
tgt_lang: <str> target language
dataset: <str> wmt16, w... | download_wmt_dataset | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/download_wmt.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/download_wmt.py | Apache-2.0 |
def handle_metrics(split, metrics, output_dir):
"""
Log and save metrics
Args:
- split: one of train, val, test
- metrics: metrics dict
- output_dir: where to save the metrics
"""
logger.info(f"***** {split} metrics *****")
for key in sorted(metrics.keys()):
logger.info(f" ... |
Log and save metrics
Args:
- split: one of train, val, test
- metrics: metrics dict
- output_dir: where to save the metrics
| handle_metrics | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/finetune_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/finetune_trainer.py | Apache-2.0 |
def minify(src_dir: str, dest_dir: str, n: int):
"""Write first n lines of each file f in src_dir to dest_dir/f"""
src_dir = Path(src_dir)
dest_dir = Path(dest_dir)
dest_dir.mkdir(exist_ok=True)
for path in src_dir.iterdir():
new = [x.rstrip() for x in list(path.open().readlines())][:n]
... | Write first n lines of each file f in src_dir to dest_dir/f | minify | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/minify_dataset.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/minify_dataset.py | Apache-2.0 |
def eval_data_dir(
data_dir,
save_dir: str,
model_name: str,
bs: int = 8,
max_source_length: int = 1024,
type_path="val",
n_obs=None,
fp16=False,
task="summarization",
local_rank=None,
num_return_sequences=1,
dataset_kwargs: Dict = None,
prefix="",
**generate_kwar... | Run evaluation on part of the data for one gpu and save to {save_dir}/rank_{rank}_output.json | eval_data_dir | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/run_distributed_eval.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/run_distributed_eval.py | Apache-2.0 |
def combine_partial_results(partial_results) -> List:
"""Concatenate partial results into one file, then sort it by id."""
records = []
for partial_result in partial_results:
records.extend(partial_result)
records = list(sorted(records, key=lambda x: x["id"]))
preds = [x["pred"] for x in rec... | Concatenate partial results into one file, then sort it by id. | combine_partial_results | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/run_distributed_eval.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/run_distributed_eval.py | Apache-2.0 |
def generate_summaries_or_translations(
examples: List[str],
out_file: str,
model_name: str,
batch_size: int = 8,
device: str = DEFAULT_DEVICE,
fp16=False,
task="summarization",
prefix=None,
**generate_kwargs,
) -> Dict:
"""Save model.generate results to <out_file>, and return ho... | Save model.generate results to <out_file>, and return how long it took. | generate_summaries_or_translations | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/run_eval.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/run_eval.py | Apache-2.0 |
def run_generate(verbose=True):
"""
Takes input text, generates output, and then using reference calculates the BLEU scores.
The results are saved to a file and returned to the caller, and printed out unless ``verbose=False`` is passed.
Args:
verbose (:obj:`bool`, `optional`, defaults to :obj... |
Takes input text, generates output, and then using reference calculates the BLEU scores.
The results are saved to a file and returned to the caller, and printed out unless ``verbose=False`` is passed.
Args:
verbose (:obj:`bool`, `optional`, defaults to :obj:`True`): print results to stdout
... | run_generate | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/run_eval.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/run_eval.py | Apache-2.0 |
def run_search():
"""
Run parametric search over the desired hparam space with help of ``run_eval.py``.
All the arguments except ``--search`` are passed to ``run_eval.py`` as is. The values inside of "--search" are parsed, reformatted and fed to ``run_eval.py`` as additional args.
The format for the... |
Run parametric search over the desired hparam space with help of ``run_eval.py``.
All the arguments except ``--search`` are passed to ``run_eval.py`` as is. The values inside of "--search" are parsed, reformatted and fed to ``run_eval.py`` as additional args.
The format for the ``--search`` value is a ... | run_search | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/run_eval_search.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/run_eval_search.py | Apache-2.0 |
def save_len_file(
tokenizer_name, data_dir, max_source_length=1024, max_target_length=1024, consider_target=False, **kwargs
):
"""Save max(src_len, tgt_len) for each example to allow dynamic batching."""
tok = AutoTokenizer.from_pretrained(tokenizer_name)
train_ds = Seq2SeqDataset(tok, data_dir, max_so... | Save max(src_len, tgt_len) for each example to allow dynamic batching. | save_len_file | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/save_len_file.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/save_len_file.py | Apache-2.0 |
def save_randomly_initialized_version(config_name: str, save_dir: str, **config_kwargs):
"""Save a randomly initialized version of a model using a pretrained config.
Args:
config_name: which config to use
save_dir: where to save the resulting model and tokenizer
config_kwargs: Passed to ... | Save a randomly initialized version of a model using a pretrained config.
Args:
config_name: which config to use
save_dir: where to save the resulting model and tokenizer
config_kwargs: Passed to AutoConfig
Usage::
save_randomly_initialized_version("facebook/bart-large-cnn", "di... | save_randomly_initialized_version | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/save_randomly_initialized_model.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/save_randomly_initialized_model.py | Apache-2.0 |
def add_newline_to_end_of_each_sentence(x: str) -> str:
"""This was added to get rougeLsum scores matching published rougeL scores for BART and PEGASUS."""
re.sub("<n>", "", x) # remove pegasus newline char
assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install ... | This was added to get rougeLsum scores matching published rougeL scores for BART and PEGASUS. | add_newline_to_end_of_each_sentence | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/sentence_splitter.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/sentence_splitter.py | Apache-2.0 |
def create_optimizer_and_scheduler(self, num_training_steps: int):
"""
Setup the optimizer and the learning rate scheduler.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through :obj:`optimizers`, or subcla... |
Setup the optimizer and the learning rate scheduler.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.
| create_optimizer_and_scheduler | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/seq2seq_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/seq2seq_trainer.py | Apache-2.0 |
def prediction_step(
self,
model: nn.Module,
inputs: Dict[str, Union[torch.Tensor, Any]],
prediction_loss_only: bool,
ignore_keys: Optional[List[str]] = None,
) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
"""
Perform an evaluatio... |
Perform an evaluation step on :obj:`model` using obj:`inputs`.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to evaluate.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and ta... | prediction_step | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/seq2seq_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/seq2seq_trainer.py | Apache-2.0 |
def trim_batch(
input_ids,
pad_token_id,
attention_mask=None,
):
"""Remove columns that are populated exclusively by pad_token_id"""
keep_column_mask = input_ids.ne(pad_token_id).any(dim=0)
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_i... | Remove columns that are populated exclusively by pad_token_id | trim_batch | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | Apache-2.0 |
def sortish_sampler_indices(data: List, bs: int, shuffle=True) -> np.array:
"Go through the text data by order of src length with a bit of randomness. From fastai repo."
if not shuffle:
return np.argsort(np.array(data) * -1)
def key_fn(i):
return data[i]
idxs = np.random.permutation(le... | Go through the text data by order of src length with a bit of randomness. From fastai repo. | sortish_sampler_indices | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | Apache-2.0 |
def use_task_specific_params(model, task):
"""Update config with summarization specific params."""
task_specific_params = model.config.task_specific_params
if task_specific_params is not None:
pars = task_specific_params.get(task, {})
logger.info(f"setting model.config to task specific para... | Update config with summarization specific params. | use_task_specific_params | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | Apache-2.0 |
def calculate_rouge(
pred_lns: List[str],
tgt_lns: List[str],
use_stemmer=True,
rouge_keys=ROUGE_KEYS,
return_precision_and_recall=False,
bootstrap_aggregation=True,
newline_sep=True,
) -> Dict:
"""Calculate rouge using rouge_scorer package.
Args:
pred_lns: list of summaries... | Calculate rouge using rouge_scorer package.
Args:
pred_lns: list of summaries generated by model
tgt_lns: list of groundtruth summaries (e.g. contents of val.target)
use_stemmer: Bool indicating whether Porter stemmer should be used to
strip word suffixes to improve matching.
... | calculate_rouge | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | Apache-2.0 |
def freeze_params(model: nn.Module):
"""Set requires_grad=False for each of model.parameters()"""
for par in model.parameters():
par.requires_grad = False | Set requires_grad=False for each of model.parameters() | freeze_params | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | Apache-2.0 |
def freeze_embeds(model):
"""Freeze token embeddings and positional embeddings for bart, just token embeddings for t5."""
model_type = model.config.model_type
if model_type in ["t5", "mt5"]:
freeze_params(model.shared)
for d in [model.encoder, model.decoder]:
freeze_params(d.emb... | Freeze token embeddings and positional embeddings for bart, just token embeddings for t5. | freeze_embeds | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | Apache-2.0 |
def parse_numeric_n_bool_cl_kwargs(unparsed_args: List[str]) -> Dict[str, Union[int, float, bool]]:
"""
Parse an argv list of unspecified command line args to a dict.
Assumes all values are either numeric or boolean in the form of true/false.
"""
result = {}
assert len(unparsed_args) % 2 == 0, f... |
Parse an argv list of unspecified command line args to a dict.
Assumes all values are either numeric or boolean in the form of true/false.
| parse_numeric_n_bool_cl_kwargs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | Apache-2.0 |
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i : i + n] | Yield successive n-sized chunks from lst. | chunks | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | Apache-2.0 |
def check_output_dir(args, expected_items=0):
"""
Checks whether to bail out if output_dir already exists and has more than expected_items in it
`args`: needs to have the following attributes of `args`:
- output_dir
- do_train
- overwrite_output_dir
`expected_items`: normally 0 (defa... |
Checks whether to bail out if output_dir already exists and has more than expected_items in it
`args`: needs to have the following attributes of `args`:
- output_dir
- do_train
- overwrite_output_dir
`expected_items`: normally 0 (default) - i.e. empty dir, but in some cases a few files ... | check_output_dir | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/utils.py | Apache-2.0 |
def parse_args():
"""
Helper function parsing the command line options
@retval ArgumentParser
"""
parser = ArgumentParser(
description=(
"PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"
)
)
# Optional argu... |
Helper function parsing the command line options
@retval ArgumentParser
| parse_args | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/seq2seq/xla_spawn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/seq2seq/xla_spawn.py | Apache-2.0 |
def convert_examples_to_features(
examples: List[InputExample],
label_list: List[str],
max_seq_length: int,
tokenizer: PreTrainedTokenizer,
cls_token_at_end=False,
cls_token="[CLS]",
cls_token_segment_id=1,
sep_token="[SEP]",
sep_token_extra=False,... | Loads a data file into a list of `InputFeatures`
`cls_token_at_end` define the location of the CLS token:
- False (Default, BERT/XLM pattern): [CLS] + A + [SEP] + B + [SEP]
- True (XLNet/GPT pattern): A + [SEP] + B + [SEP] + [CLS]
`cls_token_segment_id` define the segment id asso... | convert_examples_to_features | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/legacy/token-classification/utils_ner.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/legacy/token-classification/utils_ner.py | Apache-2.0 |
def random_subsample(wav: np.ndarray, max_length: float, sample_rate: int = 16000):
"""Randomly sample chunks of `max_length` seconds from the input audio"""
sample_length = int(round(sample_rate * max_length))
if len(wav) <= sample_length:
return wav
random_offset = randint(0, len(wav) - sample... | Randomly sample chunks of `max_length` seconds from the input audio | random_subsample | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/pytorch/audio-classification/run_audio_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/pytorch/audio-classification/run_audio_classification.py | Apache-2.0 |
def compute_metrics(eval_pred):
"""Computes accuracy on a batch of predictions"""
predictions = np.argmax(eval_pred.predictions, axis=1)
return metric.compute(predictions=predictions, references=eval_pred.label_ids) | Computes accuracy on a batch of predictions | compute_metrics | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/pytorch/audio-classification/run_audio_classification.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/pytorch/audio-classification/run_audio_classification.py | Apache-2.0 |
def preprocess_images(examples):
"""Preprocess a batch of images by applying transforms + creating a corresponding mask, indicating
which patches to mask."""
examples["pixel_values"] = [transforms(image) for image in examples[image_column_name]]
examples["mask"] = [mask_generator() for ... | Preprocess a batch of images by applying transforms + creating a corresponding mask, indicating
which patches to mask. | preprocess_images | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/pytorch/image-pretraining/run_mim.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/pytorch/image-pretraining/run_mim.py | Apache-2.0 |
def save_prefixed_metrics(results, output_dir, file_name: str = "all_results.json", metric_key_prefix: str = "eval"):
"""
Save results while prefixing metric names.
Args:
results: (:obj:`dict`):
A dictionary of results.
output_dir: (:obj:`str`):
An output directory.
... |
Save results while prefixing metric names.
Args:
results: (:obj:`dict`):
A dictionary of results.
output_dir: (:obj:`str`):
An output directory.
file_name: (:obj:`str`, `optional`, defaults to :obj:`all_results.json`):
An output file name.
me... | save_prefixed_metrics | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/pytorch/question-answering/run_qa_beam_search_no_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/pytorch/question-answering/run_qa_beam_search_no_trainer.py | Apache-2.0 |
def get_grad_norm(params, scale=1):
"""Compute grad norm given a gradient scale."""
total_norm = 0.0
for p in params:
if p.grad is not None:
param_norm = (p.grad.detach().data / scale).norm(2)
total_norm += param_norm.item() ** 2
total_norm = total_norm**0.5
return to... | Compute grad norm given a gradient scale. | get_grad_norm | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/pytorch/speech-pretraining/run_wav2vec2_pretraining_no_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/pytorch/speech-pretraining/run_wav2vec2_pretraining_no_trainer.py | Apache-2.0 |
def hans_data_collator(features: List[InputFeatures]) -> Dict[str, torch.Tensor]:
"""
Data collator that removes the "pairID" key if present.
"""
batch = default_data_collator(features)
_ = batch.pop("pairID", None)
return batch |
Data collator that removes the "pairID" key if present.
| hans_data_collator | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/adversarial/run_hans.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/adversarial/run_hans.py | Apache-2.0 |
def hans_convert_examples_to_features(
examples: List[InputExample],
label_list: List[str],
max_length: int,
tokenizer: PreTrainedTokenizer,
):
"""
Loads a data file into a list of ``InputFeatures``
Args:
examples: List of ``InputExamples`` containing the examples.
label_lis... |
Loads a data file into a list of ``InputFeatures``
Args:
examples: List of ``InputExamples`` containing the examples.
label_list: List of labels. Can be obtained from the processor using the ``processor.get_labels()`` method.
max_length: Maximum example length.
tokenizer: Insta... | hans_convert_examples_to_features | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/adversarial/utils_hans.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/adversarial/utils_hans.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_dropout=None,
output_layers=None,
regression=False,
):
r"""
Return:
:... |
Return:
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.AlbertConfig`) and inputs:
last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
Sequence of hidde... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_albert.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_albert.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
... |
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the sequence classification/regression loss.
Indices should be in ``[0, ..., config.num_labels - 1]``.
If ``config.num_labels == 1`` a regression loss is computed... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_albert.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_albert.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_dropout=None,
output_layers=None,
... |
Return:
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_bert.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_bert.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
... |
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the sequence classification/regression loss.
Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
If :obj:`config.num_labels == 1` a regression loss is co... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_bert.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bert-loses-patience/pabee/modeling_pabee_bert.py | Apache-2.0 |
def forward(
self,
input_ids,
encoder_hidden_states=None,
state=None,
attention_mask=None,
memory_lengths=None,
step=None,
cache=None,
encoder_attention_mask=None,
):
"""
See :obj:`onmt.modules.RNNDecoderBase.forward()`
... |
See :obj:`onmt.modules.RNNDecoderBase.forward()`
memory_bank = encoder_hidden_states
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def forward(
self,
inputs,
memory_bank,
src_pad_mask,
tgt_pad_mask,
previous_input=None,
layer_cache=None,
step=None,
):
"""
Args:
inputs (`FloatTensor`): `[batch_size x 1 x model_dim]`
memory_bank (`FloatTensor`... |
Args:
inputs (`FloatTensor`): `[batch_size x 1 x model_dim]`
memory_bank (`FloatTensor`): `[batch_size x src_len x model_dim]`
src_pad_mask (`LongTensor`): `[batch_size x 1 x src_len]`
tgt_pad_mask (`LongTensor`): `[batch_size x 1 x 1]`
Returns:
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def _get_attn_subsequent_mask(self, size):
"""
Get an attention mask to avoid using the subsequent info.
Args:
size: int
Returns:
(`LongTensor`):
* subsequent_mask `[1 x size x size]`
"""
attn_shape = (1, size, size)
subseque... |
Get an attention mask to avoid using the subsequent info.
Args:
size: int
Returns:
(`LongTensor`):
* subsequent_mask `[1 x size x size]`
| _get_attn_subsequent_mask | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def forward(
self,
key,
value,
query,
mask=None,
layer_cache=None,
type=None,
predefined_graph_1=None,
):
"""
Compute the context vector and the attention vectors.
Args:
key (`FloatTensor`): set of `key_len`
... |
Compute the context vector and the attention vectors.
Args:
key (`FloatTensor`): set of `key_len`
key vectors `[batch, key_len, dim]`
value (`FloatTensor`): set of `key_len`
value vectors `[batch, key_len, dim]`
query (`FloatTensor`): se... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def __init__(self, src):
"""
Args:
src (FloatTensor): a sequence of source words tensors
with optional feature tensors, of size (len x batch).
"""
self.src = src
self.previous_input = None
self.previous_layer_inputs = None
self.cach... |
Args:
src (FloatTensor): a sequence of source words tensors
with optional feature tensors, of size (len x batch).
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def _all(self):
"""
Contains attributes that need to be updated in self.beam_update().
"""
if self.previous_input is not None and self.previous_layer_inputs is not None:
return (self.previous_input, self.previous_layer_inputs, self.src)
else:
return (self.... |
Contains attributes that need to be updated in self.beam_update().
| _all | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def length_wu(self, beam, logprobs, alpha=0.0):
"""
NMT length re-ranking score from
"Google's Neural Machine Translation System" :cite:`wu2016google`.
"""
modifier = ((5 + len(beam.next_ys)) ** alpha) / ((5 + 1) ** alpha)
return logprobs / modifier |
NMT length re-ranking score from
"Google's Neural Machine Translation System" :cite:`wu2016google`.
| length_wu | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def translate(self, batch, step, attn_debug=False):
"""Generates summaries from one batch of data."""
self.model.eval()
with torch.no_grad():
batch_data = self.translate_batch(batch)
translations = self.from_batch(batch_data)
return translations | Generates summaries from one batch of data. | translate | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def translate_batch(self, batch, fast=False):
"""
Translate a batch of sentences.
Mostly a wrapper around :obj:`Beam`.
Args:
batch (:obj:`Batch`): a batch from a dataset object
fast (bool): enables fast beam search (may not support all features)
"""
... |
Translate a batch of sentences.
Mostly a wrapper around :obj:`Beam`.
Args:
batch (:obj:`Batch`): a batch from a dataset object
fast (bool): enables fast beam search (may not support all features)
| translate_batch | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def _fast_translate_batch(self, batch, max_length, min_length=0):
"""Beam Search using the encoder inputs contained in `batch`."""
# The batch object is funny
# Instead of just looking at the size of the arguments we encapsulate
# a size argument.
# Where is it defined?
... | Beam Search using the encoder inputs contained in `batch`. | _fast_translate_batch | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def tile(x, count, dim=0):
"""
Tiles x on dimension dim count times.
"""
perm = list(range(len(x.size())))
if dim != 0:
perm[0], perm[dim] = perm[dim], perm[0]
x = x.permute(perm).contiguous()
out_size = list(x.size())
out_size[0] *= count
batch = x.size(0)
x = x.view... |
Tiles x on dimension dim count times.
| tile | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/modeling_bertabs.py | Apache-2.0 |
def save_summaries(summaries, path, original_document_name):
"""Write the summaries in fies that are prefixed by the original
files' name with the `_summary` appended.
Attributes:
original_document_names: List[string]
Name of the document that was summarized.
path: string
... | Write the summaries in fies that are prefixed by the original
files' name with the `_summary` appended.
Attributes:
original_document_names: List[string]
Name of the document that was summarized.
path: string
Path were the summaries will be written
summaries: Lis... | save_summaries | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/run_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/run_summarization.py | Apache-2.0 |
def format_summary(translation):
"""Transforms the output of the `from_batch` function
into nicely formatted summaries.
"""
raw_summary, _, _ = translation
summary = (
raw_summary.replace("[unused0]", "")
.replace("[unused3]", "")
.replace("[PAD]", "")
.replace("[unus... | Transforms the output of the `from_batch` function
into nicely formatted summaries.
| format_summary | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/run_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/run_summarization.py | Apache-2.0 |
def collate(data, tokenizer, block_size, device):
"""Collate formats the data passed to the data loader.
In particular we tokenize the data batch after batch to avoid keeping them
all in memory. We output the data as a namedtuple to fit the original BertAbs's
API.
"""
data = [x for x in data if... | Collate formats the data passed to the data loader.
In particular we tokenize the data batch after batch to avoid keeping them
all in memory. We output the data as a namedtuple to fit the original BertAbs's
API.
| collate | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/run_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/run_summarization.py | Apache-2.0 |
def decode_summary(summary_tokens, tokenizer):
"""Decode the summary and return it in a format
suitable for evaluation.
"""
summary_tokens = summary_tokens.to("cpu").numpy()
summary = tokenizer.decode(summary_tokens)
sentences = summary.split(".")
sentences = [s + "." for s in sentences]
... | Decode the summary and return it in a format
suitable for evaluation.
| decode_summary | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/run_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/run_summarization.py | Apache-2.0 |
def main():
"""The main function defines the interface with the users."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--documents_dir",
default=None,
type=str,
required=True,
help="The folder where the documents to summarize are located.",
)
parse... | The main function defines the interface with the users. | main | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/run_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/run_summarization.py | Apache-2.0 |
def test_fit_to_block_sequence_too_small(self):
"""Pad the sequence with 0 if the sequence is smaller than the block size."""
sequence = [1, 2, 3, 4]
expected_output = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
self.assertEqual(truncate_or_pad(sequence, self.block_size, 0), expected_output) | Pad the sequence with 0 if the sequence is smaller than the block size. | test_fit_to_block_sequence_too_small | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/test_utils_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/test_utils_summarization.py | Apache-2.0 |
def test_fit_to_block_sequence_fit_exactly(self):
"""Do nothing if the sequence is the right size."""
sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
expected_output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.assertEqual(truncate_or_pad(sequence, self.block_size, 0), expected_output) | Do nothing if the sequence is the right size. | test_fit_to_block_sequence_fit_exactly | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/test_utils_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/test_utils_summarization.py | Apache-2.0 |
def test_fit_to_block_sequence_too_big(self):
"""Truncate the sequence if it is too long."""
sequence = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
expected_output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
self.assertEqual(truncate_or_pad(sequence, self.block_size, 0), expected_output) | Truncate the sequence if it is too long. | test_fit_to_block_sequence_too_big | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/test_utils_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/test_utils_summarization.py | Apache-2.0 |
def test_process_story_no_highlights(self):
"""Processing a story with no highlights returns an empty list for the summary."""
raw_story = """It was the year of Our Lord one thousand seven hundred and
seventy-five.\n\nSpiritual revelations were conceded to England at that
favoured period... | Processing a story with no highlights returns an empty list for the summary. | test_process_story_no_highlights | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/test_utils_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/test_utils_summarization.py | Apache-2.0 |
def test_process_empty_story(self):
"""An empty story returns an empty collection of lines."""
raw_story = ""
story_lines, summary_lines = process_story(raw_story)
self.assertEqual(story_lines, [])
self.assertEqual(summary_lines, []) | An empty story returns an empty collection of lines. | test_process_empty_story | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/test_utils_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/test_utils_summarization.py | Apache-2.0 |
def __init__(self, path="", prefix="train"):
"""We initialize the class by listing all the documents to summarize.
Files are not read in memory due to the size of some datasets (like CNN/DailyMail).
"""
assert os.path.isdir(path)
self.documents = []
story_filenames_list ... | We initialize the class by listing all the documents to summarize.
Files are not read in memory due to the size of some datasets (like CNN/DailyMail).
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/utils_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/utils_summarization.py | Apache-2.0 |
def process_story(raw_story):
"""Extract the story and summary from a story file.
Arguments:
raw_story (str): content of the story file as an utf-8 encoded string.
Raises:
IndexError: If the story is empty or contains no highlights.
"""
nonempty_lines = list(filter(lambda x: len(x)... | Extract the story and summary from a story file.
Arguments:
raw_story (str): content of the story file as an utf-8 encoded string.
Raises:
IndexError: If the story is empty or contains no highlights.
| process_story | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/utils_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/utils_summarization.py | Apache-2.0 |
def truncate_or_pad(sequence, block_size, pad_token_id):
"""Adapt the source and target sequences' lengths to the block size.
If the sequence is shorter we append padding token to the right of the sequence.
"""
if len(sequence) > block_size:
return sequence[:block_size]
else:
sequenc... | Adapt the source and target sequences' lengths to the block size.
If the sequence is shorter we append padding token to the right of the sequence.
| truncate_or_pad | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/utils_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/utils_summarization.py | Apache-2.0 |
def build_mask(sequence, pad_token_id):
"""Builds the mask. The attention mechanism will only attend to positions
with value 1."""
mask = torch.ones_like(sequence)
idx_pad_tokens = sequence == pad_token_id
mask[idx_pad_tokens] = 0
return mask | Builds the mask. The attention mechanism will only attend to positions
with value 1. | build_mask | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/utils_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/utils_summarization.py | Apache-2.0 |
def encode_for_summarization(story_lines, summary_lines, tokenizer):
"""Encode the story and summary lines, and join them
as specified in [1] by using `[SEP] [CLS]` tokens to separate
sentences.
"""
story_lines_token_ids = [tokenizer.encode(line) for line in story_lines]
story_token_ids = [token... | Encode the story and summary lines, and join them
as specified in [1] by using `[SEP] [CLS]` tokens to separate
sentences.
| encode_for_summarization | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertabs/utils_summarization.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertabs/utils_summarization.py | Apache-2.0 |
def entropy(p):
"""Compute the entropy of a probability distribution"""
plogp = p * torch.log(p)
plogp[p == 0] = 0
return -plogp.sum(dim=-1) | Compute the entropy of a probability distribution | entropy | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertology/run_bertology.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertology/run_bertology.py | Apache-2.0 |
def compute_heads_importance(
args, model, eval_dataloader, compute_entropy=True, compute_importance=True, head_mask=None, actually_pruned=False
):
"""This method shows how to compute:
- head attention entropy
- head importance scores according to http://arxiv.org/abs/1905.10650
"""
# Prepare ou... | This method shows how to compute:
- head attention entropy
- head importance scores according to http://arxiv.org/abs/1905.10650
| compute_heads_importance | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertology/run_bertology.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertology/run_bertology.py | Apache-2.0 |
def mask_heads(args, model, eval_dataloader):
"""This method shows how to mask head (set some heads to zero), to test the effect on the network,
based on the head importance scores, as described in Michel et al. (http://arxiv.org/abs/1905.10650)
"""
_, head_importance, preds, labels = compute_heads_impo... | This method shows how to mask head (set some heads to zero), to test the effect on the network,
based on the head importance scores, as described in Michel et al. (http://arxiv.org/abs/1905.10650)
| mask_heads | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertology/run_bertology.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertology/run_bertology.py | Apache-2.0 |
def prune_heads(args, model, eval_dataloader, head_mask):
"""This method shows how to prune head (remove heads weights) based on
the head importance scores as described in Michel et al. (http://arxiv.org/abs/1905.10650)
"""
# Try pruning and test time speedup
# Pruning is like masking but we actuall... | This method shows how to prune head (remove heads weights) based on
the head importance scores as described in Michel et al. (http://arxiv.org/abs/1905.10650)
| prune_heads | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/bertology/run_bertology.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/bertology/run_bertology.py | Apache-2.0 |
def __call__(self, input_ids, scores, **kwargs):
"""Returns true if all generated sequences contain any of the end-of-function strings."""
decoded_generations = self.tokenizer.batch_decode(input_ids[:, self.start_length :])
done = []
for decoded_generation in decoded_generations:
... | Returns true if all generated sequences contain any of the end-of-function strings. | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/human_eval.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/human_eval.py | Apache-2.0 |
def remove_last_block(string):
"""Remove the last block of the code containing EOF_STRINGS"""
string_list = re.split("(%s)" % "|".join(EOF_STRINGS), string)
# last string should be ""
return "".join(string_list[:-2]) | Remove the last block of the code containing EOF_STRINGS | remove_last_block | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/human_eval.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/human_eval.py | Apache-2.0 |
def complete_code(accelerator, model, tokenizer, dataloader, n_tasks, batch_size=20, **gen_kwargs):
"""Generate multiple codes for each task in the dataset. This function leverage accelerator to distribute
the processing to multiple GPUs.
dataloader, a wrapper around a TokenizeDataset objectm is supposed to... | Generate multiple codes for each task in the dataset. This function leverage accelerator to distribute
the processing to multiple GPUs.
dataloader, a wrapper around a TokenizeDataset objectm is supposed to send all the prompts from
the evalution dataset to the modelm as the following:
[p_0_0, p_0_1, ...... | complete_code | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/human_eval.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/human_eval.py | Apache-2.0 |
def get_min_hash(tokens: List[str]) -> Optional[MinHash]:
"""Compute the MinHash of a code snippet."""
if len(tokens) < MIN_NUM_TOKENS:
return None
min_hash = MinHash(num_perm=NUM_PERM)
for token in set(tokens):
min_hash.update(token.encode())
return min_hash | Compute the MinHash of a code snippet. | get_min_hash | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | Apache-2.0 |
def add(self, code_key: Tuple, min_hash: MinHash) -> None:
"""Add a key to _index (MinHashLSH)
the min_hash is used to query closest matches based on the jaccard_threshold.
The new key is either added to a existing cluster of one close match,
or a new cluster is created. The clusters cre... | Add a key to _index (MinHashLSH)
the min_hash is used to query closest matches based on the jaccard_threshold.
The new key is either added to a existing cluster of one close match,
or a new cluster is created. The clusters created in this way, depend on the order of add.
Args:
... | add | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | Apache-2.0 |
def get_duplicate_clusters(self) -> List[List[Dict]]:
"""Export the duplicate clusters.
For each cluster, the first element is the base element of the cluster.
The base element has an estimation jaccard similarity higher than the threshold with all the other elements.
Returns:
... | Export the duplicate clusters.
For each cluster, the first element is the base element of the cluster.
The base element has an estimation jaccard similarity higher than the threshold with all the other elements.
Returns:
duplicate_clusters (List[List[Dict]]):
List of... | get_duplicate_clusters | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | Apache-2.0 |
def make_duplicate_clusters(dataset_iterator: Type[Dataset], jaccard_threshold: float):
"""Find duplicate clusters in the dataset in two steps:
1. Compute MinHash for each code snippet. MinHash is a tool for fast jaccard similarity estimation.
This step is computed using an asynchronous multiprocessing pool... | Find duplicate clusters in the dataset in two steps:
1. Compute MinHash for each code snippet. MinHash is a tool for fast jaccard similarity estimation.
This step is computed using an asynchronous multiprocessing pool, minhash_iter
2. Find duplicate clusters. The computed MinHash is added sequentially to th... | make_duplicate_clusters | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | Apache-2.0 |
def jaccard_similarity(code1: str, code2: str) -> float:
"""Compute the Jaccard similarity of two code snippets."""
tokens1 = get_tokens(code1)
tokens2 = get_tokens(code2)
return len(tokens1 & tokens2) / len(tokens1 | tokens2) | Compute the Jaccard similarity of two code snippets. | jaccard_similarity | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | Apache-2.0 |
def _find_cluster_extremes_shared(cluster, jaccard_threshold):
"""Find a reduced cluster such that each code in the origin cluster is similar to at least one code in the reduced cluster.
Two codes are similar if their Jaccard similarity is above the threshold.
Args:
cluster (List[dict]):
... | Find a reduced cluster such that each code in the origin cluster is similar to at least one code in the reduced cluster.
Two codes are similar if their Jaccard similarity is above the threshold.
Args:
cluster (List[dict]):
cluster is a list of dict, each dict contains the following keys:
... | _find_cluster_extremes_shared | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | Apache-2.0 |
def find_extremes(cluster_list, dataset, jaccard_threshold):
"""Call the _find_cluster_extremes_shared function in a parallel fashion.
Args:
cluster_list (List[List[Dict]]):
each cluster is a list of dicts with the key base_index,
referring to the index of the base code in the d... | Call the _find_cluster_extremes_shared function in a parallel fashion.
Args:
cluster_list (List[List[Dict]]):
each cluster is a list of dicts with the key base_index,
referring to the index of the base code in the dataset.
dataset (Type[Dataset]):
dataset is used... | find_extremes | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | Apache-2.0 |
def deduplicate_dataset(
dataset: Type[Dataset], jaccard_threshold: float = 0.85
) -> Tuple[Type[Dataset], List[List[Dict]]]:
"""Deduplicate the dataset using minhash and jaccard similarity.
This function first generate duplicate clusters, then each cluster
is reduced to the extremes that are similar to... | Deduplicate the dataset using minhash and jaccard similarity.
This function first generate duplicate clusters, then each cluster
is reduced to the extremes that are similar to the other elements in the cluster.
Codes are called similar if their Jaccard similarity is greater than jaccard_threshold (0.85 defa... | deduplicate_dataset | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/minhash_deduplication.py | Apache-2.0 |
def line_stats(example):
"""Calculates mean and max line length of file."""
line_lengths = [len(line) for line in example["content"].splitlines()]
return {"line_mean": np.mean(line_lengths), "line_max": max(line_lengths)} | Calculates mean and max line length of file. | line_stats | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | Apache-2.0 |
def check_uniques(example, uniques):
"""Check if current hash is still in set of unique hashes and remove if true."""
if example["hash"] in uniques:
uniques.remove(example["hash"])
return True
else:
return False | Check if current hash is still in set of unique hashes and remove if true. | check_uniques | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | Apache-2.0 |
def is_autogenerated(example, scan_width=5):
"""Check if file is autogenerated by looking for keywords in the first few lines of the file."""
keywords = ["auto-generated", "autogenerated", "automatically generated"]
lines = example["content"].splitlines()
for _, line in zip(range(scan_width), lines):
... | Check if file is autogenerated by looking for keywords in the first few lines of the file. | is_autogenerated | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | Apache-2.0 |
def is_config_or_test(example, scan_width=5, coeff=0.05):
"""Check if file is a configuration file or a unit test by :
1- looking for keywords in the first few lines of the file.
2- counting number of occurence of the words 'config' and 'test' with respect to number of lines.
"""
keywords = ["unit ... | Check if file is a configuration file or a unit test by :
1- looking for keywords in the first few lines of the file.
2- counting number of occurence of the words 'config' and 'test' with respect to number of lines.
| is_config_or_test | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | Apache-2.0 |
def has_no_keywords(example):
"""Check if a python file has none of the keywords for: funcion, class, for loop, while loop."""
keywords = ["def ", "class ", "for ", "while "]
lines = example["content"].splitlines()
for line in lines:
for keyword in keywords:
if keyword in line.lower(... | Check if a python file has none of the keywords for: funcion, class, for loop, while loop. | has_no_keywords | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | Apache-2.0 |
def has_few_assignments(example, minimum=4):
"""Check if file uses symbol '=' less than `minimum` times."""
lines = example["content"].splitlines()
counter = 0
for line in lines:
counter += line.lower().count("=")
if counter > minimum:
return {"has_few_assignments": False}
... | Check if file uses symbol '=' less than `minimum` times. | has_few_assignments | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | Apache-2.0 |
def char_token_ratio(example):
"""Compute character/token ratio of the file with tokenizer."""
input_ids = tokenizer(example["content"], truncation=False)["input_ids"]
ratio = len(example["content"]) / len(input_ids)
return {"ratio": ratio} | Compute character/token ratio of the file with tokenizer. | char_token_ratio | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | Apache-2.0 |
def preprocess(example):
"""Chain all preprocessing steps into one function to not fill cache."""
results = dict()
results.update(get_hash(example))
results.update(line_stats(example))
results.update(alpha_stats(example))
results.update(char_token_ratio(example))
results.update(is_autogenera... | Chain all preprocessing steps into one function to not fill cache. | preprocess | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | Apache-2.0 |
def filter(example, uniques, args):
"""Filter dataset with heuristics. Config, test and has_no_keywords files are removed with a given probability."""
if not check_uniques(example, uniques):
return False
elif example["autogenerated"]:
return False
elif example["line_max"] > args.line_max... | Filter dataset with heuristics. Config, test and has_no_keywords files are removed with a given probability. | filter | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/codeparrot/scripts/preprocessing.py | Apache-2.0 |
def entropy(x):
"""Calculate entropy of a pre-softmax logit Tensor"""
exp_x = torch.exp(x)
A = torch.sum(exp_x, dim=1) # sum of exp(x_i)
B = torch.sum(x * exp_x, dim=1) # sum of x_i * exp(x_i)
return torch.log(A) - B / A | Calculate entropy of a pre-softmax logit Tensor | entropy | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/deebert/src/modeling_highway_bert.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/deebert/src/modeling_highway_bert.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
):
r"""
Return:
:obj:`tuple... |
Return:
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs:
last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/deebert/src/modeling_highway_bert.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/deebert/src/modeling_highway_bert.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_layer=-1,
train_highway=False,
):
r"""
labels (:obj:`torch.LongT... |
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the sequence classification/regression loss.
Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
If :obj:`config.num_labels == 1` a regression loss is co... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/deebert/src/modeling_highway_bert.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/deebert/src/modeling_highway_bert.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_layer=-1,
train_highway=False,
):
r"""
labels (:obj:`torch.LongT... |
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the sequence classification/regression loss.
Indices should be in :obj:`[0, ..., config.num_labels - 1]`.
If :obj:`config.num_labels == 1` a regression loss is co... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/deebert/src/modeling_highway_roberta.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/deebert/src/modeling_highway_roberta.py | Apache-2.0 |
def prepare_batch_mlm(self, batch):
"""
Prepare the batch: from the token_ids and the lengths, compute the attention mask and the masked label for MLM.
Input:
------
batch: `Tuple`
token_ids: `torch.tensor(bs, seq_length)` - The token ids for each of the sequ... |
Prepare the batch: from the token_ids and the lengths, compute the attention mask and the masked label for MLM.
Input:
------
batch: `Tuple`
token_ids: `torch.tensor(bs, seq_length)` - The token ids for each of the sequence. It is padded.
lengths: `t... | prepare_batch_mlm | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/distillation/distiller.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/distillation/distiller.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.