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 prepare_batch_clm(self, batch):
"""
Prepare the batch: from the token_ids and the lengths, compute the attention mask and the labels for CLM.
Input:
------
batch: `Tuple`
token_ids: `torch.tensor(bs, seq_length)` - The token ids for each of the sequence. ... |
Prepare the batch: from the token_ids and the lengths, compute the attention mask and the labels for CLM.
Input:
------
batch: `Tuple`
token_ids: `torch.tensor(bs, seq_length)` - The token ids for each of the sequence. It is padded.
lengths: `torch.t... | prepare_batch_clm | 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 |
def round_batch(self, x: torch.tensor, lengths: torch.tensor):
"""
For float16 only.
Sub-sample sentences in a batch, and add padding, so that each dimension is a multiple of 8.
Input:
------
x: `torch.tensor(bs, seq_length)` - The token ids.
lengths: `to... |
For float16 only.
Sub-sample sentences in a batch, and add padding, so that each dimension is a multiple of 8.
Input:
------
x: `torch.tensor(bs, seq_length)` - The token ids.
lengths: `torch.tensor(bs, seq_length)` - The lengths of each of the sequence in the b... | round_batch | 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 |
def step(self, input_ids: torch.tensor, attention_mask: torch.tensor, lm_labels: torch.tensor):
"""
One optimization step: forward of student AND teacher, backward on the loss (for gradient accumulation),
and possibly a parameter update (depending on the gradient accumulation).
Input:
... |
One optimization step: forward of student AND teacher, backward on the loss (for gradient accumulation),
and possibly a parameter update (depending on the gradient accumulation).
Input:
------
input_ids: `torch.tensor(bs, seq_length)` - The token ids.
attention_mask: `t... | step | 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 |
def optimize(self, loss):
"""
Normalization on the loss (gradient accumulation or distributed training), followed by
backward pass on the loss, possibly followed by a parameter update (depending on the gradient accumulation).
Also update the metrics for tensorboard.
"""
#... |
Normalization on the loss (gradient accumulation or distributed training), followed by
backward pass on the loss, possibly followed by a parameter update (depending on the gradient accumulation).
Also update the metrics for tensorboard.
| optimize | 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 |
def iter(self):
"""
Update global counts, write to tensorboard and save checkpoint.
"""
self.n_iter += 1
self.n_total_iter += 1
if self.n_total_iter % self.params.log_interval == 0:
self.log_tensorboard()
self.last_log = time.time()
if sel... |
Update global counts, write to tensorboard and save checkpoint.
| iter | 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 |
def log_tensorboard(self):
"""
Log into tensorboard. Only by the master process.
"""
if not self.is_master:
return
for param_name, param in self.student.named_parameters():
self.tensorboard.add_scalar(
tag="parameter_mean/" + param_name, s... |
Log into tensorboard. Only by the master process.
| log_tensorboard | 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 |
def end_epoch(self):
"""
Finally arrived at the end of epoch (full pass on dataset).
Do some tensorboard logging and checkpoint saving.
"""
logger.info(f"{self.n_sequences_epoch} sequences have been trained during this epoch.")
if self.is_master:
self.save_ch... |
Finally arrived at the end of epoch (full pass on dataset).
Do some tensorboard logging and checkpoint saving.
| end_epoch | 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 |
def save_checkpoint(self, checkpoint_name: str = "checkpoint.pth"):
"""
Save the current state. Only by the master process.
"""
if not self.is_master:
return
mdl_to_save = self.student.module if hasattr(self.student, "module") else self.student
mdl_to_save.con... |
Save the current state. Only by the master process.
| save_checkpoint | 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 |
def remove_long_sequences(self):
"""
Sequences that are too long are split by chunk of max_model_input_size.
"""
max_len = self.params.max_model_input_size
indices = self.lengths > max_len
logger.info(f"Splitting {sum(indices)} too long sequences.")
def divide_ch... |
Sequences that are too long are split by chunk of max_model_input_size.
| remove_long_sequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/distillation/lm_seqs_dataset.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/distillation/lm_seqs_dataset.py | Apache-2.0 |
def remove_empty_sequences(self):
"""
Too short sequences are simply removed. This could be tuned.
"""
init_size = len(self)
indices = self.lengths > 11
self.token_ids = self.token_ids[indices]
self.lengths = self.lengths[indices]
new_size = len(self)
... |
Too short sequences are simply removed. This could be tuned.
| remove_empty_sequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/distillation/lm_seqs_dataset.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/distillation/lm_seqs_dataset.py | Apache-2.0 |
def remove_unknown_sequences(self):
"""
Remove sequences with a (too) high level of unknown tokens.
"""
if "unk_token" not in self.params.special_tok_ids:
return
else:
unk_token_id = self.params.special_tok_ids["unk_token"]
init_size = len(self)
... |
Remove sequences with a (too) high level of unknown tokens.
| remove_unknown_sequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/distillation/lm_seqs_dataset.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/distillation/lm_seqs_dataset.py | Apache-2.0 |
def print_statistics(self):
"""
Print some statistics on the corpus. Only the master process.
"""
if not self.params.is_master:
return
logger.info(f"{len(self)} sequences")
# data_len = sum(self.lengths)
# nb_unique_tokens = len(Counter(list(chain(*sel... |
Print some statistics on the corpus. Only the master process.
| print_statistics | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/distillation/lm_seqs_dataset.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/distillation/lm_seqs_dataset.py | Apache-2.0 |
def batch_sequences(self, batch):
"""
Do the padding and transform into torch.tensor.
"""
token_ids = [t[0] for t in batch]
lengths = [t[1] for t in batch]
assert len(token_ids) == len(lengths)
# Max for paddings
max_seq_len_ = max(lengths)
# Pad... |
Do the padding and transform into torch.tensor.
| batch_sequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/distillation/lm_seqs_dataset.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/distillation/lm_seqs_dataset.py | Apache-2.0 |
def sanity_checks(args):
"""
A bunch of args sanity checks to perform even starting...
"""
assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0)
assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0)
if args.ml... |
A bunch of args sanity checks to perform even starting...
| sanity_checks | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/distillation/train.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/distillation/train.py | Apache-2.0 |
def init_gpu_params(params):
"""
Handle single and multi-GPU / multi-node.
"""
if params.n_gpu <= 0:
params.local_rank = 0
params.master_port = -1
params.is_master = True
params.multi_gpu = False
return
assert torch.cuda.is_available()
logger.info("Initi... |
Handle single and multi-GPU / multi-node.
| init_gpu_params | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/distillation/utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/distillation/utils.py | Apache-2.0 |
def forward(self, W_query, W_supports):
"""
Find scores of each token being start and end token for an entity.
Args:
W_query (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of query sequence tokens in the vocabulary.
W_supports (`tor... |
Find scores of each token being start and end token for an entity.
Args:
W_query (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of query sequence tokens in the vocabulary.
W_supports (`torch.LongTensor` of shape `(batch_size, sequence_leng... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/fsner/src/fsner/model.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/fsner/src/fsner/model.py | Apache-2.0 |
def tokenize(self, x):
"""
Wrapper function for tokenizing query and supports
Args:
x (`List[str] or List[List[str]]`):
List of strings for query or list of lists of strings for supports.
Returns:
`transformers.tokenization_utils_base.BatchEncoding... |
Wrapper function for tokenizing query and supports
Args:
x (`List[str] or List[List[str]]`):
List of strings for query or list of lists of strings for supports.
Returns:
`transformers.tokenization_utils_base.BatchEncoding` dict with additional keys and va... | tokenize | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/fsner/src/fsner/tokenizer_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/fsner/src/fsner/tokenizer_utils.py | Apache-2.0 |
def extract_entity_from_scores(self, query, W_query, p_start, p_end, thresh=0.70):
"""
Extracts entities from query and scores given a threshold.
Args:
query (`List[str]`):
List of query strings.
W_query (`torch.LongTensor` of shape `(batch_size, sequence_... |
Extracts entities from query and scores given a threshold.
Args:
query (`List[str]`):
List of query strings.
W_query (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of query sequence tokens in the vocabulary.
p_s... | extract_entity_from_scores | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/fsner/src/fsner/tokenizer_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/fsner/src/fsner/tokenizer_utils.py | Apache-2.0 |
def generate_n_pairs(
context_len=32,
max_steps=10,
size_objective_set=100,
min_len=1026,
trim=True,
data_file="data/tokenized_stories_train_wikitext103.jbl",
igf_data_file="igf_context_pairs.jbl",
):
"""
Collecting *n* pairs for training the secondary learner
Args:
cont... |
Collecting *n* pairs for training the secondary learner
Args:
context_len: The maximum total input sequence length after tokenization. Sequences longer
than this will be truncated, sequences shorter will be padded
max_steps: To calculate training epochs of secondary learner
... | generate_n_pairs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/run_clm_igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/run_clm_igf.py | Apache-2.0 |
def training_secondary_learner(
secondary_learner_train_data,
secondary_learner_max_epochs=15,
secondary_learner_batch_size=128,
eval_freq=100,
igf_model_path="igf_model.pt",
):
"""
Train the secondary learner
Args:
secondary_learner_train_data: Data set with (X,IG(X)) pairs to ... |
Train the secondary learner
Args:
secondary_learner_train_data: Data set with (X,IG(X)) pairs to train secondary learner where IG(X) - measure of informativeness and X- context
secondary_learner_max_epochs: Number of epochs to train secondary learner
secondary_learner_batch_size: Batch... | training_secondary_learner | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/run_clm_igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/run_clm_igf.py | Apache-2.0 |
def finetune(
model,
train_dataset,
test_dataset,
context_len=32,
max_steps=1000,
batch_size=16,
threshold=1.0,
recopy_model=recopy_gpt2,
secondary_learner=None,
eval_interval=10,
finetuned_model_name="gpt2_finetuned.pt",
):
"""
fine-tune with IGF if secondary_learner... |
fine-tune with IGF if secondary_learner is not None, else standard fine-tuning
Args:
model: pre-trained GPT-2 model
train_dataset: Data set to train GPT-2 model
test_dataset: Evaluate GPT-2 model
context_len: The maximum total input sequence length after tokenization. Sequences... | finetune | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/run_clm_igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/run_clm_igf.py | Apache-2.0 |
def set_seed(seed):
"""
For reproducible training
Args:
seed: A seed for reproducible training
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed) |
For reproducible training
Args:
seed: A seed for reproducible training
| set_seed | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def compute_perplexity(model, test_data, context_len):
"""
Computes perplexity of the transformer model on data in test_data
Args:
model: Pre-trained GPT2 model
test_data: Data on which perplexity calculation is required
context_len: The maximum total input sequence length after tok... |
Computes perplexity of the transformer model on data in test_data
Args:
model: Pre-trained GPT2 model
test_data: Data on which perplexity calculation is required
context_len: The maximum total input sequence length after tokenization. Sequences longer
than this wil... | compute_perplexity | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def load_gpt2(model_name="gpt2"):
"""
load original gpt2 and save off for quicker loading
Args:
model_name: GPT-2
Returns:
GPT-2 model
"""
model = GPT2LMHeadModel.from_pretrained(model_name, output_hidden_states=True)
torch.save(model.state_dict(), model_name + "local.pt"... |
load original gpt2 and save off for quicker loading
Args:
model_name: GPT-2
Returns:
GPT-2 model
| load_gpt2 | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def recopy_gpt2(orig_model, device, max_steps):
"""
Reset the model to the original pretrained GPT-2 weights after each iteration
Args:
orig_model: Original pretrained GPT-2 model imported from Transformers library
device: CPU/GPU
max_steps: number of training steps
Returns:
... |
Reset the model to the original pretrained GPT-2 weights after each iteration
Args:
orig_model: Original pretrained GPT-2 model imported from Transformers library
device: CPU/GPU
max_steps: number of training steps
Returns:
Original PreTrained GPT-2 model,
lm_optim... | recopy_gpt2 | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def intermittent_save(contexts, real_perps, past_perps, filename):
"""
save the perplexity differences to filename
Args:
contexts: Example on which the perplexity is calculated
real_perps: Perplexity after back-propagating on the selected context
past_perps: Perplexity of model bef... |
save the perplexity differences to filename
Args:
contexts: Example on which the perplexity is calculated
real_perps: Perplexity after back-propagating on the selected context
past_perps: Perplexity of model before training on the context
filename: File to store perplexity diff... | intermittent_save | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def collect_objective_set(
model,
orig_perp,
context_len,
train_data,
objective_set,
max_steps,
device,
filename="dev.jbl",
recopy_model=recopy_gpt2,
):
"""
Collect individual IGF values from pre-trained transformer model
max_steps samples of training data to train secon... |
Collect individual IGF values from pre-trained transformer model
max_steps samples of training data to train secondary model
Args:
model: Pre-trained GPT2 model
orig_perp: Perplexity of original pretrained GPT-2 model
context_len: The maximum total input sequence length after token... | collect_objective_set | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def generate_datasets(
context_len, file="data/tokenized_stories_train_wikitext103.jbl", number=100, min_len=1026, trim=True
):
"""
Generate objective set and training set
Args:
context_len: The maximum total input sequence length after tokenization. Sequences longer
than this w... |
Generate objective set and training set
Args:
context_len: The maximum total input sequence length after tokenization. Sequences longer
than this will be truncated, sequences shorter will be padded
file: Tokenized data split into training set and objective set
number: s... | generate_datasets | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def train_secondary_learner(
secondary_learner, train_dataset, max_epochs, batch_size, eval_freq=50, igf_model_path="secondary_learner.pt"
):
"""
Train the secondary learner (igf_model)
Args:
secondary_learner: secondary learner
train_dataset: data to train secondary learner
ma... |
Train the secondary learner (igf_model)
Args:
secondary_learner: secondary learner
train_dataset: data to train secondary learner
max_epochs: number of epochs to train secondary learner
batch_size: batch size of training data of secondary learner
eval_freq: secondary mo... | train_secondary_learner | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def __init__(self, model):
"""
We use a simple convolutional network as our secondary learner
Args:
model: Pre-trained GPT2 model
"""
# embeddings are from the pretrained model
super(SecondaryLearner, self).__init__()
self.embeddings = model.transform... |
We use a simple convolutional network as our secondary learner
Args:
model: Pre-trained GPT2 model
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def forward(self, context):
"""
Forward pass through the secondary learner
Args:
context: Context input to the secondary learner
Returns:
tensor after squeeze operation
"""
pooled = torch.max(self.conv(self.embeddings(context).squeeze(1).transpo... |
Forward pass through the secondary learner
Args:
context: Context input to the secondary learner
Returns:
tensor after squeeze operation
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def from_pretrained(cls, state_path, model):
"""
Load the secondary learner
Args:
state_path: Path to save secondary learner
model: Pretrained GPT-2
Returns:
secondary learner
"""
secondary_learner = cls(model) # this calls __init__... |
Load the secondary learner
Args:
state_path: Path to save secondary learner
model: Pretrained GPT-2
Returns:
secondary learner
| from_pretrained | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/information-gain-filtration/igf/igf.py | Apache-2.0 |
def cross_entropy(logits, labels, reduction=None):
"""
Args:
logits: bsz, seqlen, vocab_size
labels: bsz, seqlen
"""
vocab_size = logits.shape[-1]
labels = (labels[..., None] == jnp.arange(vocab_size)[None]).astype("f4")
logits = jax.nn.log_softmax... |
Args:
logits: bsz, seqlen, vocab_size
labels: bsz, seqlen
| cross_entropy | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/jax-projects/big_bird/bigbird_flax.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/jax-projects/big_bird/bigbird_flax.py | Apache-2.0 |
def get_context_and_ans(example, assertion=False):
"""Gives new context after removing <html> & new answer tokens as per new context"""
answer = _get_single_answer(example)
# bytes are of no use
del answer["start_byte"]
del answer["end_byte"]
# handle yes_no answers explicitly
if answer["ca... | Gives new context after removing <html> & new answer tokens as per new context | get_context_and_ans | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/jax-projects/big_bird/prepare_natural_questions.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/jax-projects/big_bird/prepare_natural_questions.py | Apache-2.0 |
def advance_iter_and_group_samples(train_iterator, num_samples, max_seq_length):
"""
The training iterator is advanced so that after groupifying the samples,
`num_samples` of length `max_seq_length` are returned.
"""
num_total_tokens = max_seq_length * num_samples
samples = defaultdict(list)
... |
The training iterator is advanced so that after groupifying the samples,
`num_samples` of length `max_seq_length` are returned.
| advance_iter_and_group_samples | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/jax-projects/dataset-streaming/run_mlm_flax_stream.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/jax-projects/dataset-streaming/run_mlm_flax_stream.py | Apache-2.0 |
def to_dict(self):
"""
Serializes this instance to a Python dictionary. Override the default
:meth:`~transformers.PretrainedConfig.to_dict`.
Returns:
:obj:`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
"""
output ... |
Serializes this instance to a Python dictionary. Override the default
:meth:`~transformers.PretrainedConfig.to_dict`.
Returns:
:obj:`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
| to_dict | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/jax-projects/hybrid_clip/configuration_hybrid_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/jax-projects/hybrid_clip/configuration_hybrid_clip.py | Apache-2.0 |
def get_text_features(
self,
input_ids,
attention_mask=None,
position_ids=None,
token_type_ids=None,
params: dict = None,
dropout_rng: jax.random.PRNGKey = None,
train=False,
):
r"""
Args:
input_ids (:obj:`numpy.ndarray` of ... |
Args:
input_ids (:obj:`numpy.ndarray` of shape :obj:`(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using :class:`~transformers.Pr... | get_text_features | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/jax-projects/hybrid_clip/modeling_hybrid_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/jax-projects/hybrid_clip/modeling_hybrid_clip.py | Apache-2.0 |
def get_image_features(
self, pixel_values, params: dict = None, dropout_rng: jax.random.PRNGKey = None, train=False
):
r"""
Args:
pixel_values (:obj:`numpy.ndarray` of shape :obj:`(batch_size, num_channels, height, width)`):
Pixel values. Padding will be ignored ... |
Args:
pixel_values (:obj:`numpy.ndarray` of shape :obj:`(batch_size, num_channels, height, width)`):
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained
using :class:`~transformers.ImageFeatureExtractionMixin`. See
... | get_image_features | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/jax-projects/hybrid_clip/modeling_hybrid_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/jax-projects/hybrid_clip/modeling_hybrid_clip.py | Apache-2.0 |
def from_text_vision_pretrained(
cls,
text_model_name_or_path: str = None,
vision_model_name_or_path: str = None,
*model_args,
**kwargs,
) -> FlaxPreTrainedModel:
"""
Params:
text_model_name_or_path (:obj: `str`, `optional`):
Inform... |
Params:
text_model_name_or_path (:obj: `str`, `optional`):
Information necessary to initiate the text model. Can be either:
- A string, the `model id` of a pretrained model hosted inside a model repo on huggingface.co.
Valid model ids can b... | from_text_vision_pretrained | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/jax-projects/hybrid_clip/modeling_hybrid_clip.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/jax-projects/hybrid_clip/modeling_hybrid_clip.py | Apache-2.0 |
def pad_list_tensors(
list_tensors,
preds_per_image,
max_detections=None,
return_tensors=None,
padding=None,
pad_value=0,
location=None,
):
"""
location will always be cpu for np tensors
"""
if location is None:
location = "cpu"
assert return_tensors in {"pt", "np... |
location will always be cpu for np tensors
| pad_list_tensors | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def find_top_rpn_proposals(
proposals,
pred_objectness_logits,
images,
image_sizes,
nms_thresh,
pre_nms_topk,
post_nms_topk,
min_box_side_len,
training,
):
"""Args:
proposals (list[Tensor]): (L, N, Hi*Wi*A, 4).
pred_objectness_logits: tensors of length L.
... | Args:
proposals (list[Tensor]): (L, N, Hi*Wi*A, 4).
pred_objectness_logits: tensors of length L.
nms_thresh (float): IoU threshold to use for NMS
pre_nms_topk (int): before nms
post_nms_topk (int): after nms
min_box_side_len (float): minimum proposal box side
trai... | find_top_rpn_proposals | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def subsample_labels(labels, num_samples, positive_fraction, bg_label):
"""
Returns:
pos_idx, neg_idx (Tensor):
1D vector of indices. The total length of both is `num_samples` or fewer.
"""
positive = torch.nonzero((labels != -1) & (labels != bg_label)).squeeze(1)
negative = torc... |
Returns:
pos_idx, neg_idx (Tensor):
1D vector of indices. The total length of both is `num_samples` or fewer.
| subsample_labels | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def __init__(self, weights: Tuple[float, float, float, float], scale_clamp: float = None):
"""
Args:
weights (4-element tuple): Scaling factors that are applied to the
(dx, dy, dw, dh) deltas. In Fast R-CNN, these were originally set
such that the deltas have ... |
Args:
weights (4-element tuple): Scaling factors that are applied to the
(dx, dy, dw, dh) deltas. In Fast R-CNN, these were originally set
such that the deltas have unit variance; now they are treated as
hyperparameters of the system.
scal... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def get_deltas(self, src_boxes, target_boxes):
"""
Get box regression transformation deltas (dx, dy, dw, dh) that can be used
to transform the `src_boxes` into the `target_boxes`. That is, the relation
``target_boxes == self.apply_deltas(deltas, src_boxes)`` is true (unless
any d... |
Get box regression transformation deltas (dx, dy, dw, dh) that can be used
to transform the `src_boxes` into the `target_boxes`. That is, the relation
``target_boxes == self.apply_deltas(deltas, src_boxes)`` is true (unless
any delta is too large and is clamped).
Args:
... | get_deltas | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def apply_deltas(self, deltas, boxes):
"""
Apply transformation `deltas` (dx, dy, dw, dh) to `boxes`.
Args:
deltas (Tensor): transformation deltas of shape (N, k*4), where k >= 1.
deltas[i] represents k potentially different class-specific
box transfor... |
Apply transformation `deltas` (dx, dy, dw, dh) to `boxes`.
Args:
deltas (Tensor): transformation deltas of shape (N, k*4), where k >= 1.
deltas[i] represents k potentially different class-specific
box transformations for the single box boxes[i].
b... | apply_deltas | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def __init__(
self,
thresholds: List[float],
labels: List[int],
allow_low_quality_matches: bool = False,
):
"""
Args:
thresholds (list): a list of thresholds used to stratify predictions
into levels.
labels (list): a list of val... |
Args:
thresholds (list): a list of thresholds used to stratify predictions
into levels.
labels (list): a list of values to label predictions belonging at
each level. A label can be one of {-1, 0, 1} signifying
{ignore, negative class, posi... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def __call__(self, match_quality_matrix):
"""
Args:
match_quality_matrix (Tensor[float]): an MxN tensor, containing the pairwise quality between M ground-truth elements and N predicted
elements. All elements must be >= 0 (due to the us of `torch.nonzero` for selecting indices... |
Args:
match_quality_matrix (Tensor[float]): an MxN tensor, containing the pairwise quality between M ground-truth elements and N predicted
elements. All elements must be >= 0 (due to the us of `torch.nonzero` for selecting indices in :meth:`set_low_quality_matches_`).
Return... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def set_low_quality_matches_(self, match_labels, match_quality_matrix):
"""
Produce additional matches for predictions that have only low-quality matches.
Specifically, for each ground-truth G find the set of predictions that have
maximum overlap with it (including ties); for each predic... |
Produce additional matches for predictions that have only low-quality matches.
Specifically, for each ground-truth G find the set of predictions that have
maximum overlap with it (including ties); for each prediction in that set, if
it is unmatched, then match it to the ground-truth G.
... | set_low_quality_matches_ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def __init__(
self,
box2box_transform,
anchor_matcher,
batch_size_per_image,
positive_fraction,
images,
pred_objectness_logits,
pred_anchor_deltas,
anchors,
boundary_threshold=0,
gt_boxes=None,
smooth_l1_beta=0.0,
):
... |
Args:
box2box_transform (Box2BoxTransform): :class:`Box2BoxTransform` instance for anchor-proposal transformations.
anchor_matcher (Matcher): :class:`Matcher` instance for matching anchors to ground-truth boxes; used to determine training labels.
batch_size_per_image (int): ... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def __init__(self, stem, stages, num_classes=None, out_features=None):
"""
Args:
stem (nn.Module): a stem module
stages (list[list[ResNetBlock]]): several (typically 4) stages, each contains multiple :class:`ResNetBlockBase`.
num_classes (None or int): if None, will n... |
Args:
stem (nn.Module): a stem module
stages (list[list[ResNetBlock]]): several (typically 4) stages, each contains multiple :class:`ResNetBlockBase`.
num_classes (None or int): if None, will not perform classification.
out_features (list[str]): name of the layer... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def make_stage(
block_class,
num_blocks,
first_stride=None,
*,
in_channels,
out_channels,
**kwargs,
):
"""
Usually, layers that produce the same feature map spatial size
are defined as one "stage".
Under such definition, stride_... |
Usually, layers that produce the same feature map spatial size
are defined as one "stage".
Under such definition, stride_per_block[1:] should all be 1.
| make_stage | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def forward(self, feature_maps, boxes):
"""
Args:
feature_maps: List[torch.Tensor(N,C,W,H)]
box_lists: list[torch.Tensor])
Returns:
A tensor of shape(N*B, Channels, output_size, output_size)
"""
x = [v for v in feature_maps.values()]
nu... |
Args:
feature_maps: List[torch.Tensor(N,C,W,H)]
box_lists: list[torch.Tensor])
Returns:
A tensor of shape(N*B, Channels, output_size, output_size)
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def generate_cell_anchors(self, sizes=(32, 64, 128, 256, 512), aspect_ratios=(0.5, 1, 2)):
"""
anchors are continuous geometric rectangles
centered on one feature map point sample.
We can later build the set of anchors
for the entire feature map by tiling these tensors
""... |
anchors are continuous geometric rectangles
centered on one feature map point sample.
We can later build the set of anchors
for the entire feature map by tiling these tensors
| generate_cell_anchors | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def forward(self, features):
"""
Args:
features List[torch.Tensor]: list of feature maps on which to generate anchors.
Returns:
torch.Tensor: a list of #image elements.
"""
num_images = features[0].size(0)
grid_sizes = [feature_map.shape[-2:] for f... |
Args:
features List[torch.Tensor]: list of feature maps on which to generate anchors.
Returns:
torch.Tensor: a list of #image elements.
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def forward(self, features):
"""
Args:
features (list[Tensor]): list of feature maps
"""
pred_objectness_logits = []
pred_anchor_deltas = []
for x in features:
t = nn.functional.relu(self.conv(x))
pred_objectness_logits.append(self.obje... |
Args:
features (list[Tensor]): list of feature maps
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def forward(self, images, image_shapes, features, gt_boxes=None):
"""
Args:
images (torch.Tensor): input images of length `N`
features (dict[str: Tensor])
gt_instances
"""
# features is dict, key = block level, v = feature_map
features = [featu... |
Args:
images (torch.Tensor): input images of length `N`
features (dict[str: Tensor])
gt_instances
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def __init__(
self,
input_size,
num_classes,
cls_agnostic_bbox_reg,
box_dim=4,
use_attr=False,
num_attrs=-1,
):
"""
Args:
input_size (int): channels, or (channels, height, width)
num_classes (int)
cls_agnosti... |
Args:
input_size (int): channels, or (channels, height, width)
num_classes (int)
cls_agnostic_bbox_reg (bool)
box_dim (int)
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def forward(
self,
images,
image_shapes,
gt_boxes=None,
proposals=None,
scales_yx=None,
**kwargs,
):
"""
kwargs:
max_detections (int), return_tensors {"np", "pt", None}, padding {None,
"max_detections"}, pad_value (int),... |
kwargs:
max_detections (int), return_tensors {"np", "pt", None}, padding {None,
"max_detections"}, pad_value (int), location = {"cuda", "cpu"}
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/modeling_frcnn.py | Apache-2.0 |
def __init__(self, short_edge_length, max_size=sys.maxsize):
"""
Args:
short_edge_length (list[min, max])
max_size (int): maximum allowed longest edge length.
"""
self.interp_method = "bilinear"
self.max_size = max_size
self.short_edge_length = sho... |
Args:
short_edge_length (list[min, max])
max_size (int): maximum allowed longest edge length.
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/processing_image.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/processing_image.py | Apache-2.0 |
def __init__(
self,
img,
scale=1.2,
edgecolor="g",
alpha=0.5,
linestyle="-",
saveas="test_out.jpg",
rgb=True,
pynb=False,
id2obj=None,
id2attr=None,
pad=0.7,
):
"""
img: an RGB image of shape (H, W, 3).
... |
img: an RGB image of shape (H, W, 3).
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/lxmert/visualizing_image.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/lxmert/visualizing_image.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,
threshold=None,
):
r"""
thresho... |
threshold (:obj:`float`):
Threshold value (see :class:`~emmental.MaskedLinear`).
Return:
:obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~emmental.MaskedBertConfig`) and inputs:
last_hidden_state (:obj:`torch.Float... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modeling_bert_masked.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modeling_bert_masked.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,
threshold=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_s... |
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/movement-pruning/emmental/modeling_bert_masked.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modeling_bert_masked.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,
threshold=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_s... |
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the multiple choice classification loss.
Indices should be in ``[0, ..., num_choices]`` where `num_choices` is the size of the second dimension
of the input tenso... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modeling_bert_masked.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modeling_bert_masked.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,
threshold=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_s... |
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Labels for computing the token classification loss.
Indices should be in ``[0, ..., config.num_labels - 1]``.
threshold (:obj:`float`):
Threshold value (se... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modeling_bert_masked.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modeling_bert_masked.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,
start_positions=None,
end_positions=None,
threshold=None,
):
r"""
start_positions (:... |
start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`).
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modeling_bert_masked.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modeling_bert_masked.py | Apache-2.0 |
def forward(ctx, inputs: torch.tensor, threshold: float, sigmoid: bool):
"""
Args:
inputs (`torch.FloatTensor`)
The input matrix from which the binarizer computes the binary mask.
threshold (`float`)
The threshold value (in R).
sigmoid ... |
Args:
inputs (`torch.FloatTensor`)
The input matrix from which the binarizer computes the binary mask.
threshold (`float`)
The threshold value (in R).
sigmoid (`bool`)
If set to ``True``, we apply the sigmoid function to the `i... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modules/binarizer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modules/binarizer.py | Apache-2.0 |
def forward(ctx, inputs: torch.tensor, threshold: float):
"""
Args:
inputs (`torch.FloatTensor`)
The input matrix from which the binarizer computes the binary mask.
threshold (`float`)
The percentage of weights to keep (the rest is pruned).
... |
Args:
inputs (`torch.FloatTensor`)
The input matrix from which the binarizer computes the binary mask.
threshold (`float`)
The percentage of weights to keep (the rest is pruned).
`threshold` is a float between 0 and 1.
Returns:
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modules/binarizer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modules/binarizer.py | Apache-2.0 |
def apply(inputs: torch.tensor, threshold: float):
"""
Args:
inputs (`torch.FloatTensor`)
The input matrix from which the binarizer computes the binary mask.
This input marix is typically the weight matrix.
threshold (`float`)
The p... |
Args:
inputs (`torch.FloatTensor`)
The input matrix from which the binarizer computes the binary mask.
This input marix is typically the weight matrix.
threshold (`float`)
The percentage of weights to keep (the rest is pruned).
... | apply | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modules/binarizer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modules/binarizer.py | Apache-2.0 |
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = True,
mask_init: str = "constant",
mask_scale: float = 0.0,
pruning_method: str = "topK",
):
"""
Args:
in_features (`int`)
Size of each input samp... |
Args:
in_features (`int`)
Size of each input sample
out_features (`int`)
Size of each output sample
bias (`bool`)
If set to ``False``, the layer will not learn an additive bias.
Default: ``True``
mas... | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modules/masked_nn.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/movement-pruning/emmental/modules/masked_nn.py | Apache-2.0 |
def _convert_past_list_to_tuple(past_key_values):
"""
In Bart model, the type of past_key_values is tuple(tuple(torch.FloatTensor)) which is not
TorchScript-compatible. To support this, we have to convert it during the export process.
This function will convert past values from a list to tuple(tuple(tor... |
In Bart model, the type of past_key_values is tuple(tuple(torch.FloatTensor)) which is not
TorchScript-compatible. To support this, we have to convert it during the export process.
This function will convert past values from a list to tuple(tuple(torch.FloatTensor)) for
the inner decoder.
Accordin... | _convert_past_list_to_tuple | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/onnx/summarization/bart_onnx/generation_onnx.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/onnx/summarization/bart_onnx/generation_onnx.py | Apache-2.0 |
def _force_token_id_to_be_generated(scores, token_id: int):
"""force one of token_ids to be generated by setting prob of all other tokens to 0 (logprob=-float("inf"))"""
mask = torch.full_like(scores, 1, dtype=torch.bool)
mask[:, token_id] = False
return scores.masked_fill(mask, -float("... | force one of token_ids to be generated by setting prob of all other tokens to 0 (logprob=-float("inf")) | _force_token_id_to_be_generated | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/onnx/summarization/bart_onnx/generation_onnx.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/onnx/summarization/bart_onnx/generation_onnx.py | Apache-2.0 |
def remove_dup_initializers(onnx_file_path):
"""
Removes duplicate initializers from the model to reduce its size.
Writes a new file in the same directory as onnx_file_path and returns the path to that file.
"""
model_file_folder = os.path.dirname(onnx_file_path)
model_file_name = os.path.basen... |
Removes duplicate initializers from the model to reduce its size.
Writes a new file in the same directory as onnx_file_path and returns the path to that file.
| remove_dup_initializers | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/onnx/summarization/bart_onnx/reduce_onnx_size.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/onnx/summarization/bart_onnx/reduce_onnx_size.py | Apache-2.0 |
def __call__(self, x):
"""
Applies layer normalization on the input. It normalizes the activations of the layer for each given example in
a batch independently, rather than across a batch like Batch Normalization. i.e. applies a transformation that
maintains the mean activation within ea... |
Applies layer normalization on the input. It normalizes the activations of the layer for each given example in
a batch independently, rather than across a batch like Batch Normalization. i.e. applies a transformation that
maintains the mean activation within each example close to 0 and the acti... | __call__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/performer/modeling_flax_performer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/performer/modeling_flax_performer.py | Apache-2.0 |
def nonnegative_softmax_kernel_feature_creator(
data, projection_matrix, attention_dims_t, batch_dims_t, precision, is_query, normalize_data=True, eps=0.0001
):
"""
Constructs nonnegative kernel features for fast softmax attention
Args:
data: input for which features are computes
projection... |
Constructs nonnegative kernel features for fast softmax attention
Args:
data: input for which features are computes
projection_matrix: random matrix used to compute features
attention_dims_t: tuple of attention dimensions
batch_dims_t: tuple of batch dimensions
precision: precisi... | nonnegative_softmax_kernel_feature_creator | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/performer/modeling_flax_performer_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/performer/modeling_flax_performer_utils.py | Apache-2.0 |
def sincos_softmax_kernel_feature_creator(
data, projection_matrix, attention_dims_t, batch_dims_t, precision, normalize_data=True
):
"""
Constructs kernel sin-cos features for fast softmax attention
Args:
data: input for which features are computes
projection_matrix: random matrix used to ... |
Constructs kernel sin-cos features for fast softmax attention
Args:
data: input for which features are computes
projection_matrix: random matrix used to compute features
attention_dims_t: tuple of attention dimensions
batch_dims_t: tuple of batch dimensions
precision: precision p... | sincos_softmax_kernel_feature_creator | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/performer/modeling_flax_performer_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/performer/modeling_flax_performer_utils.py | Apache-2.0 |
def generalized_kernel_feature_creator(
data, projection_matrix, batch_dims_t, precision, kernel_fn, kernel_epsilon, normalize_data
):
"""
Constructs kernel features for fast generalized attention
Args:
data: input for which features are computes
projection_matrix: matrix used to compute fe... |
Constructs kernel features for fast generalized attention
Args:
data: input for which features are computes
projection_matrix: matrix used to compute features
batch_dims_t: tuple of batch dimensions
precision: precision parameter
kernel_fn: kernel function used
kernel_epsil... | generalized_kernel_feature_creator | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/performer/modeling_flax_performer_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/performer/modeling_flax_performer_utils.py | Apache-2.0 |
def create_learning_rate_scheduler(
factors="constant * linear_warmup * rsqrt_decay",
base_learning_rate=0.5,
warmup_steps=1000,
decay_factor=0.5,
steps_per_decay=20000,
steps_per_cycle=100000,
):
"""Creates learning rate schedule.
Interprets factors in the factors string which can consi... | Creates learning rate schedule.
Interprets factors in the factors string which can consist of:
* constant: interpreted as the constant value,
* linear_warmup: interpreted as linear warmup until warmup_steps,
* rsqrt_decay: divide by square root of max(step, warmup_steps)
* rsqrt_normalized_decay: di... | create_learning_rate_scheduler | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/performer/run_mlm_performer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/performer/run_mlm_performer.py | Apache-2.0 |
def accuracy(logits, targets, weights=None):
"""Compute weighted accuracy for log probs and targets.
Args:
logits: [batch, length, num_classes] float array.
targets: categorical targets [batch, length] int array.
weights: None or array of shape [batch, length]
Returns:
Tuple of scalar l... | Compute weighted accuracy for log probs and targets.
Args:
logits: [batch, length, num_classes] float array.
targets: categorical targets [batch, length] int array.
weights: None or array of shape [batch, length]
Returns:
Tuple of scalar loss and batch normalizing factor.
| accuracy | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/performer/run_mlm_performer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/performer/run_mlm_performer.py | Apache-2.0 |
def cross_entropy(logits, targets, weights=None, label_smoothing=0.0):
"""Compute cross entropy and entropy for log probs and targets.
Args:
logits: [batch, length, num_classes] float array.
targets: categorical targets [batch, length] int array.
weights: None or array of shape [batch, length]
... | Compute cross entropy and entropy for log probs and targets.
Args:
logits: [batch, length, num_classes] float array.
targets: categorical targets [batch, length] int array.
weights: None or array of shape [batch, length]
label_smoothing: label smoothing constant, used to determine the on and off... | cross_entropy | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/performer/run_mlm_performer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/performer/run_mlm_performer.py | Apache-2.0 |
def top_k_filter(logits, k, probs=False):
"""
Masks everything but the k top entries as -infinity (1e10).
Used to mask logits such that e^-infinity -> 0 won't contribute to the
sum of the denominator.
"""
if k == 0:
return logits
else:
values = torch.topk(logits, k)[0]
... |
Masks everything but the k top entries as -infinity (1e10).
Used to mask logits such that e^-infinity -> 0 won't contribute to the
sum of the denominator.
| top_k_filter | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/pplm/run_pplm.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/pplm/run_pplm.py | Apache-2.0 |
def __init__(self, X, y):
"""Reads source and target sequences from txt files."""
self.X = X
self.y = y | Reads source and target sequences from txt files. | __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/pplm/run_pplm_discrim_train.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/pplm/run_pplm_discrim_train.py | Apache-2.0 |
def __getitem__(self, index):
"""Returns one data pair (source and target)."""
data = {}
data["X"] = self.X[index]
data["y"] = self.y[index]
return data | Returns one data pair (source and target). | __getitem__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/pplm/run_pplm_discrim_train.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/pplm/run_pplm_discrim_train.py | Apache-2.0 |
def add_arguments(parser):
"""Add arguments to parser for functions defined in quant_trainer."""
group = parser.add_argument_group("quant_trainer arguments")
group.add_argument("--wprec", type=int, default=8, help="weight precision")
group.add_argument("--aprec", type=int, default=8, help="activation p... | Add arguments to parser for functions defined in quant_trainer. | add_arguments | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def set_default_quantizers(args):
"""Set default quantizers before creating the model."""
if args.calibrator == "max":
calib_method = "max"
elif args.calibrator == "percentile":
if args.percentile is None:
raise ValueError("Specify --percentile when using percentile calibrator")... | Set default quantizers before creating the model. | set_default_quantizers | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def configure_model(model, args, calib=False, eval=False):
"""Function called before the training loop."""
logger.info("Configuring Model for Quantization")
logger.info(f"using quantization package {pytorch_quantization.__file__}")
if not calib:
if args.quant_disable_embeddings:
se... | Function called before the training loop. | configure_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def enable_calibration(model):
"""Enable calibration of all *_input_quantizer modules in model."""
logger.info("Enabling Calibration")
for name, module in model.named_modules():
if name.endswith("_quantizer"):
if module._calibrator is not None:
module.disable_quant()
... | Enable calibration of all *_input_quantizer modules in model. | enable_calibration | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def finish_calibration(model, args):
"""Disable calibration and load amax for all "*_input_quantizer modules in model."""
logger.info("Loading calibrated amax")
for name, module in model.named_modules():
if name.endswith("_quantizer"):
if module._calibrator is not None:
... | Disable calibration and load amax for all "*_input_quantizer modules in model. | finish_calibration | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def fuse_qkv(model, args):
"""Adjust quantization ranges to match an implementation where the QKV projections are implemented with a single GEMM.
Force the weight and output scale factors to match by taking the max of (Q,K,V).
"""
def fuse3(qq, qk, qv):
for mod in [qq, qk, qv]:
if n... | Adjust quantization ranges to match an implementation where the QKV projections are implemented with a single GEMM.
Force the weight and output scale factors to match by taking the max of (Q,K,V).
| fuse_qkv | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def clip_gelu(model, maxval):
"""Clip activations generated by GELU to maxval when quantized.
Implemented by adjusting the amax of the following input_quantizer.
"""
for name, mod in model.named_modules():
if name.endswith(".output.dense") and not name.endswith("attention.output.dense"):
... | Clip activations generated by GELU to maxval when quantized.
Implemented by adjusting the amax of the following input_quantizer.
| clip_gelu | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def expand_amax(model):
"""Expand per-tensor amax to be per channel, where each channel is assigned the per-tensor amax."""
for name, mod in model.named_modules():
if hasattr(mod, "_weight_quantizer") and mod._weight_quantizer.axis is not None:
k = mod.weight.shape[0]
amax = mod... | Expand per-tensor amax to be per channel, where each channel is assigned the per-tensor amax. | expand_amax | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def recalibrate_weights(model):
"""Performs max calibration on the weights and updates amax."""
for name, mod in model.named_modules():
if hasattr(mod, "_weight_quantizer"):
if not hasattr(mod.weight_quantizer, "_amax"):
print("RECALIB: {name:{name_width}} WARNING: NO AMAX B... | Performs max calibration on the weights and updates amax. | recalibrate_weights | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def print_quant_summary(model):
"""Print summary of all quantizer modules in the model."""
count = 0
for name, mod in model.named_modules():
if isinstance(mod, pytorch_quantization.nn.TensorQuantizer):
print(f"{name:80} {mod}")
count += 1
print(f"{count} TensorQuantizers... | Print summary of all quantizer modules in the model. | print_quant_summary | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def set_quantizer_by_name(model, names, **kwargs):
"""Set quantizer attributes for layers where name contains a substring in names."""
for name, mod in model.named_modules():
if hasattr(mod, "_input_quantizer") or hasattr(mod, "_weight_quantizer"):
for n in names:
if re.sear... | Set quantizer attributes for layers where name contains a substring in names. | set_quantizer_by_name | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/quant_trainer.py | Apache-2.0 |
def get_calib_dataloader(self, calib_dataset=None):
"""
Returns the calibration dataloader :class:`~torch.utils.data.DataLoader`.
Args:
calib_dataset (:obj:`torch.utils.data.Dataset`, `optional`)
"""
if calib_dataset is None and self.calib_dataset is None:
... |
Returns the calibration dataloader :class:`~torch.utils.data.DataLoader`.
Args:
calib_dataset (:obj:`torch.utils.data.Dataset`, `optional`)
| get_calib_dataloader | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/trainer_quant_qa.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/quantization-qdqbert/trainer_quant_qa.py | Apache-2.0 |
def get_checkpoint_callback(output_dir, metric):
"""Saves the best model by validation EM score."""
if metric == "rouge2":
exp = "{val_avg_rouge2:.4f}-{step_count}"
elif metric == "bleu":
exp = "{val_avg_bleu:.4f}-{step_count}"
elif metric == "em":
exp = "{val_avg_em:.4f}-{step_c... | Saves the best model by validation EM score. | get_checkpoint_callback | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/rag/callbacks_rag.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/rag/callbacks_rag.py | Apache-2.0 |
def init_retrieval(self, distributed_port: int):
"""
Retriever initialization function, needs to be called from the training process. The function sets some common parameters
and environment variables. On top of that, (only) the main process in the process group loads the index into memory.
... |
Retriever initialization function, needs to be called from the training process. The function sets some common parameters
and environment variables. On top of that, (only) the main process in the process group loads the index into memory.
Args:
distributed_port (:obj:`int`):
... | init_retrieval | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/rag/distributed_pytorch_retriever.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/rag/distributed_pytorch_retriever.py | Apache-2.0 |
def retrieve(self, question_hidden_states: np.ndarray, n_docs: int) -> Tuple[np.ndarray, List[dict]]:
"""
Retrieves documents for specified ``question_hidden_states``. The main process, which has the access to the index stored in memory, gathers queries
from all the processes in the main trainin... |
Retrieves documents for specified ``question_hidden_states``. The main process, which has the access to the index stored in memory, gathers queries
from all the processes in the main training process group, performs the retrieval and scatters back the results.
Args:
question_hidden... | retrieve | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/rag/distributed_pytorch_retriever.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/rag/distributed_pytorch_retriever.py | Apache-2.0 |
def init_retrieval(self):
"""
Retriever initialization function, needs to be called from the
training process. This function triggers retrieval initialization
for all retrieval actors if using distributed setting, or loads
index into current process if training is not distributed... |
Retriever initialization function, needs to be called from the
training process. This function triggers retrieval initialization
for all retrieval actors if using distributed setting, or loads
index into current process if training is not distributed.
| init_retrieval | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/rag/distributed_ray_retriever.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/rag/distributed_ray_retriever.py | Apache-2.0 |
def retrieve(self, question_hidden_states, n_docs):
"""
Retrieves documents for specified ``question_hidden_states``. If
running training with multiple workers, a random retrieval actor is
selected to perform the index lookup and return the result.
Args:
question_hid... |
Retrieves documents for specified ``question_hidden_states``. If
running training with multiple workers, a random retrieval actor is
selected to perform the index lookup and return the result.
Args:
question_hidden_states (:obj:`np.ndarray` of shape :obj:`(batch_size, vecto... | retrieve | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/rag/distributed_ray_retriever.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/rag/distributed_ray_retriever.py | Apache-2.0 |
def require_distributed_retrieval(test_case):
"""
Decorator marking a test that requires a set of dependencies necessary for pefrorm retrieval with
:class:`~transformers.RagRetriever`.
These tests are skipped when respective libraries are not installed.
"""
if not (is_datasets_available() and ... |
Decorator marking a test that requires a set of dependencies necessary for pefrorm retrieval with
:class:`~transformers.RagRetriever`.
These tests are skipped when respective libraries are not installed.
| require_distributed_retrieval | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/examples/research_projects/rag/test_distributed_retriever.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/examples/research_projects/rag/test_distributed_retriever.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.