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 flatten_beam_dim(tensor):
"""Flattens the first two dimensions of a non-scalar array."""
# ignore scalars (e.g. cache index)
if tensor.ndim == 0:
return tensor
return tensor.reshape((tensor.shape[0] * tensor.shape[1],) + tensor.shape[2:]) | Flattens the first two dimensions of a non-scalar array. | flatten_beam_dim | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_flax_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_flax_utils.py | Apache-2.0 |
def unflatten_beam_dim(tensor, batch_size, num_beams):
"""Unflattens the first, flat batch*beam dimension of a non-scalar array."""
# ignore scalars (e.g. cache index)
if tensor.ndim == 0:
return tensor
return tensor.reshape((batch_size, num_beams) + tenso... | Unflattens the first, flat batch*beam dimension of a non-scalar array. | unflatten_beam_dim | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_flax_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_flax_utils.py | Apache-2.0 |
def gather_beams(nested, beam_indices, batch_size, new_num_beams):
"""
Gathers the beam slices indexed by beam_indices into new beam array.
"""
batch_indices = jnp.reshape(
jnp.arange(batch_size * new_num_beams) // new_num_beams, (batch_size, new_num_beams... |
Gathers the beam slices indexed by beam_indices into new beam array.
| gather_beams | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_flax_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_flax_utils.py | Apache-2.0 |
def beam_search_cond_fn(state):
"""beam search state termination condition fn."""
# 1. is less than max length?
not_max_length_yet = state.cur_len < max_length
# 2. can the new beams still improve?
best_running_score = state.running_scores[:, -1:] / (max_len... | beam search state termination condition fn. | beam_search_cond_fn | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_flax_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_flax_utils.py | Apache-2.0 |
def _set_scores_to_inf_for_banned_tokens(
self, scores: torch.Tensor, banned_tokens: List[List[int]]
) -> torch.Tensor:
"""
Modifies the scores in place by setting the banned token positions to `-inf`. Banned token is expected to be a
list of list of banned tokens to ban in the forma... |
Modifies the scores in place by setting the banned token positions to `-inf`. Banned token is expected to be a
list of list of banned tokens to ban in the format [[batch index, vocabulary position],...
Args:
scores: logits distribution of shape (batch size, vocabulary size)
... | _set_scores_to_inf_for_banned_tokens | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_logits_process.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_logits_process.py | Apache-2.0 |
def _use_cache(self, outputs, use_cache):
"""During generation, decide whether to pass the `past` variable to the next forward pass."""
use_cache = getattr(self.config, "use_cache", False)
if len(outputs) <= 1 or use_cache is False:
return False
if hasattr(self.config, "mem_l... | During generation, decide whether to pass the `past` variable to the next forward pass. | _use_cache | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def generate(
self,
input_ids=None,
max_length=None,
max_new_tokens=None,
min_length=None,
do_sample=None,
early_stopping=None,
num_beams=None,
temperature=None,
top_k=None,
top_p=None,
repetition_penalty=None,
bad_w... |
Generates sequences for models with a language modeling head. The method currently supports greedy decoding,
beam-search decoding, sampling with temperature, sampling with top-k or nucleus sampling.
Adapted in part from [Facebook's XLM beam search
code](https://github.com/facebookresea... | generate | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def _generate_beam_search(
self,
input_ids,
cur_len,
max_length,
min_length,
do_sample,
early_stopping,
temperature,
top_k,
top_p,
repetition_penalty,
no_repeat_ngram_size,
bad_words_ids,
pad_token_id,
... | Generate sequences for each example with beam search. | _generate_beam_search | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def adjust_logits_during_generation(
self, logits, cur_len, max_length, forced_bos_token_id, forced_eos_token_id, **kwargs
):
"""
Implement in subclasses of [`PreTrainedModel`] for custom behavior to adjust the logits in the generate method.
"""
vocab_size = getattr(self.conf... |
Implement in subclasses of [`PreTrainedModel`] for custom behavior to adjust the logits in the generate method.
| adjust_logits_during_generation | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def _generate(
self,
input_ids=None,
max_length=None,
max_new_tokens=None,
min_length=None,
do_sample=None,
early_stopping=None,
num_beams=None,
temperature=None,
top_k=None,
top_p=None,
repetition_penalty=None,
bad_... |
Generates sequences for models with a language modeling head. The method currently supports greedy decoding,
beam-search decoding, sampling with temperature, sampling with top-k or nucleus sampling.
Adapted in part from [Facebook's XLM beam search
code](https://github.com/facebookresea... | _generate | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def _initialize_attention(model_kwargs, num_padding_values, is_encoder_decoder):
"""initializes the appropriate attention mask -- encoder-decoder models use `decoder_attention_mask`"""
if is_encoder_decoder:
# One 1 for decoder_start_token_id, 0s for the currently-unfilled locati... | initializes the appropriate attention mask -- encoder-decoder models use `decoder_attention_mask` | _initialize_attention | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def _update_attention(model_kwargs, new_past_index, is_encoder_decoder):
"""updates the appropriate attention mask -- encoder-decoder models use `decoder_attention_mask`"""
update_start = tf.constant([0, 1], dtype=tf.int32) * new_past_index
if is_encoder_decoder:
deco... | updates the appropriate attention mask -- encoder-decoder models use `decoder_attention_mask` | _update_attention | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def _initialize_past(past, num_padding_values, batch_axis):
"""initialize past with zeros -- the structure depends on `batch_axis`"""
if batch_axis == 0:
padding_values = tf.constant([[0, 0], [0, 0], [0, num_padding_values], [0, 0]], dtype=tf.int32)
new_past = ()
... | initialize past with zeros -- the structure depends on `batch_axis` | _initialize_past | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def _get_logits_warper(
self,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
temperature: Optional[float] = None,
) -> TFLogitsProcessorList:
"""
This class returns a [`TFLogitsProcessorList`] list object that contains all relevant [`TFLogitsWarper`]
... |
This class returns a [`TFLogitsProcessorList`] list object that contains all relevant [`TFLogitsWarper`]
instances used for multinomial sampling.
| _get_logits_warper | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def _get_logits_processor(
self,
repetition_penalty: float,
no_repeat_ngram_size: int,
input_ids_seq_length: int,
bad_words_ids: List[List[int]],
min_length: int,
max_length: int,
eos_token_id: int,
forced_bos_token_id: int,
forced_eos_toke... |
This class returns a [`TFLogitsProcessorList`] list object that contains all relevant [`TFLogitsProcessor`]
instances used to modify the scores of the language model head.
| _get_logits_processor | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def greedy_search(
self,
input_ids: tf.Tensor,
max_length: Optional[int] = None,
pad_token_id: Optional[int] = None,
eos_token_id: Optional[int] = None,
logits_processor: Optional[TFLogitsProcessorList] = None,
output_attentions: Optional[bool] = None,
out... |
Generates sequences for models with a language modeling head using greedy decoding.
Parameters:
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
The sequence used as a prompt for the generation.
logits_processor (`TFLogitsProcessorList`, *option... | greedy_search | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def sample(
self,
input_ids: tf.Tensor,
logits_processor: Optional[TFLogitsProcessorList] = None,
logits_warper: Optional[TFLogitsProcessorList] = None,
max_length: Optional[int] = None,
pad_token_id: Optional[int] = None,
eos_token_id: Optional[int] = None,
... |
Generates sequences for models with a language modeling head using multinomial sampling.
Parameters:
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
The sequence used as a prompt for the generation.
logits_processor (`TFLogitsProcessorList`, *o... | sample | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def beam_search(
self,
input_ids: tf.Tensor,
max_length: Optional[int] = None,
pad_token_id: Optional[int] = None,
eos_token_id: Optional[int] = None,
length_penalty: Optional[float] = None,
early_stopping: Optional[bool] = None,
logits_processor: Optional... |
Generates sequences for models with a language modeling head using beam search with multinomial sampling.
Parameters:
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
The sequence used as a prompt for the generation.
max_length (`int`, *optional... | beam_search | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def gather_beams(nested, beam_indices, batch_axis=0):
"""Gathers the beam slices indexed by beam_indices into new beam array."""
def gather_fn(tensor):
if batch_axis > 0:
# pushes all dimentions before the batch to the end, so we get (batch, beam_id, ...)
... | Gathers the beam slices indexed by beam_indices into new beam array. | gather_beams | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def beam_search_cond_fn(
cur_len,
running_sequences,
running_scores,
sequences,
scores,
is_sent_finished,
model_kwargs,
):
"""
Beam Search termination condition function -- halts the generation loop if an... |
Beam Search termination condition function -- halts the generation loop if any of these conditions becomes
False
| beam_search_cond_fn | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def beam_search_body_fn(
cur_len,
running_sequences,
running_scores,
sequences,
scores,
is_sent_finished,
model_kwargs,
):
"""
Beam Search iterative update function -- each iteration adds a new token and ... |
Beam Search iterative update function -- each iteration adds a new token and updates the best sequences
seen so far
| beam_search_body_fn | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def tf_top_k_top_p_filtering(logits, top_k=0, top_p=1.0, filter_value=-float("Inf"), min_tokens_to_keep=1):
"""
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (batch size, vocabulary size)
top_k (`int`, *optional*, defaul... |
Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (batch size, vocabulary size)
top_k (`int`, *optional*, defaults to 0):
If > 0, only keep the top k tokens with highest probability (top-k filtering)
top_p (... | tf_top_k_top_p_filtering | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def sample_without_replacement(logits, num_samples):
"""
categorical sampling without replacement is currently not implemented the gumbel-max trick will do for now see
https://github.com/tensorflow/tensorflow/issues/9260 for more info
"""
z = -tf.math.log(tf.random.uniform(shape_list(logits), 0, 1))... |
categorical sampling without replacement is currently not implemented the gumbel-max trick will do for now see
https://github.com/tensorflow/tensorflow/issues/9260 for more info
| sample_without_replacement | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_tf_utils.py | Apache-2.0 |
def _prepare_model_inputs(
self,
inputs: Optional[torch.Tensor] = None,
bos_token_id: Optional[int] = None,
model_kwargs: Optional[Dict[str, torch.Tensor]] = None,
) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:
"""
This function extracts the model-s... |
This function extracts the model-specific `inputs` for generation.
| _prepare_model_inputs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def _can_retrieve_inputs_from_name(
self, inputs: Optional[torch.Tensor], name: str, model_kwargs: Dict[str, torch.Tensor]
) -> torch.Tensor:
"""
If `inputs` is None and `name` is in both forward function and keyword arguments, then inputs can be retrieved
from name
"""
... |
If `inputs` is None and `name` is in both forward function and keyword arguments, then inputs can be retrieved
from name
| _can_retrieve_inputs_from_name | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def _get_logits_warper(
self,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
typical_p: Optional[float] = None,
temperature: Optional[float] = None,
num_beams: Optional[int] = None,
renormalize_logits: Optional[bool] = None,
) -> LogitsProcessorLi... |
This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsWarper`] instances
used for multinomial sampling.
| _get_logits_warper | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def _get_logits_processor(
self,
repetition_penalty: float,
no_repeat_ngram_size: int,
encoder_no_repeat_ngram_size: int,
input_ids_seq_length: int,
encoder_input_ids: torch.LongTensor,
bad_words_ids: List[List[int]],
min_length: int,
max_length: i... |
This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsProcessor`]
instances used to modify the scores of the language model head.
| _get_logits_processor | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def compute_transition_beam_scores(
self,
sequences: torch.Tensor,
scores: Tuple[torch.Tensor],
beam_indices: torch.Tensor,
eos_token_id: int = None,
):
"""compute the transition probabilities of sequences given generation
scores and beam indices"""
#... | compute the transition probabilities of sequences given generation
scores and beam indices | compute_transition_beam_scores | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def generate(
self,
inputs: Optional[torch.Tensor] = None,
max_length: Optional[int] = None,
min_length: Optional[int] = None,
do_sample: Optional[bool] = None,
early_stopping: Optional[bool] = None,
num_beams: Optional[int] = None,
temperature: Optional[f... |
Generates sequences of token ids for models with a language modeling head. The method supports the following
generation methods for text-decoder, text-to-text, speech-to-text, and vision-to-text models:
- *greedy decoding* by calling [`~generation_utils.GenerationMixin.greedy_search`] if ... | generate | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def greedy_search(
self,
input_ids: torch.LongTensor,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
max_length: Optional[int] = None,
pad_token_id: Optional[int] = None,
eos_token_id: Optional[int... |
Generates sequences of token ids for models with a language modeling head using **greedy decoding** and can be
used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
Parameters:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
... | greedy_search | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def sample(
self,
input_ids: torch.LongTensor,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
logits_warper: Optional[LogitsProcessorList] = None,
max_length: Optional[int] = None,
pad_token_id: Op... |
Generates sequences of token ids for models with a language modeling head using **multinomial sampling** and
can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
Parameters:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
... | sample | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def beam_search(
self,
input_ids: torch.LongTensor,
beam_scorer: BeamScorer,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
max_length: Optional[int] = None,
pad_token_id: Optional[int] = None,
... |
Generates sequences of token ids for models with a language modeling head using **beam search decoding** and
can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
Parameters:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
... | beam_search | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def beam_sample(
self,
input_ids: torch.LongTensor,
beam_scorer: BeamScorer,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
logits_warper: Optional[LogitsProcessorList] = None,
max_length: Optional... |
Generates sequences of token ids for models with a language modeling head using **beam search multinomial
sampling** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
Parameters:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_... | beam_sample | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def group_beam_search(
self,
input_ids: torch.LongTensor,
beam_scorer: BeamScorer,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
max_length: Optional[int] = None,
pad_token_id: Optional[int] = Non... |
Generates sequences of token ids for models with a language modeling head using **diverse beam search
decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
Parameters:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_leng... | group_beam_search | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def constrained_beam_search(
self,
input_ids: torch.LongTensor,
constrained_beam_scorer: ConstrainedBeamSearchScorer,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
max_length: Optional[int] = None,
... |
Generates sequences of token ids for models with a language modeling head using **constrained beam search
decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
Parameters:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_... | constrained_beam_search | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def _ranking_fast(
context_hidden: torch.FloatTensor,
next_hidden: torch.FloatTensor,
next_top_k_probs: torch.FloatTensor,
alpha: float,
beam_width: int,
) -> torch.FloatTensor:
"""
Reranks the top_k candidates based on a degeneration penalty (cosine similarity with previous tokens), as desc... |
Reranks the top_k candidates based on a degeneration penalty (cosine similarity with previous tokens), as described
in the paper "A Contrastive Framework for Neural Text Generation". Returns the index of the best candidate for each
row in the batch.
| _ranking_fast | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/generation_utils.py | Apache-2.0 |
def __init__(self, dataclass_types: Union[DataClassType, Iterable[DataClassType]], **kwargs):
"""
Args:
dataclass_types:
Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args.
kwargs:
(Optional) Passed t... |
Args:
dataclass_types:
Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args.
kwargs:
(Optional) Passed to `argparse.ArgumentParser()` in the regular way.
| __init__ | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/hf_argparser.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/hf_argparser.py | Apache-2.0 |
def parse_args_into_dataclasses(
self, args=None, return_remaining_strings=False, look_for_args_file=True, args_filename=None
) -> Tuple[DataClass, ...]:
"""
Parse command-line args into instances of the specified dataclass types.
This relies on argparse's `ArgumentParser.parse_know... |
Parse command-line args into instances of the specified dataclass types.
This relies on argparse's `ArgumentParser.parse_known_args`. See the doc at:
docs.python.org/3.7/library/argparse.html#argparse.ArgumentParser.parse_args
Args:
args:
List of strings to... | parse_args_into_dataclasses | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/hf_argparser.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/hf_argparser.py | Apache-2.0 |
def parse_dict(self, args: Dict[str, Any], allow_extra_keys: bool = False) -> Tuple[DataClass, ...]:
"""
Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass
types.
Args:
args (`dict`):
dict containin... |
Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass
types.
Args:
args (`dict`):
dict containing config values
allow_extra_keys (`bool`, *optional*, defaults to `False`):
Defaults... | parse_dict | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/hf_argparser.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/hf_argparser.py | Apache-2.0 |
def parse_json_file(self, json_file: str, allow_extra_keys: bool = False) -> Tuple[DataClass, ...]:
"""
Alternative helper method that does not use `argparse` at all, instead loading a json file and populating the
dataclass types.
Args:
json_file (`str` or `os.PathLike`):
... |
Alternative helper method that does not use `argparse` at all, instead loading a json file and populating the
dataclass types.
Args:
json_file (`str` or `os.PathLike`):
File name of the json file to parse
allow_extra_keys (`bool`, *optional*, defaults to... | parse_json_file | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/hf_argparser.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/hf_argparser.py | Apache-2.0 |
def to_channel_dimension_format(image: np.ndarray, channel_dim: Union[ChannelDimension, str]) -> np.ndarray:
"""
Converts `image` to the channel dimension format specified by `channel_dim`.
Args:
image (`numpy.ndarray`):
The image to have its channel dimension set.
channel_dim (... |
Converts `image` to the channel dimension format specified by `channel_dim`.
Args:
image (`numpy.ndarray`):
The image to have its channel dimension set.
channel_dim (`ChannelDimension`):
The channel dimension format to use.
Returns:
`np.ndarray`: The image ... | to_channel_dimension_format | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_transforms.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_transforms.py | Apache-2.0 |
def rescale(
image: np.ndarray, scale: float, data_format: Optional[ChannelDimension] = None, dtype=np.float32
) -> np.ndarray:
"""
Rescales `image` by `scale`.
Args:
image (`np.ndarray`):
The image to rescale.
scale (`float`):
The scale to use for rescaling the ... |
Rescales `image` by `scale`.
Args:
image (`np.ndarray`):
The image to rescale.
scale (`float`):
The scale to use for rescaling the image.
data_format (`ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it wil... | rescale | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_transforms.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_transforms.py | Apache-2.0 |
def to_pil_image(
image: Union[np.ndarray, PIL.Image.Image, "torch.Tensor", "tf.Tensor", "jnp.Tensor"],
do_rescale: Optional[bool] = None,
) -> PIL.Image.Image:
"""
Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
needed.
Args:
... |
Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
needed.
Args:
image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor` or `tf.Tensor`):
The image to convert to the `PIL.Image` format.
do_rescale (`bool`, *opti... | to_pil_image | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_transforms.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_transforms.py | Apache-2.0 |
def get_resize_output_image_size(
input_image: np.ndarray,
size: Union[int, Tuple[int, int], List[int], Tuple[int]],
default_to_square: bool = True,
max_size: Optional[int] = None,
) -> tuple:
"""
Find the target (height, width) dimension of the output image after resizing given the input image ... |
Find the target (height, width) dimension of the output image after resizing given the input image and the desired
size.
Args:
input_image (`np.ndarray`):
The image to resize.
size (`int` or `Tuple[int, int]` or List[int] or Tuple[int]):
The size to use for resizing... | get_resize_output_image_size | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_transforms.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_transforms.py | Apache-2.0 |
def resize(
image,
size: Tuple[int, int],
resample=PILImageResampling.BILINEAR,
data_format: Optional[ChannelDimension] = None,
return_numpy: bool = True,
) -> np.ndarray:
"""
Resizes `image` to (h, w) specified by `size` using the PIL library.
Args:
image (`PIL.Image.Image` or ... |
Resizes `image` to (h, w) specified by `size` using the PIL library.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to resize.
size (`Tuple[int, int]`):
The size to use for resizing the image.
resample (`int`, *optional*, defaults t... | resize | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_transforms.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_transforms.py | Apache-2.0 |
def normalize(
image: np.ndarray,
mean: Union[float, Iterable[float]],
std: Union[float, Iterable[float]],
data_format: Optional[ChannelDimension] = None,
) -> np.ndarray:
"""
Normalizes `image` using the mean and standard deviation specified by `mean` and `std`.
image = (image - mean) / st... |
Normalizes `image` using the mean and standard deviation specified by `mean` and `std`.
image = (image - mean) / std
Args:
image (`np.ndarray`):
The image to normalize.
mean (`float` or `Iterable[float]`):
The mean to use for normalization.
std (`float` or ... | normalize | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_transforms.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_transforms.py | Apache-2.0 |
def center_crop(
image: np.ndarray,
size: Tuple[int, int],
data_format: Optional[Union[str, ChannelDimension]] = None,
return_numpy: Optional[bool] = None,
) -> np.ndarray:
"""
Crops the `image` to the specified `size` using a center crop. Note that if the image is too small to be cropped to
... |
Crops the `image` to the specified `size` using a center crop. Note that if the image is too small to be cropped to
the size given, it will be padded (so the returned result will always be of size `size`).
Args:
image (`np.ndarray`):
The image to crop.
size (`Tuple[int, int]`):... | center_crop | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_transforms.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_transforms.py | Apache-2.0 |
def infer_channel_dimension_format(image: np.ndarray) -> ChannelDimension:
"""
Infers the channel dimension format of `image`.
Args:
image (`np.ndarray`):
The image to infer the channel dimension of.
Returns:
The channel dimension of the image.
"""
if image.ndim == ... |
Infers the channel dimension format of `image`.
Args:
image (`np.ndarray`):
The image to infer the channel dimension of.
Returns:
The channel dimension of the image.
| infer_channel_dimension_format | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def get_channel_dimension_axis(image: np.ndarray) -> int:
"""
Returns the channel dimension axis of the image.
Args:
image (`np.ndarray`):
The image to get the channel dimension axis of.
Returns:
The channel dimension axis of the image.
"""
channel_dim = infer_chann... |
Returns the channel dimension axis of the image.
Args:
image (`np.ndarray`):
The image to get the channel dimension axis of.
Returns:
The channel dimension axis of the image.
| get_channel_dimension_axis | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:
"""
Returns the (height, width) dimensions of the image.
Args:
image (`np.ndarray`):
The image to get the dimensions of.
channel_dim (`ChannelDimension`, *optional*):
Whic... |
Returns the (height, width) dimensions of the image.
Args:
image (`np.ndarray`):
The image to get the dimensions of.
channel_dim (`ChannelDimension`, *optional*):
Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.
... | get_image_size | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def load_image(image: Union[str, "PIL.Image.Image"]) -> "PIL.Image.Image":
"""
Loads `image` to a PIL Image.
Args:
image (`str` or `PIL.Image.Image`):
The image to convert to the PIL Image format.
Returns:
`PIL.Image.Image`: A PIL Image.
"""
if isinstance(image, str... |
Loads `image` to a PIL Image.
Args:
image (`str` or `PIL.Image.Image`):
The image to convert to the PIL Image format.
Returns:
`PIL.Image.Image`: A PIL Image.
| load_image | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def to_pil_image(self, image, rescale=None):
"""
Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
needed.
Args:
image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):
The image to convert... |
Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
needed.
Args:
image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):
The image to convert to the PIL Image format.
rescale (`bool`, *... | to_pil_image | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def convert_rgb(self, image):
"""
Converts `PIL.Image.Image` to RGB format.
Args:
image (`PIL.Image.Image`):
The image to convert.
"""
self._ensure_format_supported(image)
if not isinstance(image, PIL.Image.Image):
return image
... |
Converts `PIL.Image.Image` to RGB format.
Args:
image (`PIL.Image.Image`):
The image to convert.
| convert_rgb | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def rescale(self, image: np.ndarray, scale: Union[float, int]) -> np.ndarray:
"""
Rescale a numpy image by scale amount
"""
self._ensure_format_supported(image)
return image * scale |
Rescale a numpy image by scale amount
| rescale | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def to_numpy_array(self, image, rescale=None, channel_first=True):
"""
Converts `image` to a numpy array. Optionally rescales it and puts the channel dimension as the first
dimension.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The imag... |
Converts `image` to a numpy array. Optionally rescales it and puts the channel dimension as the first
dimension.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to convert to a NumPy array.
rescale (`bool`, *optional*):
... | to_numpy_array | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def expand_dims(self, image):
"""
Expands 2-dimensional `image` to 3 dimensions.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to expand.
"""
self._ensure_format_supported(image)
# Do nothing if PIL image
... |
Expands 2-dimensional `image` to 3 dimensions.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to expand.
| expand_dims | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def normalize(self, image, mean, std, rescale=False):
"""
Normalizes `image` with `mean` and `std`. Note that this will trigger a conversion of `image` to a NumPy array
if it's a PIL Image.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
Th... |
Normalizes `image` with `mean` and `std`. Note that this will trigger a conversion of `image` to a NumPy array
if it's a PIL Image.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to normalize.
mean (`List[float]` or `np.ndar... | normalize | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def resize(self, image, size, resample=None, default_to_square=True, max_size=None):
"""
Resizes `image`. Enforces conversion of input to PIL.Image.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to resize.
size (`int` or `Tu... |
Resizes `image`. Enforces conversion of input to PIL.Image.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to resize.
size (`int` or `Tuple[int, int]`):
The size to use for resizing the image. If `size` is a sequence... | resize | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def center_crop(self, image, size):
"""
Crops `image` to the given size using a center crop. Note that if the image is too small to be cropped to the
size given, it will be padded (so the returned result has the size asked).
Args:
image (`PIL.Image.Image` or `np.ndarray` or ... |
Crops `image` to the given size using a center crop. Note that if the image is too small to be cropped to the
size given, it will be padded (so the returned result has the size asked).
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape (n_channels, height, wi... | center_crop | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def flip_channel_order(self, image):
"""
Flips the channel order of `image` from RGB to BGR, or vice versa. Note that this will trigger a conversion of
`image` to a NumPy array if it's a PIL Image.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
... |
Flips the channel order of `image` from RGB to BGR, or vice versa. Note that this will trigger a conversion of
`image` to a NumPy array if it's a PIL Image.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image whose color channels to flip. If... | flip_channel_order | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def rotate(self, image, angle, resample=None, expand=0, center=None, translate=None, fillcolor=None):
"""
Returns a rotated copy of `image`. This method returns a copy of `image`, rotated the given number of degrees
counter clockwise around its centre.
Args:
image (`PIL.Imag... |
Returns a rotated copy of `image`. This method returns a copy of `image`, rotated the given number of degrees
counter clockwise around its centre.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to rotate. If `np.ndarray` or `torch.Tenso... | rotate | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/image_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/image_utils.py | Apache-2.0 |
def dynamic_modules_import_trainable(*args, **kwargs):
"""
Wrapper around `tune.with_parameters` to ensure datasets_modules are loaded on each Actor.
Without this, an ImportError will be thrown. See https://github.com/huggingface/transformers/issues/11565.
Assumes that `_objective`, de... |
Wrapper around `tune.with_parameters` to ensure datasets_modules are loaded on each Actor.
Without this, an ImportError will be thrown. See https://github.com/huggingface/transformers/issues/11565.
Assumes that `_objective`, defined above, is a function.
| dynamic_modules_import_trainable | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/integrations.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/integrations.py | Apache-2.0 |
def setup(self, args, state, model, **kwargs):
"""
Setup the optional Weights & Biases (*wandb*) integration.
One can subclass and override this method to customize the setup if needed. Find more information
[here](https://docs.wandb.ai/integrations/huggingface). You can also override t... |
Setup the optional Weights & Biases (*wandb*) integration.
One can subclass and override this method to customize the setup if needed. Find more information
[here](https://docs.wandb.ai/integrations/huggingface). You can also override the following environment
variables:
Envir... | setup | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/integrations.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/integrations.py | Apache-2.0 |
def setup(self, args, state, model):
"""
Setup the optional Comet.ml integration.
Environment:
COMET_MODE (`str`, *optional*):
Whether to create an online, offline experiment or disable Comet logging. Can be "OFFLINE", "ONLINE",
or "DISABLED". Default... |
Setup the optional Comet.ml integration.
Environment:
COMET_MODE (`str`, *optional*):
Whether to create an online, offline experiment or disable Comet logging. Can be "OFFLINE", "ONLINE",
or "DISABLED". Defaults to "ONLINE".
COMET_PROJECT_NAME (`... | setup | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/integrations.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/integrations.py | Apache-2.0 |
def setup(self, args, state, model):
"""
Setup the optional MLflow integration.
Environment:
HF_MLFLOW_LOG_ARTIFACTS (`str`, *optional*):
Whether to use MLflow .log_artifact() facility to log artifacts. This only makes sense if logging to a
remote ser... |
Setup the optional MLflow integration.
Environment:
HF_MLFLOW_LOG_ARTIFACTS (`str`, *optional*):
Whether to use MLflow .log_artifact() facility to log artifacts. This only makes sense if logging to a
remote server, e.g. s3 or GCS. If set to `True` or *1*, wi... | setup | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/integrations.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/integrations.py | Apache-2.0 |
def save_pretrained(self, save_directory_or_file):
"""Save a model card object to the directory or file `save_directory_or_file`."""
if os.path.isdir(save_directory_or_file):
# If we save using the predefined names, we can load using `from_pretrained`
output_model_card_file = os.... | Save a model card object to the directory or file `save_directory_or_file`. | save_pretrained | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modelcard.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modelcard.py | Apache-2.0 |
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
r"""
Instantiate a [`ModelCard`] from a pre-trained model model card.
Parameters:
pretrained_model_name_or_path: either:
- a string, the *model id* of a pretrained model card hosted inside a model re... |
Instantiate a [`ModelCard`] from a pre-trained model model card.
Parameters:
pretrained_model_name_or_path: either:
- a string, the *model id* of a pretrained model card hosted inside a model repo on huggingface.co.
Valid model ids can be located at the r... | from_pretrained | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modelcard.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modelcard.py | Apache-2.0 |
def from_json_file(cls, json_file):
"""Constructs a `ModelCard` from a json file of parameters."""
with open(json_file, "r", encoding="utf-8") as reader:
text = reader.read()
dict_obj = json.loads(text)
return cls(**dict_obj) | Constructs a `ModelCard` from a json file of parameters. | from_json_file | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modelcard.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modelcard.py | Apache-2.0 |
def parse_keras_history(logs):
"""
Parse the `logs` of either a `tf.keras.History` object returned by `model.fit()` or an accumulated logs `dict`
passed to the `PushToHubCallback`. Returns lines and logs compatible with those returned by `parse_log_history`.
"""
if hasattr(logs, "history"):
... |
Parse the `logs` of either a `tf.keras.History` object returned by `model.fit()` or an accumulated logs `dict`
passed to the `PushToHubCallback`. Returns lines and logs compatible with those returned by `parse_log_history`.
| parse_keras_history | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modelcard.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modelcard.py | Apache-2.0 |
def parse_log_history(log_history):
"""
Parse the `log_history` of a Trainer to get the intermediate and final evaluation results.
"""
idx = 0
while idx < len(log_history) and "train_runtime" not in log_history[idx]:
idx += 1
# If there are no training logs
if idx == len(log_history... |
Parse the `log_history` of a Trainer to get the intermediate and final evaluation results.
| parse_log_history | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modelcard.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modelcard.py | Apache-2.0 |
def make_markdown_table(lines):
"""
Create a nice Markdown table from the results in `lines`.
"""
if lines is None or len(lines) == 0:
return ""
col_widths = {key: len(str(key)) for key in lines[0].keys()}
for line in lines:
for key, value in line.items():
if col_widt... |
Create a nice Markdown table from the results in `lines`.
| make_markdown_table | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modelcard.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modelcard.py | Apache-2.0 |
def load_pytorch_checkpoint_in_flax_state_dict(
flax_model, pytorch_checkpoint_path, is_sharded, allow_missing_keys=False
):
"""Load pytorch checkpoints in a flax model"""
try:
import torch # noqa: F401
except ImportError:
logger.error(
"Loading a PyTorch model in Flax, requ... | Load pytorch checkpoints in a flax model | load_pytorch_checkpoint_in_flax_state_dict | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_flax_pytorch_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_flax_pytorch_utils.py | Apache-2.0 |
def rename_key_and_reshape_tensor(
pt_tuple_key: Tuple[str],
pt_tensor: np.ndarray,
random_flax_state_dict: Dict[str, jnp.ndarray],
model_prefix: str,
) -> (Tuple[str], np.ndarray):
"""Rename PT weight names to corresponding Flax weight names and reshape tensor if necessary"""
def is_key_or_pre... | Rename PT weight names to corresponding Flax weight names and reshape tensor if necessary | rename_key_and_reshape_tensor | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_flax_pytorch_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_flax_pytorch_utils.py | Apache-2.0 |
def load_flax_checkpoint_in_pytorch_model(model, flax_checkpoint_path):
"""Load flax checkpoints in a PyTorch model"""
flax_checkpoint_path = os.path.abspath(flax_checkpoint_path)
logger.info(f"Loading Flax weights from {flax_checkpoint_path}")
# import correct flax class
flax_cls = getattr(transfo... | Load flax checkpoints in a PyTorch model | load_flax_checkpoint_in_pytorch_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_flax_pytorch_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_flax_pytorch_utils.py | Apache-2.0 |
def dtype_byte_size(dtype):
"""
Returns the size (in bytes) occupied by one parameter of type `dtype`. Example:
```py
>>> dtype_byte_size(np.float32)
4
```
"""
if dtype == bool:
return 1 / 8
bit_search = re.search(r"[^\d](\d+)$", dtype.name)
if bit_search is None:
... |
Returns the size (in bytes) occupied by one parameter of type `dtype`. Example:
```py
>>> dtype_byte_size(np.float32)
4
```
| dtype_byte_size | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_flax_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_flax_utils.py | Apache-2.0 |
def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any:
"""
Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.
"""
# taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e65... |
Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.
| _cast_floating_to | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_flax_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_flax_utils.py | Apache-2.0 |
def load_flax_sharded_weights(cls, shard_files):
"""
This is the same as [`flax.serialization.from_bytes`]
(https:lax.readthedocs.io/en/latest/_modules/flax/serialization.html#from_bytes) but for a sharded checkpoint.
This load is performed efficiently: each checkpoint shard is loaded o... |
This is the same as [`flax.serialization.from_bytes`]
(https:lax.readthedocs.io/en/latest/_modules/flax/serialization.html#from_bytes) but for a sharded checkpoint.
This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and deleted after being
loaded in t... | load_flax_sharded_weights | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_flax_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_flax_utils.py | Apache-2.0 |
def save_pretrained(
self, save_directory: Union[str, os.PathLike], params=None, push_to_hub=False, max_shard_size="10GB", **kwargs
):
"""
Save a model and its configuration file to a directory, so that it can be re-loaded using the
`[`~FlaxPreTrainedModel.from_pretrained`]` class me... |
Save a model and its configuration file to a directory, so that it can be re-loaded using the
`[`~FlaxPreTrainedModel.from_pretrained`]` class method
Arguments:
save_directory (`str` or `os.PathLike`):
Directory to which to save. Will be created if it doesn't exist.... | save_pretrained | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_flax_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_flax_utils.py | Apache-2.0 |
def register_for_auto_class(cls, auto_class="FlaxAutoModel"):
"""
Register this class with a given auto class. This should only be used for custom models as the ones in the
library are already mapped with an auto class.
<Tip warning={true}>
This API is experimental and may have... |
Register this class with a given auto class. This should only be used for custom models as the ones in the
library are already mapped with an auto class.
<Tip warning={true}>
This API is experimental and may have some slight breaking changes in the next releases.
</Tip>
... | register_for_auto_class | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_flax_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_flax_utils.py | Apache-2.0 |
def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove="", tf_weight_shape=None):
"""
Convert a TF 2.0 model variable name in a pytorch model weight name.
Conventions for TF2.0 scopes -> PyTorch attribute names conversions:
- '$1___$2' is replaced by $2 (can be used to duplic... |
Convert a TF 2.0 model variable name in a pytorch model weight name.
Conventions for TF2.0 scopes -> PyTorch attribute names conversions:
- '$1___$2' is replaced by $2 (can be used to duplicate or remove layers in TF2.0 vs PyTorch)
- '_._' is replaced by a new level separation (can be used to... | convert_tf_weight_name_to_pt_weight_name | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | Apache-2.0 |
def apply_transpose(transpose: TransposeType, weight, match_shape=None, pt_to_tf=True):
"""
Apply a transpose to some weight then tries to reshape the weight to the same shape as a given shape, all in a
framework agnostic way.
"""
if transpose is TransposeType.CONV2D:
# Conv2D weight:
... |
Apply a transpose to some weight then tries to reshape the weight to the same shape as a given shape, all in a
framework agnostic way.
| apply_transpose | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | Apache-2.0 |
def load_pytorch_checkpoint_in_tf2_model(
tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False, output_loading_info=False
):
"""Load pytorch checkpoints in a TF 2.0 model"""
try:
import tensorflow as tf # noqa: F401
import torch # noqa: F401
except ImportError:
... | Load pytorch checkpoints in a TF 2.0 model | load_pytorch_checkpoint_in_tf2_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | Apache-2.0 |
def load_tf2_checkpoint_in_pytorch_model(
pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False, output_loading_info=False
):
"""
Load TF 2.0 HDF5 checkpoint in a PyTorch model We use HDF5 to easily do transfer learning (see
https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660... |
Load TF 2.0 HDF5 checkpoint in a PyTorch model We use HDF5 to easily do transfer learning (see
https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357).
| load_tf2_checkpoint_in_pytorch_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | Apache-2.0 |
def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False, output_loading_info=False):
"""Load TF 2.0 model in a pytorch model"""
weights = tf_model.weights
return load_tf2_weights_in_pytorch_model(
pt_model, weights, allow_missing_keys=allow_missing_keys, output_loading_info... | Load TF 2.0 model in a pytorch model | load_tf2_model_in_pytorch_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | Apache-2.0 |
def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False, output_loading_info=False):
"""Load TF2.0 symbolic weights in a PyTorch model"""
try:
import tensorflow as tf # noqa: F401
import torch # noqa: F401
except ImportError:
logger.error(
"... | Load TF2.0 symbolic weights in a PyTorch model | load_tf2_weights_in_pytorch_model | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_pytorch_utils.py | Apache-2.0 |
def num_parameters(self, only_trainable: bool = False) -> int:
"""
Get the number of (optionally, trainable) parameters in the model.
Args:
only_trainable (`bool`, *optional*, defaults to `False`):
Whether or not to return only the number of trainable parameters
... |
Get the number of (optionally, trainable) parameters in the model.
Args:
only_trainable (`bool`, *optional*, defaults to `False`):
Whether or not to return only the number of trainable parameters
Returns:
`int`: The number of parameters.
| num_parameters | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def keras_serializable(cls):
"""
Decorate a Keras Layer class to support Keras serialization.
This is done by:
1. Adding a `transformers_config` dict to the Keras config dictionary in `get_config` (called by Keras at
serialization time.
2. Wrapping `__init__` to accept that `transformers_co... |
Decorate a Keras Layer class to support Keras serialization.
This is done by:
1. Adding a `transformers_config` dict to the Keras config dictionary in `get_config` (called by Keras at
serialization time.
2. Wrapping `__init__` to accept that `transformers_config` dict (passed by Keras at deser... | keras_serializable | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def booleans_processing(config, **kwargs):
"""
Process the input booleans of each model.
Args:
config ([`PretrainedConfig`]):
The config of the running model.
**kwargs:
The boolean parameters
Returns:
A dictionary with the proper values for each boolean
... |
Process the input booleans of each model.
Args:
config ([`PretrainedConfig`]):
The config of the running model.
**kwargs:
The boolean parameters
Returns:
A dictionary with the proper values for each boolean
| booleans_processing | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def unpack_inputs(func):
"""
Decorator that processes the inputs to a Keras layer, passing them to the layer as keyword arguments. This enables
downstream use of the inputs by their variable name, even if they arrive packed as a dictionary in the first input
(common case in Keras).
Args:
fu... |
Decorator that processes the inputs to a Keras layer, passing them to the layer as keyword arguments. This enables
downstream use of the inputs by their variable name, even if they arrive packed as a dictionary in the first input
(common case in Keras).
Args:
func (`callable`):
The... | unpack_inputs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def input_processing(func, config, **kwargs):
"""
Process the input of each TensorFlow model including the booleans. In case of a list of symbolic inputs, each input
has to be named accordingly to the parameters name, i.e. `input_ids = tf.keras.Input(shape=(128,), dtype='int32',
name="input_ids")` other... |
Process the input of each TensorFlow model including the booleans. In case of a list of symbolic inputs, each input
has to be named accordingly to the parameters name, i.e. `input_ids = tf.keras.Input(shape=(128,), dtype='int32',
name="input_ids")` otherwise the order of the tensors will not be guaranteed ... | input_processing | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def dtype_byte_size(dtype):
"""
Returns the size (in bytes) occupied by one parameter of type `dtype`.
Example:
```py
>>> dtype_byte_size(tf.float32)
4
```
"""
if dtype == tf.bool:
return 1 / 8
bit_search = re.search(r"[^\d](\d+)$", dtype.name)
if bit_search is None... |
Returns the size (in bytes) occupied by one parameter of type `dtype`.
Example:
```py
>>> dtype_byte_size(tf.float32)
4
```
| dtype_byte_size | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def load_tf_sharded_weights(model, shard_files, ignore_mismatched_sizes=False, strict=True):
"""
This is the same as `load_tf_weights` but for a sharded checkpoint. Detect missing and unexpected layers and load
the TF weights from the shard file accordingly to their names and shapes.
This load is perfo... |
This is the same as `load_tf_weights` but for a sharded checkpoint. Detect missing and unexpected layers and load
the TF weights from the shard file accordingly to their names and shapes.
This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and deleted after being
load... | load_tf_sharded_weights | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def load_tf_shard(model, model_layer_map, resolved_archive_file, ignore_mismatched_sizes=False):
"""
Loads a shard from a sharded checkpoint file. Handles the missing keys and unexpected keys.
Args:
model (`tf.keras.models.Model`): Model in which the weights are loaded
model_layer_map (`Dic... |
Loads a shard from a sharded checkpoint file. Handles the missing keys and unexpected keys.
Args:
model (`tf.keras.models.Model`): Model in which the weights are loaded
model_layer_map (`Dict`): A dictionnary mapping the layer name to the index of the layer in the model.
resolved_archi... | load_tf_shard | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def load_tf_weights(model, resolved_archive_file, ignore_mismatched_sizes=False, _prefix=None):
"""
Detect missing and unexpected layers and load the TF weights from the shard file accordingly to their names and
shapes.
Args:
model (`tf.keras.models.Model`):
The model to load the we... |
Detect missing and unexpected layers and load the TF weights from the shard file accordingly to their names and
shapes.
Args:
model (`tf.keras.models.Model`):
The model to load the weights into.
resolved_archive_file (`str`):
The location of the H5 file.
ign... | load_tf_weights | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def init_copy_embeddings(old_embeddings, new_num_tokens):
r"""
This function aims to reduce the embeddings in case new_num_tokens < old_num_tokens or to pad with -1 in case
new_num_tokens > old_num_tokens. A mask is also computed in order to know which weight in the embeddings should be
kept or not. Exa... |
This function aims to reduce the embeddings in case new_num_tokens < old_num_tokens or to pad with -1 in case
new_num_tokens > old_num_tokens. A mask is also computed in order to know which weight in the embeddings should be
kept or not. Example:
- if new_num_tokens=5 and old_num_tokens=4 and old_... | init_copy_embeddings | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def dummy_inputs(self) -> Dict[str, tf.Tensor]:
"""
Dummy inputs to build the network.
Returns:
`Dict[str, tf.Tensor]`: The dummy inputs.
"""
return {
"input_ids": tf.constant(DUMMY_INPUTS),
} |
Dummy inputs to build the network.
Returns:
`Dict[str, tf.Tensor]`: The dummy inputs.
| dummy_inputs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def get_input_embeddings(self) -> tf.keras.layers.Layer:
"""
Returns the model's input embeddings layer.
Returns:
`tf.Variable`: The embeddings layer mapping vocabulary to hidden states.
"""
main_layer = getattr(self, self.base_model_prefix, self)
if main_la... |
Returns the model's input embeddings layer.
Returns:
`tf.Variable`: The embeddings layer mapping vocabulary to hidden states.
| get_input_embeddings | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def load_repo_checkpoint(self, repo_path_or_name):
"""
Loads a saved checkpoint (model weights and optimizer state) from a repo. Returns the current epoch count when
the checkpoint was made.
Args:
repo_path_or_name (`str`):
Can either be a repository name for... |
Loads a saved checkpoint (model weights and optimizer state) from a repo. Returns the current epoch count when
the checkpoint was made.
Args:
repo_path_or_name (`str`):
Can either be a repository name for your {object} in the Hub or a path to a local folder (in whic... | load_repo_checkpoint | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def prepare_tf_dataset(
self,
dataset: "datasets.Dataset", # noqa:F821
batch_size: int = 8,
shuffle: bool = True,
tokenizer: Optional["PreTrainedTokenizerBase"] = None,
collate_fn: Optional[Callable] = None,
collate_fn_args: Optional[Dict[str, Any]] = None,
... |
Wraps a HuggingFace [`~datasets.Dataset`] as a `tf.data.Dataset` with collation and batching. This method is
designed to create a "ready-to-use" dataset that can be passed directly to Keras methods like `fit()` without
further modification. The method will drop columns from the dataset if they ... | prepare_tf_dataset | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
def compile(
self,
optimizer="rmsprop",
loss="passthrough",
metrics=None,
loss_weights=None,
weighted_metrics=None,
run_eagerly=None,
steps_per_execution=None,
**kwargs
):
"""
This is a thin wrapper that sets the model's loss ou... |
This is a thin wrapper that sets the model's loss output head as the loss if the user does not specify a loss
function themselves.
| compile | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/modeling_tf_utils.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.