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 _score_rejection_sampling(self, input_seq: torch.LongTensor, scores: torch.FloatTensor) -> torch.LongTensor: """ Generate greenlist based on current candidate next token. Reject and move on if necessary. Runs for a fixed number of steps only for efficiency, since the methods is not batched. ...
Generate greenlist based on current candidate next token. Reject and move on if necessary. Runs for a fixed number of steps only for efficiency, since the methods is not batched.
_score_rejection_sampling
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0
def __init__( self, batch_size: int, ngram_len: int, context_history_size: int, device: torch.device, ): """Initializes the state. Args: batch_size (`int`): Batch size. ngram_len (`int`): Ngram length. context_history_size ...
Initializes the state. Args: batch_size (`int`): Batch size. ngram_len (`int`): Ngram length. context_history_size (`int`): Size of the tensor to keep track of seen contexts. device (`int`): Device to use.
__init__
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0
def update_scores(self, scores: torch.FloatTensor, g_values: torch.FloatTensor) -> torch.FloatTensor: """Updates scores using the g values. We assume that the scores are in the log space. Args: scores (`torch.FloatTensor`): Scores (batch_size, vocab_size). g_values (`tor...
Updates scores using the g values. We assume that the scores are in the log space. Args: scores (`torch.FloatTensor`): Scores (batch_size, vocab_size). g_values (`torch.FloatTensor`): G values (batch_size, vocab_size, depth). Returns: Updated scores (batch_s...
update_scores
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0
def accumulate_hash( self, current_hash: torch.LongTensor, data: torch.LongTensor, multiplier: int = 6364136223846793005, increment: int = 1, ) -> torch.LongTensor: """ Accumulate hash of data on current hash. Method uses adapted linear congruential g...
Accumulate hash of data on current hash. Method uses adapted linear congruential generator with newlib/musl parameters. This function has following property - f(x, data[T]) = f(f(x, data[:T - 1]), data[T]) This function expects current_hash.shape and data.shape[:-1] to ...
accumulate_hash
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0
def compute_ngram_keys(self, ngrams: torch.LongTensor) -> torch.LongTensor: """Computes random keys for each ngram and depth. Args: ngrams (`torch.LongTensor`): Ngrams (batch_size, num_ngrams, ngram_len). Returns: ngram keys (batch_size, num_ngrams, dept...
Computes random keys for each ngram and depth. Args: ngrams (`torch.LongTensor`): Ngrams (batch_size, num_ngrams, ngram_len). Returns: ngram keys (batch_size, num_ngrams, depth).
compute_ngram_keys
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0
def _compute_keys( self, n_minus_1_grams: torch.LongTensor, indices: torch.LongTensor ) -> Tuple[torch.LongTensor, torch.LongTensor]: """Computes random keys for each ngram and depth. Args: n_minus_1_grams (`torch.LongTensor`): Ngrams (batch_size, ngram_len - 1)....
Computes random keys for each ngram and depth. Args: n_minus_1_grams (`torch.LongTensor`): Ngrams (batch_size, ngram_len - 1). indices (`torch.LongTensor`): indices of the continuations (batch_size, num_indices) Returns: Ngram keys (b...
_compute_keys
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0
def sample_g_values(self, ngram_keys: torch.LongTensor) -> torch.LongTensor: """ Samples g values from Bernoulli distribution. It is not possible to pass random keys in a vectorized way in torch. Instead we pre-compute a random sampling table, and use apply modulo table size to ...
Samples g values from Bernoulli distribution. It is not possible to pass random keys in a vectorized way in torch. Instead we pre-compute a random sampling table, and use apply modulo table size to map from ngram keys (int64) to g values. Args: ngram_keys (`torch.L...
sample_g_values
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0
def compute_g_values(self, input_ids: torch.LongTensor) -> torch.LongTensor: """ Computes g values for each ngram from the given sequence of tokens. Args: input_ids (`torch.LongTensor`): Input token ids (batch_size, input_len). Returns: G values ...
Computes g values for each ngram from the given sequence of tokens. Args: input_ids (`torch.LongTensor`): Input token ids (batch_size, input_len). Returns: G values (batch_size, input_len - (ngram_len - 1), depth).
compute_g_values
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0
def compute_context_repetition_mask(self, input_ids: torch.LongTensor) -> torch.LongTensor: """ Computes repetition mask. 0 and 1 stand for repeated and not repeated context n-1 grams respectively. Args: input_ids (`torch.LongTensor`): Input token ids (batch...
Computes repetition mask. 0 and 1 stand for repeated and not repeated context n-1 grams respectively. Args: input_ids (`torch.LongTensor`): Input token ids (batch_size, input_len). Returns: Repetitions mask (batch_size, input_len - (ngram_len -...
compute_context_repetition_mask
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0
def compute_eos_token_mask(self, input_ids: torch.LongTensor, eos_token_id: int) -> torch.LongTensor: """ Computes repetitions mask. 1 stands for ngrams that don't contain EOS tokens and vice versa. Args: input_ids (`torch.LongTensor`): Input token ids (batc...
Computes repetitions mask. 1 stands for ngrams that don't contain EOS tokens and vice versa. Args: input_ids (`torch.LongTensor`): Input token ids (batch_size, input_len). eos_token_id (`int`): EOS token ID. Returns: ...
compute_eos_token_mask
python
huggingface/transformers
src/transformers/generation/logits_process.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/logits_process.py
Apache-2.0
def _stop_string_get_matching_positions( token_list, token_indices, stop_strings ) -> Tuple[Dict[str, Dict[str, List[int]]], Dict[str, Dict[str, List[int]]]]: """This function preprocesses stop strings and the tokenizer vocabulary to determine where tokens can validly appear in the stop stri...
This function preprocesses stop strings and the tokenizer vocabulary to determine where tokens can validly appear in the stop strings. For each token, it computes a list of positions in the stop string where the token appears, as well as a list of the possible "end overlaps" for that token - that is, th...
_stop_string_get_matching_positions
python
huggingface/transformers
src/transformers/generation/stopping_criteria.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/stopping_criteria.py
Apache-2.0
def _stop_string_create_embedding_vec(token_list, token_indices, stop_strings) -> Dict[str, torch.tensor]: """This function precomputes everything needed for the run-time checks in StopStringCriteria, and packs them into an embedding tensor that can be accessed with pure tensor operations. For the speci...
This function precomputes everything needed for the run-time checks in StopStringCriteria, and packs them into an embedding tensor that can be accessed with pure tensor operations. For the specifics of the values that are precomputed and what they are used for, please refer to the StopStringCriteria doc...
_stop_string_create_embedding_vec
python
huggingface/transformers
src/transformers/generation/stopping_criteria.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/stopping_criteria.py
Apache-2.0
def compute_transition_scores( self, sequences: tf.Tensor, scores: Tuple[tf.Tensor], beam_indices: Optional[tf.Tensor] = None, normalize_logits: bool = False, ) -> tf.Tensor: """ Computes the transition scores of sequences given the generation scores (and beam...
Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was used). This is a convenient method to quickly obtain the scores of the selected tokens at generation time. Parameters: sequences (`tf.Tensor`): The generate...
compute_transition_scores
python
huggingface/transformers
src/transformers/generation/tf_utils.py
https://github.com/huggingface/transformers/blob/master/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
huggingface/transformers
src/transformers/generation/tf_utils.py
https://github.com/huggingface/transformers/blob/master/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
huggingface/transformers
src/transformers/generation/tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/tf_utils.py
Apache-2.0
def beam_search( self, input_ids: tf.Tensor, do_sample: bool = False, 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[Union[bool, str...
Generates sequences for models with a language modeling head using beam search. If `do_sample` is `False`, uses a greedy approach, otherwise does multinomial sampling without replacement. Parameters: input_ids (`tf.Tensor` of shape `(batch_size, num_beams, sequence_length)`): ...
beam_search
python
huggingface/transformers
src/transformers/generation/tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/tf_utils.py
Apache-2.0
def load_custom_generate( self, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]] = None, trust_remote_code: Optional[bool] = None, **kwargs, ) -> Callable: """ Loads and returns a custom generate function, given a model repo. Args: ...
Loads and returns a custom generate function, given a model repo. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. ...
load_custom_generate
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _cache_dependant_input_preparation( self, input_ids: torch.LongTensor, inputs_embeds: Optional[torch.FloatTensor], cache_position: Optional[torch.LongTensor], ) -> Tuple[torch.FloatTensor, torch.LongTensor]: """ Generic cache-dependent input preparation Th...
Generic cache-dependent input preparation The code is put in a separate function to allow granular unit testing as it needs a different implementation to be exportable. If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens - Exc...
_cache_dependant_input_preparation
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _cache_dependant_input_preparation_exporting( self, input_ids: torch.LongTensor, inputs_embeds: Optional[torch.FloatTensor], cache_position: Optional[torch.LongTensor], ) -> Tuple[torch.FloatTensor, torch.LongTensor]: """ This method implements method ``_cache_dep...
This method implements method ``_cache_dependant_input_preparation`` with :func:`torch.cond` to make it exportable with :func:`torch.export.export`. The code is put in a separate function to allow granular unit testing.
_cache_dependant_input_preparation_exporting
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _merge_criteria_processor_list( self, default_list: Union[LogitsProcessorList, StoppingCriteriaList], custom_list: Union[LogitsProcessorList, StoppingCriteriaList], ) -> Union[LogitsProcessorList, StoppingCriteriaList]: """ Merge user-defined processors/criteria with the ...
Merge user-defined processors/criteria with the ones instantiated inside `generate`. In case the same processor/criteria is present on both lists, use the user-defined one. (Note: up to v4.49.0, this function threw an exception is the same logit processor was found twice.)
_merge_criteria_processor_list
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def compute_transition_scores( self, sequences: torch.Tensor, scores: Tuple[torch.Tensor], beam_indices: Optional[torch.Tensor] = None, normalize_logits: bool = False, ) -> torch.Tensor: """ Computes the transition scores of sequences given the generation scor...
Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was used). This is a convenient method to quickly obtain the scores of the selected tokens at generation time. Parameters: sequences (`torch.LongTensor`): The g...
compute_transition_scores
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _get_layer_device_map_for_cache_init(self) -> Optional[Dict[int, Union[str, int]]]: """ Returns the device map for each decoder layer, to allocate the cache on the right device. Inspired from `dispatch_model` in accelerate. """ execution_device_map = None if hasattr(...
Returns the device map for each decoder layer, to allocate the cache on the right device. Inspired from `dispatch_model` in accelerate.
_get_layer_device_map_for_cache_init
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _valid_auto_compile_criteria(self, model_kwargs: Dict, generation_config: GenerationConfig) -> bool: """ Determines whether to trigger auto-compilation of the model's forward pass at generation time. """ # Override: honor `disable_compile` flag if generation_config.disable_co...
Determines whether to trigger auto-compilation of the model's forward pass at generation time.
_valid_auto_compile_criteria
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def generate( self, inputs: Optional[torch.Tensor] = None, generation_config: Optional[GenerationConfig] = None, logits_processor: Optional[LogitsProcessorList] = None, stopping_criteria: Optional[StoppingCriteriaList] = None, prefix_allowed_tokens_fn: Optional[Callable[[...
Generates sequences of token ids for models with a language modeling head. <Tip warning={true}> Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the model's default generation configuration. You can override any `generation_co...
generate
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _gather_beams(tensor: torch.Tensor, beam_indices: torch.Tensor) -> torch.Tensor: """ Gathers the beam slices indexed by beam_indices into new beam array. Args: tensor (`torch.Tensor`): A tensor containing data to be gathered. The tensor is a 2D or a 3D tensor wit...
Gathers the beam slices indexed by beam_indices into new beam array. Args: tensor (`torch.Tensor`): A tensor containing data to be gathered. The tensor is a 2D or a 3D tensor with the two first dimensions depicting the batch and the beam dimensions. beam_indices...
_gather_beams
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _beam_search_has_unfinished_sequences( running_beam_scores: torch.Tensor, beam_scores: torch.Tensor, is_sent_finished: torch.Tensor, next_token_hits_stopping_criteria: torch.Tensor, cur_len: int, max_length: int, decoder_prompt_len: int, early_stopping...
Beam Search stopping condition -- halts the generation loop if any of these conditions becomes False
_beam_search_has_unfinished_sequences
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _get_top_k_continuations( self, accumulated_log_probs: torch.Tensor, running_sequences: torch.Tensor, running_beam_indices: torch.Tensor, cur_len: int, decoder_prompt_len: int, do_sample: bool, beams_to_keep: int, num_beams: int, vocab_...
Get top-K continuations given the accumulated log probs on the next token. A few notes to understand what's going on: 1. Each item in batch has `num_beams` * `vocab_size` candidate continuations. For each item, get the top K [K = (number of EOS tokens + 1) * `num_beams`] candidates wit...
_get_top_k_continuations
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _get_running_beams_for_next_iteration( self, topk_log_probs: torch.Tensor, topk_running_sequences: torch.Tensor, topk_running_beam_indices: torch.Tensor, next_token_hits_stopping_criteria: torch.Tensor, num_beams: int, ) -> Tuple[torch.Tensor, torch.Tensor, torch....
Given the top-K continuations, their scores, and whether they hit a stopping criteria, select the best non-finished beams to continue beam search in the next iteration.
_get_running_beams_for_next_iteration
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _update_finished_beams( self, sequences: torch.Tensor, topk_running_sequences: torch.Tensor, beam_scores: torch.Tensor, topk_log_probs: torch.Tensor, beam_indices: torch.Tensor, topk_running_beam_indices: torch.Tensor, is_sent_finished: torch.Tensor, ...
Updates the finished beams if (and only if) there are new completed sequences that have a higher score than the current finished sequences.
_update_finished_beams
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _beam_search( self, input_ids: torch.LongTensor, logits_processor: LogitsProcessorList, stopping_criteria: StoppingCriteriaList, generation_config: GenerationConfig, synced_gpus: bool, **model_kwargs, ) -> Union[GenerateBeamOutput, torch.LongTensor]: ...
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. If it's the first time you're diving into Beam Search, we recommend you read the following blog po...
_beam_search
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _group_beam_search( self, input_ids: torch.LongTensor, beam_scorer: BeamScorer, logits_processor: LogitsProcessorList, stopping_criteria: StoppingCriteriaList, generation_config: GenerationConfig, synced_gpus: bool, **model_kwargs, ): r""" ...
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*num_beams, seq...
_group_beam_search
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def _constrained_beam_search( self, input_ids: torch.LongTensor, constrained_beam_scorer: ConstrainedBeamSearchScorer, logits_processor: LogitsProcessorList, stopping_criteria: StoppingCriteriaList, generation_config: GenerationConfig, synced_gpus: bool, *...
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*num_beams,...
_constrained_beam_search
python
huggingface/transformers
src/transformers/generation/utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/utils.py
Apache-2.0
def __call__( self, input_ids: torch.LongTensor, z_threshold: float = 3.0, return_dict: bool = False, ) -> Union[WatermarkDetectorOutput, np.array]: """ Args: input_ids (`torch.LongTensor`): The watermark generated text. It ...
Args: input_ids (`torch.LongTensor`): The watermark generated text. It is advised to remove the prompt, which can affect the detection. z_threshold (`Dict`, *optional*, defaults to `3.0`): Changing this threshold will change the se...
__call__
python
huggingface/transformers
src/transformers/generation/watermarking.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/watermarking.py
Apache-2.0
def _compute_latents(self, g_values: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """Computes the unique token probability distribution given g-values. Args: g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`): PRF values. Returns: ...
Computes the unique token probability distribution given g-values. Args: g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`): PRF values. Returns: p_one_unique_token and p_two_unique_tokens, both of shape [batch_size, seq_l...
_compute_latents
python
huggingface/transformers
src/transformers/generation/watermarking.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/watermarking.py
Apache-2.0
def forward(self, g_values: torch.Tensor) -> torch.Tensor: """Computes the likelihoods P(g_values|watermarked). Args: g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`): g-values (values 0 or 1) Returns: p(g_values|watermarked...
Computes the likelihoods P(g_values|watermarked). Args: g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`): g-values (values 0 or 1) Returns: p(g_values|watermarked) of shape [batch_size, seq_len, watermarking_depth].
forward
python
huggingface/transformers
src/transformers/generation/watermarking.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/watermarking.py
Apache-2.0
def _compute_posterior( self, likelihoods_watermarked: torch.Tensor, likelihoods_unwatermarked: torch.Tensor, mask: torch.Tensor, prior: float, ) -> torch.Tensor: """ Compute posterior P(w|g) given likelihoods, mask and prior. Args: likeli...
Compute posterior P(w|g) given likelihoods, mask and prior. Args: likelihoods_watermarked (`torch.Tensor` of shape `(batch, length, depth)`): Likelihoods P(g_values|watermarked) of g-values under watermarked model. likelihoods_unwatermarked (`torch.Tensor` of sh...
_compute_posterior
python
huggingface/transformers
src/transformers/generation/watermarking.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/watermarking.py
Apache-2.0
def forward( self, g_values: torch.Tensor, mask: torch.Tensor, labels: Optional[torch.Tensor] = None, loss_batch_weight=1, return_dict=False, ) -> BayesianWatermarkDetectorModelOutput: """ Computes the watermarked posterior P(watermarked|g_values). ...
Computes the watermarked posterior P(watermarked|g_values). Args: g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth, ...)`): g-values (with values 0 or 1) mask: A binary array shape [batch_size, seq_len] indicating which...
forward
python
huggingface/transformers
src/transformers/generation/watermarking.py
https://github.com/huggingface/transformers/blob/master/src/transformers/generation/watermarking.py
Apache-2.0
def replace_with_aqlm_linear( model, quantization_config=None, linear_weights_not_to_quantize=None, current_key_name=None, has_been_replaced=False, ): """ Public method that recursively replaces the Linear layers of the given model with AQLM quantized layers. `accelerate` is needed to us...
Public method that recursively replaces the Linear layers of the given model with AQLM quantized layers. `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the conversion has been successful or not. Args: model (`torch.nn.Module`): ...
replace_with_aqlm_linear
python
huggingface/transformers
src/transformers/integrations/aqlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/aqlm.py
Apache-2.0
def replace_with_awq_linear( model, modules_to_not_convert=None, quantization_config=None, current_key_name=None, has_been_replaced=False, ) -> bool: """ Public method that recursively replaces the Linear layers of the given model with AWQ quantized layers. `accelerate` is needed to use ...
Public method that recursively replaces the Linear layers of the given model with AWQ quantized layers. `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the conversion has been successful or not. During the module replacement, we also infer the bac...
replace_with_awq_linear
python
huggingface/transformers
src/transformers/integrations/awq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/awq.py
Apache-2.0
def get_modules_to_fuse(model, quantization_config): """ Returns the fusing mapping given the quantization config and the model Args: model (`~PreTrainedModel`): The model to fuse - note this model should have been converted into AWQ format beforehand. quantization_config (`~tra...
Returns the fusing mapping given the quantization config and the model Args: model (`~PreTrainedModel`): The model to fuse - note this model should have been converted into AWQ format beforehand. quantization_config (`~transformers.quantization_config.AWQConfig`): The q...
get_modules_to_fuse
python
huggingface/transformers
src/transformers/integrations/awq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/awq.py
Apache-2.0
def fuse_awq_modules(model, quantization_config): """ Optionally fuse some modules in the model to speedup inference. Args: model (`~PreTrainedModel`): The model to fuse - note this model should have been converted into AWQ format beforehand. quantization_config (`Union[AwqConfi...
Optionally fuse some modules in the model to speedup inference. Args: model (`~PreTrainedModel`): The model to fuse - note this model should have been converted into AWQ format beforehand. quantization_config (`Union[AwqConfig, dict]`): The quantization configuration to...
fuse_awq_modules
python
huggingface/transformers
src/transformers/integrations/awq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/awq.py
Apache-2.0
def _fuse_awq_layernorm(fuse_module_names, module, target_cls): """ Fuse the LayerNorm layers into a target class using autoawq Args: fuse_module_names (`List[str]`): The list of module names to fuse module (`nn.Module`): The pytorch parent module that has layernorm ...
Fuse the LayerNorm layers into a target class using autoawq Args: fuse_module_names (`List[str]`): The list of module names to fuse module (`nn.Module`): The pytorch parent module that has layernorm modules to fuse target_cls (`~autoawq.FasterTransformerRMSNorm`...
_fuse_awq_layernorm
python
huggingface/transformers
src/transformers/integrations/awq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/awq.py
Apache-2.0
def _fuse_awq_mlp(model, current_module_name, fuse_module_names, module, target_cls): """ Fuse the MLP layers into a target class using autoawq Args: model (`~PreTrainedModel`): The input pretrained model current_module_name (`str`): The current submodule name ...
Fuse the MLP layers into a target class using autoawq Args: model (`~PreTrainedModel`): The input pretrained model current_module_name (`str`): The current submodule name fuse_module_names (`List[str]`): The list of module names to fuse. For the MLP ...
_fuse_awq_mlp
python
huggingface/transformers
src/transformers/integrations/awq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/awq.py
Apache-2.0
def _fuse_awq_attention_layers(model, module, modules_to_fuse, current_module_name, target_cls): """ Fuse the Attention layers into a target class using autoawq Args: model (`~PreTrainedModel`): The input pretrained model module (`nn.Module`): The pytorch parent modu...
Fuse the Attention layers into a target class using autoawq Args: model (`~PreTrainedModel`): The input pretrained model module (`nn.Module`): The pytorch parent module that has layernorm modules to fuse modules_to_fuse (`List[str]`): The module fusi...
_fuse_awq_attention_layers
python
huggingface/transformers
src/transformers/integrations/awq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/awq.py
Apache-2.0
def post_init_awq_exllama_modules(model, exllama_config): """ Runs post init for Exllama layers which performs: - Weights unpacking, reordering and repacking - Devices scratch space allocation """ if exllama_config["version"] == ExllamaVersion.ONE: from awq.modules.linear.exllam...
Runs post init for Exllama layers which performs: - Weights unpacking, reordering and repacking - Devices scratch space allocation
post_init_awq_exllama_modules
python
huggingface/transformers
src/transformers/integrations/awq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/awq.py
Apache-2.0
def post_init_awq_ipex_modules(model): """ Runs post init for IPEX layers which performs: - Weights packing, reordering and repacking """ from awq.modules.linear.gemm_ipex import ipex_post_init model = ipex_post_init(model) return model
Runs post init for IPEX layers which performs: - Weights packing, reordering and repacking
post_init_awq_ipex_modules
python
huggingface/transformers
src/transformers/integrations/awq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/awq.py
Apache-2.0
def pack_weights(quantized_weights: torch.Tensor) -> torch.Tensor: """ Packs a tensor of quantized weights into a compact format using 2 bits per value. Parameters: ----------- quantized_weights : torch.Tensor A tensor containing ternary quantized weights with values in {-1, 0, 1}. These va...
Packs a tensor of quantized weights into a compact format using 2 bits per value. Parameters: ----------- quantized_weights : torch.Tensor A tensor containing ternary quantized weights with values in {-1, 0, 1}. These values are adjusted to {0, 1, 2} before being packed. Returns: ...
pack_weights
python
huggingface/transformers
src/transformers/integrations/bitnet.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/bitnet.py
Apache-2.0
def activation_quant(self, input, num_bits=8): """ Activation function : Performs symmetric, per-token quantization on the input activations. Parameters: ----------- x : torch.Tensor Input activations to be quantized. num_bits : int, optional (default=8) ...
Activation function : Performs symmetric, per-token quantization on the input activations. Parameters: ----------- x : torch.Tensor Input activations to be quantized. num_bits : int, optional (default=8) Number of bits to use for quantization, determining...
activation_quant
python
huggingface/transformers
src/transformers/integrations/bitnet.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/bitnet.py
Apache-2.0
def replace_with_bitnet_linear( model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, pre_quantized=False, ): """ A helper function to replace all `torch.nn.Linear` modules by `BitLinear158` modules`. The function will be run recursively and replace all `t...
A helper function to replace all `torch.nn.Linear` modules by `BitLinear158` modules`. The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manag...
replace_with_bitnet_linear
python
huggingface/transformers
src/transformers/integrations/bitnet.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/bitnet.py
Apache-2.0
def set_module_quantized_tensor_to_device(module, tensor_name, device, value=None, quantized_stats=None): """ A helper function to set a given tensor (parameter of buffer) of a module on a specific device (note that doing `param.to(device)` creates a new tensor not linked to the parameter, which is why we n...
A helper function to set a given tensor (parameter of buffer) of a module on a specific device (note that doing `param.to(device)` creates a new tensor not linked to the parameter, which is why we need this function). The function is adapted from `set_module_tensor_to_device` function from accelerate that ...
set_module_quantized_tensor_to_device
python
huggingface/transformers
src/transformers/integrations/bitsandbytes.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/bitsandbytes.py
Apache-2.0
def replace_with_bnb_linear(model, modules_to_not_convert=None, current_key_name=None, quantization_config=None): """ A helper function to replace all `torch.nn.Linear` modules by `bnb.nn.Linear8bit` modules from the `bitsandbytes` library. This will enable running your models using mixed int8 precision as ...
A helper function to replace all `torch.nn.Linear` modules by `bnb.nn.Linear8bit` modules from the `bitsandbytes` library. This will enable running your models using mixed int8 precision as described by the paper `LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale`. Make sure `bitsandbytes` ...
replace_with_bnb_linear
python
huggingface/transformers
src/transformers/integrations/bitsandbytes.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/bitsandbytes.py
Apache-2.0
def _create_accelerate_new_hook(old_hook): r""" Creates a new hook based on the old hook. Use it only if you know what you are doing ! This method is a copy of: https://github.com/huggingface/peft/blob/748f7968f3a31ec06a1c2b0328993319ad9a150a/src/peft/utils/other.py#L245 with some changes """ ol...
Creates a new hook based on the old hook. Use it only if you know what you are doing ! This method is a copy of: https://github.com/huggingface/peft/blob/748f7968f3a31ec06a1c2b0328993319ad9a150a/src/peft/utils/other.py#L245 with some changes
_create_accelerate_new_hook
python
huggingface/transformers
src/transformers/integrations/bitsandbytes.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/bitsandbytes.py
Apache-2.0
def _dequantize_and_replace( model, dtype, modules_to_not_convert=None, current_key_name=None, quantization_config=None, has_been_replaced=False, ): """ Converts a quantized model into its dequantized original version. The newly converted model will have some performance drop compare...
Converts a quantized model into its dequantized original version. The newly converted model will have some performance drop compared to the original model before quantization - use it only for specific usecases such as QLoRA adapters merging. Returns the converted model and a boolean that indicates if...
_dequantize_and_replace
python
huggingface/transformers
src/transformers/integrations/bitsandbytes.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/bitsandbytes.py
Apache-2.0
def validate_bnb_backend_availability(raise_exception=False): """ Validates if the available devices are supported by bitsandbytes, optionally raising an exception if not. """ if not is_bitsandbytes_available(): if importlib.util.find_spec("bitsandbytes") and version.parse( importlib...
Validates if the available devices are supported by bitsandbytes, optionally raising an exception if not.
validate_bnb_backend_availability
python
huggingface/transformers
src/transformers/integrations/bitsandbytes.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/bitsandbytes.py
Apache-2.0
def _load_state_dict_into_zero3_model(model_to_load, state_dict): """ Loads state dict into a model specifically for Zero3, since DeepSpeed does not support the `transformers` tensor parallelism API. Nearly identical code to PyTorch's `_load_from_state_dict` """ # copy state_dict so `_load_stat...
Loads state dict into a model specifically for Zero3, since DeepSpeed does not support the `transformers` tensor parallelism API. Nearly identical code to PyTorch's `_load_from_state_dict`
_load_state_dict_into_zero3_model
python
huggingface/transformers
src/transformers/integrations/deepspeed.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/deepspeed.py
Apache-2.0
def deepspeed_init(trainer, num_training_steps, inference=False): """ Init DeepSpeed, after updating the DeepSpeed configuration with any relevant Trainer's args. If `resume_from_checkpoint` was passed then an attempt to resume from a previously saved checkpoint will be made. Args: trainer: Tr...
Init DeepSpeed, after updating the DeepSpeed configuration with any relevant Trainer's args. If `resume_from_checkpoint` was passed then an attempt to resume from a previously saved checkpoint will be made. Args: trainer: Trainer object num_training_steps: per single gpu resume_fr...
deepspeed_init
python
huggingface/transformers
src/transformers/integrations/deepspeed.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/deepspeed.py
Apache-2.0
def replace_with_eetq_linear( model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, pre_quantized=False ): """ A helper function to replace all `torch.nn.Linear` modules by `eetq.EetqLinear` modules from the `eetq` library. This will enable running your models using high p...
A helper function to replace all `torch.nn.Linear` modules by `eetq.EetqLinear` modules from the `eetq` library. This will enable running your models using high performance int8 weight-only gemm kerner from FasterTransformer and TensorRT-LLM. Make sure `eetq` compiled with the correct CUDA version of y...
replace_with_eetq_linear
python
huggingface/transformers
src/transformers/integrations/eetq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/eetq.py
Apache-2.0
def __init__( self, model: PreTrainedModel, max_batch_size: int = 1, max_cache_len: int = 4096, ): """ Initializes the exportable module with `HybridCache`. Args: model (`PreTrainedModel`): The pretrained model to wrap. max_batch_size ...
Initializes the exportable module with `HybridCache`. Args: model (`PreTrainedModel`): The pretrained model to wrap. max_batch_size (int): Maximum batch size for the cache. max_cache_len (int): Maximum sequence length for the cache. Raises: Valu...
__init__
python
huggingface/transformers
src/transformers/integrations/executorch.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/executorch.py
Apache-2.0
def forward( self, input_ids: torch.Tensor, cache_position: torch.Tensor, ) -> torch.Tensor: """ Forward pass of the module, which is compatible with the ExecuTorch llm runner. Args: input_ids (`torch.Tensor`): Tensor representing current input token id t...
Forward pass of the module, which is compatible with the ExecuTorch llm runner. Args: input_ids (`torch.Tensor`): Tensor representing current input token id to the module. cache_position (`torch.Tensor`): Tensor representing current input position in the cache. Returns...
forward
python
huggingface/transformers
src/transformers/integrations/executorch.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/executorch.py
Apache-2.0
def export( self, input_ids: Optional[torch.Tensor] = None, cache_position: Optional[torch.Tensor] = None, dynamic_shapes: Optional[dict] = None, strict: Optional[bool] = None, ) -> torch.export.ExportedProgram: """ Export the wrapped module using `torch.expor...
Export the wrapped module using `torch.export`. Args: input_ids (`Optional[torch.Tensor]`): Tensor representing current input token id to the module. If not provided, a default tensor will be used. cache_position (`Optional[torch.Tensor]`): Tenso...
export
python
huggingface/transformers
src/transformers/integrations/executorch.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/executorch.py
Apache-2.0
def generate( exported_program: torch.export.ExportedProgram, tokenizer, prompt: str, max_new_tokens: int = 20, do_sample: bool = False, temperature: float = 1.0, top_k: int = 50, top_p: float = 1.0, device: str = "cpu", ) -> str: """ ...
Generate a sequence of tokens using an exported program. Args: exported_program (`torch.export.ExportedProgram`): The exported model being used for generate. tokenizer: The tokenizer to use. prompt (str): The input prompt. max_new_tokens (int): Maximum n...
generate
python
huggingface/transformers
src/transformers/integrations/executorch.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/executorch.py
Apache-2.0
def __init__(self, model: PreTrainedModel): """ Initializes the wrapper module with the pretrained model. Args: model (`PreTrainedModel`): The pretrained model to wrap. The model must have caching enabled and use a 'static' caching implementation. Raises: ...
Initializes the wrapper module with the pretrained model. Args: model (`PreTrainedModel`): The pretrained model to wrap. The model must have caching enabled and use a 'static' caching implementation. Raises: AssertionError: If the pretrained model does not ...
__init__
python
huggingface/transformers
src/transformers/integrations/executorch.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/executorch.py
Apache-2.0
def forward(self, input_ids: torch.Tensor, cache_position: torch.Tensor): """ Forward pass of the module, which is compatible with the ExecuTorch runtime. Args: input_ids (`torch.Tensor`): Tensor representing current input token id to the module. cache_position (`torch.T...
Forward pass of the module, which is compatible with the ExecuTorch runtime. Args: input_ids (`torch.Tensor`): Tensor representing current input token id to the module. cache_position (`torch.Tensor`): Tensor representing current input position in the cache. Returns: ...
forward
python
huggingface/transformers
src/transformers/integrations/executorch.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/executorch.py
Apache-2.0
def __init__( self, model: PreTrainedModel, max_batch_size: int = 1, max_cache_len: int = 4096, ): """ Initializes the exportable module with `HybridCache`. Args: model (`PreTrainedModel`): The pretrained model to wrap. max_batch_size ...
Initializes the exportable module with `HybridCache`. Args: model (`PreTrainedModel`): The pretrained model to wrap. max_batch_size (int): Maximum batch size for the cache. max_cache_len (int): Maximum sequence length for the cache. Raises: Asse...
__init__
python
huggingface/transformers
src/transformers/integrations/executorch.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/executorch.py
Apache-2.0
def convert_and_export_with_cache( model: PreTrainedModel, example_input_ids: Optional[torch.Tensor] = None, example_cache_position: Optional[torch.Tensor] = None, dynamic_shapes: Optional[dict] = None, strict: Optional[bool] = None, ): """ Convert a `PreTrainedModel` into an exportable modu...
Convert a `PreTrainedModel` into an exportable module and export it using `torch.export`, ensuring the exported model is compatible with `ExecuTorch`. Args: model (`PreTrainedModel`): The pretrained model to be exported. example_input_ids (`Optional[torch.Tensor]`): Example input token id ...
convert_and_export_with_cache
python
huggingface/transformers
src/transformers/integrations/executorch.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/executorch.py
Apache-2.0
def export_with_dynamic_cache( model: PreTrainedModel, example_input_ids: Optional[torch.Tensor] = None, example_attention_mask: Optional[torch.Tensor] = None, ): """ Export a model with DynamicCache using `torch.export`, ensuring the exported model is compatible with `ExecuTorch`. Args: ...
Export a model with DynamicCache using `torch.export`, ensuring the exported model is compatible with `ExecuTorch`. Args: model (`PreTrainedModel`): The pretrained model to be exported. example_input_ids (`Optional[torch.Tensor]`): Example input token id used by `torch.export`. example...
export_with_dynamic_cache
python
huggingface/transformers
src/transformers/integrations/executorch.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/executorch.py
Apache-2.0
def sdpa_mask_without_vmap( batch_size: int, cache_position: torch.Tensor, kv_length: int, kv_offset: int = 0, mask_function: Optional[Callable] = None, attention_mask: Optional[torch.Tensor] = None, local_size: Optional[int] = None, allow_is_causal_skip: bool = True, allow_torch_fix...
Create a 4D boolean mask of shape `(batch_size, 1, query_length, kv_length)` where a value of True indicates that the element should take part in the attention computation, and False that it should not. This is similar to `masking_utils.sdpa_mask` but does not use `vmap` which is incompatible with export....
sdpa_mask_without_vmap
python
huggingface/transformers
src/transformers/integrations/executorch.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/executorch.py
Apache-2.0
def forward(self, hidden_states): """ Args: hidden_states (torch.Tensor): (batch_size * token_num, hidden_size) Returns: torch.Tensor: (batch_size * token_num, hidden_size) """ # Reshape hidden states for expert computation hidden_states = hidden_s...
Args: hidden_states (torch.Tensor): (batch_size * token_num, hidden_size) Returns: torch.Tensor: (batch_size * token_num, hidden_size)
forward
python
huggingface/transformers
src/transformers/integrations/fbgemm_fp8.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/fbgemm_fp8.py
Apache-2.0
def replace_with_fbgemm_fp8_linear( model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, pre_quantized=False, config=None, tp_plan=None, ): """ A helper function to replace all `torch.nn.Linear` modules by `FbgemmFp8Linear` modules. This will enabl...
A helper function to replace all `torch.nn.Linear` modules by `FbgemmFp8Linear` modules. This will enable running your models using high performance fp8 kernel from FBGEMM library. The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should be ke...
replace_with_fbgemm_fp8_linear
python
huggingface/transformers
src/transformers/integrations/fbgemm_fp8.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/fbgemm_fp8.py
Apache-2.0
def w8a8_block_fp8_matmul_compile( input_q: torch.Tensor, # [batch, seq_len, hidden_dim] weight_q: torch.Tensor, # [out_features, hidden_dim] input_scale: torch.Tensor, # [batch * seq_len, num_input_groups] weight_scale: torch.Tensor, # [num_weight_blocks_m, num_weight_blocks_n] block_size: Opti...
Performs blocked matrix multiplication with FP8 quantized matrices. Args: input_q: Quantized input tensor with 1x128 block quantization weight_q: Quantized weight tensor with 128x128 block quantization input_scale: Scaling factors for input blocks weight_scale: Scaling factors ...
w8a8_block_fp8_matmul_compile
python
huggingface/transformers
src/transformers/integrations/finegrained_fp8.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/finegrained_fp8.py
Apache-2.0
def replace_with_fp8_linear( model, modules_to_not_convert=None, quantization_config=None, ): """Helper function to replace model layers with FP8 versions.""" modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert if quantization_config.modules_to_not...
Helper function to replace model layers with FP8 versions.
replace_with_fp8_linear
python
huggingface/transformers
src/transformers/integrations/finegrained_fp8.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/finegrained_fp8.py
Apache-2.0
def paged_attention_forward( module: torch.nn.Module, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, attention_mask: torch.Tensor = None, cache: PagedAttentionCache = None, cumulative_seqlens_q=None, cumulative_seqlens_k=None, max_seqlen_q=None, max_seqlen_k=None, block_t...
Perform the forward pass of attention with paged key-value cache. This function handles the cache updates and performs the attention computation using the flash_attn_varlen_func for efficient processing. Args: q: (total_q, nheads, headdim), where total_q = total number of query tokens in the batch...
paged_attention_forward
python
huggingface/transformers
src/transformers/integrations/flash_paged.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/flash_paged.py
Apache-2.0
def __init__(self, training): """ Initialize or update the singleton instance. """ if not self._is_flex_compiled or training != self.training: # In PyTorch 2.6.0, there's a known issue with flex attention compilation which may # cause errors. The suggested fix is ...
Initialize or update the singleton instance.
__init__
python
huggingface/transformers
src/transformers/integrations/flex_attention.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/flex_attention.py
Apache-2.0
def causal_mask_mod(batch_idx, head_idx, q_idx, kv_idx): """ Defines the logic of a block causal mask by combining both a standard causal mask and a block diagonal document mask. See :func:`~torchtune.modules.attention_utils.create_block_causal_mask` for an illustration. ...
Defines the logic of a block causal mask by combining both a standard causal mask and a block diagonal document mask. See :func:`~torchtune.modules.attention_utils.create_block_causal_mask` for an illustration.
causal_mask_mod
python
huggingface/transformers
src/transformers/integrations/flex_attention.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/flex_attention.py
Apache-2.0
def chunk_causal_mask_mod(batch_idx, head_idx, q_idx, kv_idx): """ Combines the chunk mask with the causal mask for chunked attention. """ chunk_mask = chunk_idxs[batch_idx, q_idx] == chunk_idxs[batch_idx, kv_idx] causal_doc_mask = causal_mask_mod(batch_idx, head_idx, q_idx, kv_i...
Combines the chunk mask with the causal mask for chunked attention.
chunk_causal_mask_mod
python
huggingface/transformers
src/transformers/integrations/flex_attention.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/flex_attention.py
Apache-2.0
def default_mask_mod(batch_idx, head_idx, q_idx, kv_idx): """ Utilizes default attention mask to enable encoder and encoder-decoder attention masks. """ document_mask = document_ids[batch_idx, q_idx] == document_ids[batch_idx, kv_idx] # kv indexing is crucial in order to ...
Utilizes default attention mask to enable encoder and encoder-decoder attention masks.
default_mask_mod
python
huggingface/transformers
src/transformers/integrations/flex_attention.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/flex_attention.py
Apache-2.0
def convert_gguf_tokenizer(architecture, tokenizer_dict) -> Tokenizer: """ Utilities to convert a slow tokenizer instance in a fast tokenizer instance. Args: architecture (`str`): The model architecture derived from gguf file. transformer_tokenizer ([`~tokenization_utils_base.PreTrainedToke...
Utilities to convert a slow tokenizer instance in a fast tokenizer instance. Args: architecture (`str`): The model architecture derived from gguf file. transformer_tokenizer ([`~tokenization_utils_base.PreTrainedTokenizer`]): Instance of a slow tokenizer to convert in the backend t...
convert_gguf_tokenizer
python
huggingface/transformers
src/transformers/integrations/ggml.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/ggml.py
Apache-2.0
def replace_with_higgs_linear( model, quantization_config=None, current_key_name=None, has_been_replaced=False, ): """ Public method that recursively replaces the Linear layers of the given model with HIGGS quantized layers. `accelerate` is needed to use this method. Returns the converted mo...
Public method that recursively replaces the Linear layers of the given model with HIGGS quantized layers. `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the conversion has been successful or not. Args: model (`torch.nn.Module`): ...
replace_with_higgs_linear
python
huggingface/transformers
src/transformers/integrations/higgs.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/higgs.py
Apache-2.0
def dequantize_higgs(model, current_key_name=None): """ Dequantizes the HiggsLinear layers in the given model by replacing them with standard torch.nn.Linear layers. Args: model (torch.nn.Module): The model containing HiggsLinear layers to be dequantized. current_key_name (list, optional): A...
Dequantizes the HiggsLinear layers in the given model by replacing them with standard torch.nn.Linear layers. Args: model (torch.nn.Module): The model containing HiggsLinear layers to be dequantized. current_key_name (list, optional): A list to keep track of the current module names during recu...
dequantize_higgs
python
huggingface/transformers
src/transformers/integrations/higgs.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/higgs.py
Apache-2.0
def prepare_for_hqq_linear(model, quantization_config=None, modules_to_not_convert=None, has_been_replaced=False): """ Prepares nn.Linear layers for HQQ quantization. Since each layer type can have separate quantization parameters, we need to do the following: 1- tag each module with its name via autona...
Prepares nn.Linear layers for HQQ quantization. Since each layer type can have separate quantization parameters, we need to do the following: 1- tag each module with its name via autoname_modules() 2- Extract linear_tags (e.g. ['self_attn.q_proj', ...]) 3- Map quantization parameters as a dictionar...
prepare_for_hqq_linear
python
huggingface/transformers
src/transformers/integrations/hqq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/hqq.py
Apache-2.0
def use_kernel_forward_from_hub(*args, **kwargs): """ Expands `kernels`' `use_kernel_forward_from_hub` to NOT use a kernel at compile time. This should be removed when `kernels` supports `torch.compile`. If the layer has a `config` attribute, we can also set `config.disable_custom_kerne...
Expands `kernels`' `use_kernel_forward_from_hub` to NOT use a kernel at compile time. This should be removed when `kernels` supports `torch.compile`. If the layer has a `config` attribute, we can also set `config.disable_custom_kernels = True` to disable the kernel.
use_kernel_forward_from_hub
python
huggingface/transformers
src/transformers/integrations/hub_kernels.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/hub_kernels.py
Apache-2.0
def setup(self, args, state, model): """ Setup the optional Comet integration. Environment: - **COMET_MODE** (`str`, *optional*, default to `get_or_create`): Control whether to create and log to a new Comet experiment or append to an existing experiment. It accep...
Setup the optional Comet integration. Environment: - **COMET_MODE** (`str`, *optional*, default to `get_or_create`): Control whether to create and log to a new Comet experiment or append to an existing experiment. It accepts the following values: * `get_...
setup
python
huggingface/transformers
src/transformers/integrations/integration_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/integration_utils.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 server,...
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*, will c...
setup
python
huggingface/transformers
src/transformers/integrations/integration_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/integration_utils.py
Apache-2.0
def convert_tekken_tokenizer(tokenizer_file: str): """Convert a "tekken" tokenizer to a fast Tokenizer.""" # Tekken format -- need to use the Converter from mistral_common.tokens.tokenizers.mistral import MistralTokenizer # Load directly using their lib mistral_tokenizer = MistralTokenizer.from_fi...
Convert a "tekken" tokenizer to a fast Tokenizer.
convert_tekken_tokenizer
python
huggingface/transformers
src/transformers/integrations/mistral.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/mistral.py
Apache-2.0
def enable_adapters(self) -> None: """ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT official documentation: https://huggingface.co/docs/peft Enable adapters that are attached to the model. """ check_peft_versio...
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT official documentation: https://huggingface.co/docs/peft Enable adapters that are attached to the model.
enable_adapters
python
huggingface/transformers
src/transformers/integrations/peft.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/peft.py
Apache-2.0
def get_adapter_state_dict(self, adapter_name: Optional[str] = None, state_dict: Optional[dict] = None) -> dict: """ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT official documentation: https://huggingface.co/docs/peft Gets th...
If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT official documentation: https://huggingface.co/docs/peft Gets the adapter state dict that should only contain the weights tensors of the specified adapter_name adapter. If no adapt...
get_adapter_state_dict
python
huggingface/transformers
src/transformers/integrations/peft.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/peft.py
Apache-2.0
def delete_adapter(self, adapter_names: Union[List[str], str]) -> None: """ Delete an adapter's LoRA layers from the underlying model. Args: adapter_names (`Union[List[str], str]`): The name(s) of the adapter(s) to delete. Example: ```py fro...
Delete an adapter's LoRA layers from the underlying model. Args: adapter_names (`Union[List[str], str]`): The name(s) of the adapter(s) to delete. Example: ```py from diffusers import AutoPipelineForText2Image import torch pipeline...
delete_adapter
python
huggingface/transformers
src/transformers/integrations/peft.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/peft.py
Apache-2.0
def replace_with_quanto_layers( model, quantization_config=None, modules_to_not_convert=None, current_key_name=None, has_been_replaced=False, ): """ Public method that recursively replaces the Linear layers of the given model with Quanto quantized layers. Returns the converted model and ...
Public method that recursively replaces the Linear layers of the given model with Quanto quantized layers. Returns the converted model and a boolean that indicates if the conversion has been successful or not. Args: model (`torch.nn.Module`): The model to convert, can be any `torch.nn....
replace_with_quanto_layers
python
huggingface/transformers
src/transformers/integrations/quanto.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/quanto.py
Apache-2.0
def replace_with_spqr_linear( model, quantization_config=None, modules_to_not_convert=None, current_key_name=None, has_been_replaced=False, ): """ Public method that recursively replaces the Linear layers of the given model with SpQR quantized layers. `accelerate` is needed to use this m...
Public method that recursively replaces the Linear layers of the given model with SpQR quantized layers. `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the conversion has been successful or not. Args: model (`torch.nn.Module`): ...
replace_with_spqr_linear
python
huggingface/transformers
src/transformers/integrations/spqr.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/spqr.py
Apache-2.0
def initialize_tensor_parallelism(tp_plan, tp_size=None): r""" Sets up the device mesh and initilized the backend for tensor parallelism. This function is called when the model is loaded and the TP plan is set to 'auto'. """ if tp_plan is None: return None, None, None if not is_torch_gr...
Sets up the device mesh and initilized the backend for tensor parallelism. This function is called when the model is loaded and the TP plan is set to 'auto'.
initialize_tensor_parallelism
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0
def _blocks_to_block_sizes(total_size: int, blocks: Union[int, List[int]]) -> List[int]: """ Convert block count or proportions to block sizes. This function accepts - The number of blocks (int), in which case the block size is total_size//blocks; or - A list of block sizes (List[int]). ...
Convert block count or proportions to block sizes. This function accepts - The number of blocks (int), in which case the block size is total_size//blocks; or - A list of block sizes (List[int]). In the second case, if sum(blocks) < total_size, the ratios between the block sizes will be...
_blocks_to_block_sizes
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0
def _get_parameter_tp_plan(parameter_name: str, tp_plan: dict[str, str]) -> Optional[str]: """ Get the TP style for a parameter from the TP plan. The TP plan is a dictionary that maps parameter names to TP styles. The parameter name can be a generic name with wildcards (e.g. "*.weight") or a specific n...
Get the TP style for a parameter from the TP plan. The TP plan is a dictionary that maps parameter names to TP styles. The parameter name can be a generic name with wildcards (e.g. "*.weight") or a specific name (e.g. "layer_1.weight").
_get_parameter_tp_plan
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0
def repack_weights( packed_parameter: torch.Tensor, sharded_dim: int, # The dimension index in the global tensor that was sharded world_size: int, num_blocks: int = 2, ) -> torch.Tensor: """ Reorders a tensor that was reconstructed from sharded packed weights into its canonical packed format. ...
Reorders a tensor that was reconstructed from sharded packed weights into its canonical packed format. For example, if a weight was packed (e.g., gate_proj and up_proj) and then sharded, DTensor.full_tensor() might produce an interleaved layout like [G0, U0, G1, U1, ...] along the sharded dimension. T...
repack_weights
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0
def get_tensor_shard(param, empty_param, device_mesh, rank, dim): """ Generalized tensor sharding across a multi-dimensional device mesh. Args: param (torch.Tensor): The tensor to shard. empty_param (torch.Tensor): A tensor used for shape reference. device_mesh (torch.Tensor): Shape...
Generalized tensor sharding across a multi-dimensional device mesh. Args: param (torch.Tensor): The tensor to shard. empty_param (torch.Tensor): A tensor used for shape reference. device_mesh (torch.Tensor): Shape [d_0, ..., d_n] representing the mesh. rank (int): Global rank o...
get_tensor_shard
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0
def distribute_module( module: nn.Module, device_mesh=None, input_fn=None, output_fn=None, ) -> nn.Module: """ Copy pasted from torch's function but we remove the communications (partitioning) as well as buffer registering that is similarly not efficient. """ if len(module._forward_p...
Copy pasted from torch's function but we remove the communications (partitioning) as well as buffer registering that is similarly not efficient.
distribute_module
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0
def convert_local_tensor_to_dtensor( parameter: torch.Tensor, parameter_name: str, device_mesh, tp_plan: dict[str, str] ) -> DTensor: """ Converts a local variant of weights to a DTensor with corresponding placements. Shouldn't be done ever except of before saving the model. """ _, param_type = para...
Converts a local variant of weights to a DTensor with corresponding placements. Shouldn't be done ever except of before saving the model.
convert_local_tensor_to_dtensor
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0
def replace_state_dict_local_with_dtensor( state_dict: dict[str, torch.Tensor], tp_plan: dict[str, str], device_mesh, ) -> dict[str, torch.Tensor]: """ Replaces all tensors that were sharded with `local_*` strategy with DTensor to make determining their proper size possible. """ for key, val...
Replaces all tensors that were sharded with `local_*` strategy with DTensor to make determining their proper size possible.
replace_state_dict_local_with_dtensor
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0
def add_tensor_parallel_hooks_to_module(model, module, tp_plan, layer_name, current_module_plan, device_mesh): """ Add hooks to the module holding the layer. Meaning: ``` class MyModel(nn.Module): def __init__(self): self.layer = nn.Linear(10, 10) ``` has state_dict like: ...
Add hooks to the module holding the layer. Meaning: ``` class MyModel(nn.Module): def __init__(self): self.layer = nn.Linear(10, 10) ``` has state_dict like: ``` { "layer.weight": torch.Tensor, "layer.bias": torch.Tensor } ``` we add hooks to ...
add_tensor_parallel_hooks_to_module
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0
def shard_and_distribute_module( model, param, empty_param, parameter_name, param_casting_dtype, is_contiguous, rank, device_mesh ): r""" Main uses cases: - column / rowise parallelism, you just shard all the weights of the layer (weight and bias) - packed layers: you slice the weights, then shard l...
Main uses cases: - column / rowise parallelism, you just shard all the weights of the layer (weight and bias) - packed layers: you slice the weights, then shard like above - custom operation: - you want to add an all-gather at the end of a local layer. - you want to have a layer that is...
shard_and_distribute_module
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0
def verify_tp_plan(expected_keys: list[str], tp_plan: Optional[dict[str, str]]): """ Verify the TP plan of the model, log a warning if the layers that were not sharded and the rules that were not applied. """ if tp_plan is None: return generic_keys = {re.sub(r"\d+", "*", key) for key in ex...
Verify the TP plan of the model, log a warning if the layers that were not sharded and the rules that were not applied.
verify_tp_plan
python
huggingface/transformers
src/transformers/integrations/tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/src/transformers/integrations/tensor_parallel.py
Apache-2.0