diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/generation/utils.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/generation/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c7fffb117bcb1327e248e21661a0a0c5d226718
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/generation/utils.py
@@ -0,0 +1,4772 @@
+# coding=utf-8
+# Copyright 2020 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.
+# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import copy
+import inspect
+import os
+import warnings
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+import torch.distributed as dist
+from torch import nn
+from torch.nn import functional as F
+
+from transformers.generation.candidate_generator import AssistantVocabTranslatorCache
+
+from ..cache_utils import (
+ Cache,
+ DynamicCache,
+ EncoderDecoderCache,
+ OffloadedCache,
+ QuantizedCacheConfig,
+ StaticCache,
+)
+from ..configuration_utils import PretrainedConfig
+from ..integrations.deepspeed import is_deepspeed_zero3_enabled
+from ..integrations.fsdp import is_fsdp_managed_module
+from ..modeling_outputs import CausalLMOutputWithPast, Seq2SeqLMOutput
+from ..pytorch_utils import isin_mps_friendly
+from ..tokenization_utils import ExtensionsTrie
+from ..utils import (
+ ModelOutput,
+ is_accelerate_available,
+ is_hqq_available,
+ is_optimum_quanto_available,
+ is_torchdynamo_compiling,
+ logging,
+)
+from .beam_constraints import DisjunctiveConstraint, PhrasalConstraint
+from .beam_search import BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
+from .candidate_generator import (
+ AssistedCandidateGenerator,
+ AssistedCandidateGeneratorDifferentTokenizers,
+ CandidateGenerator,
+ EarlyExitCandidateGenerator,
+ PromptLookupCandidateGenerator,
+ UniversalSpeculativeDecodingGenerator,
+ _crop_past_key_values,
+ _prepare_attention_mask,
+ _prepare_token_type_ids,
+)
+from .configuration_utils import (
+ NEED_SETUP_CACHE_CLASSES_MAPPING,
+ QUANT_BACKEND_CLASSES_MAPPING,
+ GenerationConfig,
+ GenerationMode,
+)
+from .logits_process import (
+ EncoderNoRepeatNGramLogitsProcessor,
+ EncoderRepetitionPenaltyLogitsProcessor,
+ EpsilonLogitsWarper,
+ EtaLogitsWarper,
+ ExponentialDecayLengthPenalty,
+ ForcedBOSTokenLogitsProcessor,
+ ForcedEOSTokenLogitsProcessor,
+ HammingDiversityLogitsProcessor,
+ InfNanRemoveLogitsProcessor,
+ LogitNormalization,
+ LogitsProcessorList,
+ MinLengthLogitsProcessor,
+ MinNewTokensLengthLogitsProcessor,
+ MinPLogitsWarper,
+ NoBadWordsLogitsProcessor,
+ NoRepeatNGramLogitsProcessor,
+ PrefixConstrainedLogitsProcessor,
+ RepetitionPenaltyLogitsProcessor,
+ SequenceBiasLogitsProcessor,
+ SuppressTokensAtBeginLogitsProcessor,
+ SuppressTokensLogitsProcessor,
+ TemperatureLogitsWarper,
+ TopKLogitsWarper,
+ TopPLogitsWarper,
+ TypicalLogitsWarper,
+ UnbatchedClassifierFreeGuidanceLogitsProcessor,
+)
+from .stopping_criteria import (
+ ConfidenceCriteria,
+ EosTokenCriteria,
+ MaxLengthCriteria,
+ MaxTimeCriteria,
+ StoppingCriteria,
+ StoppingCriteriaList,
+ StopStringCriteria,
+)
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..tokenization_utils_base import PreTrainedTokenizerBase
+ from .streamers import BaseStreamer
+
+logger = logging.get_logger(__name__)
+
+if is_accelerate_available():
+ from accelerate.hooks import AlignDevicesHook, add_hook_to_module
+
+
+# Variable names used to hold the cache at generation time
+ALL_CACHE_NAMES = [
+ "past_key_values", # default
+ "cache_params", # mamba-based models
+ "state", # rwkv
+ "mems", # xlnet
+ "past_buckets_states", # reformer
+]
+
+
+@dataclass
+class GenerateDecoderOnlyOutput(ModelOutput):
+ """
+ Outputs of decoder-only generation models, when using non-beam methods.
+
+ Args:
+ sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check
+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
+ """
+
+ sequences: torch.LongTensor = None
+ scores: Optional[Tuple[torch.FloatTensor]] = None
+ logits: Optional[Tuple[torch.FloatTensor]] = None
+ attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
+
+
+@dataclass
+class GenerateEncoderDecoderOutput(ModelOutput):
+ """
+ Outputs of encoder-decoder generation models, when using non-beam methods.
+
+ Args:
+ sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
+ sequence_length, sequence_length)`.
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+ decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check
+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
+ """
+
+ sequences: torch.LongTensor = None
+ scores: Optional[Tuple[torch.FloatTensor]] = None
+ logits: Optional[Tuple[torch.FloatTensor]] = None
+ encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
+ encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
+ decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
+
+
+@dataclass
+class GenerateBeamDecoderOnlyOutput(ModelOutput):
+ """
+ Outputs of decoder-only generation models, when using beam methods.
+
+ Args:
+ sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):
+ Final beam scores of the generated `sequences`.
+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
+ Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
+ of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
+ Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):
+ Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`.
+ attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
+ hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check
+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
+ """
+
+ sequences: torch.LongTensor = None
+ sequences_scores: Optional[torch.FloatTensor] = None
+ scores: Optional[Tuple[torch.FloatTensor]] = None
+ logits: Optional[Tuple[torch.FloatTensor]] = None
+ beam_indices: Optional[torch.LongTensor] = None
+ attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
+
+
+@dataclass
+class GenerateBeamEncoderDecoderOutput(ModelOutput):
+ """
+ Outputs of encoder-decoder generation models, when using beam methods.
+
+ Args:
+ sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):
+ Final beam scores of the generated `sequences`.
+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
+ Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
+ of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
+ Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):
+ Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`.
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
+ sequence_length, sequence_length)`.
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)`.
+ decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, num_heads, generated_length,
+ sequence_length)`.
+ cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check
+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
+ """
+
+ sequences: torch.LongTensor = None
+ sequences_scores: Optional[torch.FloatTensor] = None
+ scores: Optional[Tuple[torch.FloatTensor]] = None
+ logits: Optional[Tuple[torch.FloatTensor]] = None
+ beam_indices: Optional[torch.LongTensor] = None
+ encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
+ encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
+ decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
+
+
+# TODO (joao): remove the equivalent classes and typing shortcuts below in v5
+# Equivalent classes (kept for retrocompatibility purposes)
+GreedySearchDecoderOnlyOutput = GenerateDecoderOnlyOutput
+ContrastiveSearchDecoderOnlyOutput = GenerateDecoderOnlyOutput
+SampleDecoderOnlyOutput = GenerateDecoderOnlyOutput
+
+ContrastiveSearchEncoderDecoderOutput = GenerateEncoderDecoderOutput
+GreedySearchEncoderDecoderOutput = GenerateEncoderDecoderOutput
+SampleEncoderDecoderOutput = GenerateEncoderDecoderOutput
+
+BeamSearchDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput
+BeamSampleDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput
+
+BeamSearchEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput
+BeamSampleEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput
+
+GreedySearchOutput = Union[GreedySearchEncoderDecoderOutput, GreedySearchDecoderOnlyOutput]
+SampleOutput = Union[SampleEncoderDecoderOutput, SampleDecoderOnlyOutput]
+BeamSearchOutput = Union[BeamSearchEncoderDecoderOutput, BeamSearchDecoderOnlyOutput]
+BeamSampleOutput = Union[BeamSampleEncoderDecoderOutput, BeamSampleDecoderOnlyOutput]
+ContrastiveSearchOutput = Union[ContrastiveSearchEncoderDecoderOutput, ContrastiveSearchDecoderOnlyOutput]
+
+# Typing shortcuts
+GenerateNonBeamOutput = Union[GenerateDecoderOnlyOutput, GenerateEncoderDecoderOutput]
+GenerateBeamOutput = Union[GenerateBeamDecoderOnlyOutput, GenerateBeamEncoderDecoderOutput]
+GenerateOutput = Union[GenerateNonBeamOutput, GenerateBeamOutput]
+
+
+class GenerationMixin:
+ """
+ A class containing all functions for auto-regressive text generation, to be used as a mixin in [`PreTrainedModel`].
+
+ The class exposes [`~generation.GenerationMixin.generate`], which can be used for:
+ - *greedy decoding* if `num_beams=1` and `do_sample=False`
+ - *contrastive search* if `penalty_alpha>0` and `top_k>1`
+ - *multinomial sampling* if `num_beams=1` and `do_sample=True`
+ - *beam-search decoding* if `num_beams>1` and `do_sample=False`
+ - *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`
+ - *diverse beam-search decoding* if `num_beams>1` and `num_beam_groups>1`
+ - *constrained beam-search decoding* if `constraints!=None` or `force_words_ids!=None`
+ - *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`
+
+ To learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
+ """
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids: torch.LongTensor,
+ past_key_values: Optional[Cache] = None,
+ attention_mask: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ **kwargs,
+ ):
+ """
+ Prepare the model inputs for generation. In includes operations like computing the 4D attention mask or
+ slicing inputs given the existing cache.
+
+ See the forward pass in the model documentation for expected arguments (different models might have different
+ requirements for e.g. `past_key_values`). This function should work as is for most LLMs.
+ """
+
+ # 1. Handle BC:
+ model_inputs = {}
+ # - some models don't have `Cache` support (which implies they don't expect `cache_position` in `forward`)
+ if self._supports_cache_class:
+ model_inputs["cache_position"] = cache_position
+ # - `cache_position` was not a mandatory input in `prepare_inputs_for_generation` for those models, and this
+ # function may be called outside of `generate`. Handle most use cases by creating `cache_position` on the fly
+ # (this alternative is not as robust as calling `generate` and letting it create `cache_position`)
+ elif cache_position is None:
+ past_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
+ cache_position = torch.arange(past_length, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
+
+ # 2. Generic cache-dependent input preparation
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
+ # (we can't check exception 3 while compiling)
+ # Excpetion 4: If input_embeds are passed then slice it through `cache_position`, to keep only the unprocessed tokens and
+ # generate the first token for each sequence. Later use the generated Input ids for continuation.
+ if past_key_values is not None:
+ model_inputs["past_key_values"] = past_key_values
+ if inputs_embeds is not None and input_ids.shape[1] == 0: # Exception 4
+ inputs_embeds = inputs_embeds[:, -cache_position.shape[0] :]
+ elif (
+ inputs_embeds is not None # Exception 1
+ or (is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1]) # Exception 3
+ ):
+ input_ids = input_ids[:, -cache_position.shape[0] :]
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
+ input_ids = input_ids[:, cache_position]
+
+ # 3. Prepare base model inputs
+ input_ids_key = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step for every prompt.
+ if not self.config.is_encoder_decoder:
+ if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]:
+ model_inputs[input_ids_key] = None
+ model_inputs["inputs_embeds"] = inputs_embeds
+ else:
+ # `clone` calls in this function ensure a consistent stride. See #32227
+ model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)
+ model_inputs["inputs_embeds"] = None
+ else:
+ model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)
+
+ # 4. Create missing `position_ids` on the fly
+ encoder_attention_mask = attention_mask if self.config.is_encoder_decoder else None
+ attention_mask = (
+ kwargs.pop("decoder_attention_mask", None) if self.config.is_encoder_decoder else attention_mask
+ )
+ attention_mask_key = "decoder_attention_mask" if self.config.is_encoder_decoder else "attention_mask"
+ position_ids_key = "decoder_position_ids" if self.config.is_encoder_decoder else "position_ids"
+ if (
+ attention_mask is not None
+ and kwargs.get(position_ids_key) is None
+ and position_ids_key in set(inspect.signature(self.forward).parameters.keys())
+ ):
+ position_ids = attention_mask.long().cumsum(-1) - 1
+ position_ids.masked_fill_(attention_mask == 0, 1)
+ kwargs[position_ids_key] = position_ids # placed in kwargs for further processing (see below)
+
+ # 5. Slice model inputs if it's an input that should have the same length as `input_ids`
+ for model_input_name in ["position_ids", "token_type_ids", "decoder_position_ids"]:
+ model_input = kwargs.get(model_input_name)
+ if model_input is not None:
+ if past_key_values is not None:
+ current_input_length = (
+ model_inputs["inputs_embeds"].shape[1]
+ if model_inputs.get("inputs_embeds") is not None
+ else model_inputs[input_ids_key].shape[1]
+ )
+ model_input = model_input[:, -current_input_length:]
+ model_input = model_input.clone(memory_format=torch.contiguous_format)
+ model_inputs[model_input_name] = model_input
+
+ # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
+ if model_inputs["inputs_embeds"] is not None:
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
+ device = model_inputs["inputs_embeds"].device
+ else:
+ batch_size, sequence_length = model_inputs[input_ids_key].shape
+ device = model_inputs[input_ids_key].device
+
+ # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create
+ # the 4D causal mask exists, it should be present in the base model (XXXModel class).
+ base_model = getattr(self, self.base_model_prefix, None)
+ if base_model is None:
+ causal_mask_creation_function = getattr(
+ self, "_prepare_4d_causal_attention_mask_with_cache_position", None
+ )
+ else:
+ causal_mask_creation_function = getattr(
+ base_model, "_prepare_4d_causal_attention_mask_with_cache_position", None
+ )
+ if causal_mask_creation_function is None:
+ logger.warning_once(
+ f"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method "
+ "defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're "
+ "writing code, see Llama for an example implementation. If you're a user, please report this "
+ "issue on GitHub."
+ )
+ else:
+ attention_mask = causal_mask_creation_function(
+ attention_mask,
+ sequence_length=sequence_length,
+ target_length=past_key_values.get_max_cache_shape(),
+ dtype=self.dtype,
+ device=device,
+ cache_position=cache_position,
+ batch_size=batch_size,
+ config=self.config,
+ past_key_values=past_key_values,
+ )
+ if attention_mask is not None:
+ model_inputs[attention_mask_key] = attention_mask
+
+ if encoder_attention_mask is not None:
+ model_inputs["attention_mask"] = encoder_attention_mask
+
+ # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
+ for key, value in kwargs.items():
+ if key not in model_inputs:
+ model_inputs[key] = value
+
+ # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)
+ model_inputs.pop("labels", None)
+ return model_inputs
+
+ def _prepare_model_inputs(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ bos_token_id: Optional[torch.Tensor] = None,
+ model_kwargs: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:
+ """
+ This function extracts the model-specific `inputs` for generation.
+ """
+ # 1. retrieve all kwargs that are non-None or non-model input related.
+ # some encoder-decoder models have different names for model and encoder
+ if (
+ self.config.is_encoder_decoder
+ and hasattr(self, "encoder")
+ and self.encoder.main_input_name != self.main_input_name
+ ):
+ input_name = self.encoder.main_input_name
+ else:
+ input_name = self.main_input_name
+
+ model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None or k != input_name}
+
+ # 2. check whether model_input_name is passed as kwarg
+ # if yes and `inputs` is None use kwarg inputs
+ inputs_kwarg = model_kwargs.pop(input_name, None)
+ if inputs_kwarg is not None and inputs is not None:
+ raise ValueError(
+ f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. "
+ f"Make sure to either pass {inputs} or {input_name}=..."
+ )
+ elif inputs_kwarg is not None:
+ inputs = inputs_kwarg
+
+ # 3. In the presence of `inputs_embeds` for text models:
+ # - decoder-only models should complain if the user attempts to pass `inputs_embeds`, but the model
+ # doesn't have its forwarding implemented. `inputs_embeds` is kept in `model_kwargs` and can coexist with
+ # input_ids (`inputs_embeds` will be used in the 1st generation step, as opposed to `input_ids`)
+ # - encoder-decoder models should complain if the user attempts to pass `inputs_embeds` and `input_ids`, and
+ # pull the former to inputs. It will be used in place of `input_ids` to get the encoder hidden states.
+ if input_name == "input_ids" and "inputs_embeds" in model_kwargs:
+ if not self.config.is_encoder_decoder:
+ has_inputs_embeds_forwarding = "inputs_embeds" in set(
+ inspect.signature(self.prepare_inputs_for_generation).parameters.keys()
+ )
+ if not has_inputs_embeds_forwarding:
+ raise ValueError(
+ f"You passed `inputs_embeds` to `.generate()`, but the model class {self.__class__.__name__} "
+ "doesn't have its forwarding implemented. See the GPT2 implementation for an example "
+ "(https://github.com/huggingface/transformers/pull/21405), and feel free to open a PR with it!"
+ )
+ # In this case, `input_ids` is moved to the `model_kwargs`, so a few automations (like the creation of
+ # the attention mask) can rely on the actual model input.
+ model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(
+ inputs, bos_token_id, model_kwargs=model_kwargs
+ )
+ else:
+ if inputs is not None:
+ raise ValueError("You passed `inputs_embeds` and `input_ids` to `.generate()`. Please pick one.")
+ inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
+
+ # 4. if `inputs` is still None, try to create `input_ids` from BOS token
+ inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
+ return inputs, input_name, model_kwargs
+
+ def _maybe_initialize_input_ids_for_generation(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ bos_token_id: Optional[torch.Tensor] = None,
+ model_kwargs: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> torch.LongTensor:
+ """Initializes input ids for generation, if necessary."""
+ if inputs is not None:
+ return inputs
+
+ encoder_outputs = model_kwargs.get("encoder_outputs")
+ if self.config.is_encoder_decoder and encoder_outputs is not None:
+ # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding
+ shape = encoder_outputs.last_hidden_state.size()[:-1]
+ return torch.ones(shape, dtype=torch.long, device=self.device) * -100
+
+ # If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with
+ # soft-prompting or in multimodal implementations built on top of decoder-only language models.
+ batch_size = 1
+ for value in model_kwargs.values():
+ if isinstance(value, torch.Tensor):
+ batch_size = value.shape[0]
+ break
+
+ if "inputs_embeds" in model_kwargs:
+ return torch.ones((batch_size, 0), dtype=torch.long, device=self.device)
+
+ if bos_token_id is None:
+ raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")
+
+ return torch.ones((batch_size, 1), dtype=torch.long, device=self.device) * bos_token_id
+
+ def _prepare_attention_mask_for_generation(
+ self,
+ inputs_tensor: torch.Tensor,
+ generation_config: GenerationConfig,
+ model_kwargs: Dict[str, Any],
+ ) -> torch.LongTensor:
+ pad_token_id = generation_config._pad_token_tensor
+ eos_token_id = generation_config._eos_token_tensor
+
+ # `input_ids` may be present in the model kwargs, instead of being the main input (e.g. multimodal model)
+ if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:
+ inputs_tensor = model_kwargs["input_ids"]
+
+ # No information for attention mask inference -> return default attention mask
+ default_attention_mask = torch.ones(inputs_tensor.shape[:2], dtype=torch.long, device=inputs_tensor.device)
+ if pad_token_id is None:
+ return default_attention_mask
+
+ is_input_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long]
+ if not is_input_ids:
+ return default_attention_mask
+
+ is_pad_token_in_inputs = (pad_token_id is not None) and (
+ isin_mps_friendly(elements=inputs_tensor, test_elements=pad_token_id).any()
+ )
+ is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or ~(
+ isin_mps_friendly(elements=eos_token_id, test_elements=pad_token_id).any()
+ )
+ can_infer_attention_mask = is_pad_token_in_inputs * is_pad_token_not_equal_to_eos_token_id
+ attention_mask_from_padding = inputs_tensor.ne(pad_token_id).long()
+
+ attention_mask = (
+ attention_mask_from_padding * can_infer_attention_mask + default_attention_mask * ~can_infer_attention_mask
+ )
+ return attention_mask
+
+ def _prepare_encoder_decoder_kwargs_for_generation(
+ self,
+ inputs_tensor: torch.Tensor,
+ model_kwargs,
+ model_input_name: Optional[str],
+ generation_config: GenerationConfig,
+ ) -> Dict[str, Any]:
+ # 1. get encoder
+ encoder = self.get_encoder()
+ # Compatibility with Accelerate big model inference: we need the encoder to outputs stuff on the same device
+ # as the inputs.
+ if hasattr(self, "hf_device_map"):
+ if hasattr(encoder, "_hf_hook"):
+ encoder._hf_hook.io_same_device = True
+ else:
+ add_hook_to_module(encoder, AlignDevicesHook(io_same_device=True))
+
+ # 2. Prepare encoder args and encoder kwargs from model kwargs and generation config.
+ irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"]
+ encoder_kwargs = {
+ argument: value
+ for argument, value in model_kwargs.items()
+ if not any(argument.startswith(p) for p in irrelevant_prefix)
+ }
+ encoder_signature = set(inspect.signature(encoder.forward).parameters)
+ encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature
+ if not encoder_accepts_wildcard:
+ encoder_kwargs = {
+ argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature
+ }
+ encoder_kwargs["output_attentions"] = generation_config.output_attentions
+ encoder_kwargs["output_hidden_states"] = generation_config.output_hidden_states
+
+ # 3. make sure that encoder returns `ModelOutput`
+ model_input_name = model_input_name if model_input_name is not None else self.main_input_name
+ encoder_kwargs["return_dict"] = True
+ encoder_kwargs[model_input_name] = inputs_tensor
+ model_kwargs["encoder_outputs"]: ModelOutput = encoder(**encoder_kwargs) # type: ignore
+
+ return model_kwargs
+
+ def _prepare_decoder_input_ids_for_generation(
+ self,
+ batch_size: int,
+ model_input_name: str,
+ model_kwargs: Dict[str, torch.Tensor],
+ decoder_start_token_id: torch.Tensor,
+ device: torch.device = None,
+ ) -> Tuple[torch.LongTensor, Dict[str, torch.Tensor]]:
+ """Prepares `decoder_input_ids` for generation with encoder-decoder models"""
+ # 1. Check whether the user has defined `decoder_input_ids` manually. To facilitate in terms of input naming,
+ # we also allow the user to pass it under `input_ids`, if the encoder does not use it as the main input.
+ if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
+ decoder_input_ids = model_kwargs.pop("decoder_input_ids")
+ elif "input_ids" in model_kwargs and model_input_name != "input_ids":
+ decoder_input_ids = model_kwargs.pop("input_ids")
+ else:
+ decoder_input_ids = None
+
+ # 2. `decoder_start_token_id` must have shape (batch_size, 1)
+ if device is None:
+ device = self.device
+ if decoder_start_token_id.ndim == 1:
+ if decoder_start_token_id.shape[0] != batch_size:
+ raise ValueError(
+ f"`decoder_start_token_id` expected to have length {batch_size} but got {decoder_start_token_id.shape[0]}"
+ )
+ decoder_start_token_id = decoder_start_token_id.view(-1, 1)
+ else:
+ decoder_start_token_id = (
+ torch.ones((batch_size, 1), dtype=torch.long, device=device) * decoder_start_token_id
+ )
+
+ # 3. Encoder-decoder models expect the `decoder_input_ids` to start with a special token. Let's ensure that.
+ # no user input -> use decoder_start_token_id as decoder_input_ids
+ if decoder_input_ids is None:
+ decoder_input_ids = decoder_start_token_id
+ # exception: Donut checkpoints have task-specific decoder starts and don't expect a BOS token. Note that the
+ # original checkpoints can't be detected through `self.__class__.__name__.lower()`, needing custom logic.
+ # See: https://github.com/huggingface/transformers/pull/31470
+ elif "donut" in self.__class__.__name__.lower() or (
+ self.config.model_type == "vision-encoder-decoder" and "donut" in self.config.encoder.model_type.lower()
+ ):
+ pass
+ elif self.config.model_type in ["whisper"]:
+ pass
+ # user input but doesn't start with decoder_start_token_id -> prepend decoder_start_token_id (and adjust
+ # decoder_attention_mask if provided)
+ elif (decoder_input_ids[:, 0] != decoder_start_token_id[:, 0]).all().item():
+ decoder_input_ids = torch.cat([decoder_start_token_id, decoder_input_ids], dim=-1)
+ if "decoder_attention_mask" in model_kwargs:
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
+ decoder_attention_mask = torch.cat(
+ (torch.ones_like(decoder_attention_mask)[:, :1], decoder_attention_mask),
+ dim=-1,
+ )
+ model_kwargs["decoder_attention_mask"] = decoder_attention_mask
+
+ return decoder_input_ids, model_kwargs
+
+ @staticmethod
+ def _expand_inputs_for_generation(
+ expand_size: int = 1,
+ is_encoder_decoder: bool = False,
+ input_ids: Optional[torch.LongTensor] = None,
+ **model_kwargs,
+ ) -> Tuple[torch.LongTensor, Dict[str, Any]]:
+ """Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...]"""
+ # Do not call torch.repeat_interleave if expand_size is 1 because it clones
+ # the input tensor and thus requires more memory although no change is applied
+ if expand_size == 1:
+ return input_ids, model_kwargs
+
+ def _expand_dict_for_generation(dict_to_expand):
+ for key in dict_to_expand:
+ if (
+ key != "cache_position"
+ and dict_to_expand[key] is not None
+ and isinstance(dict_to_expand[key], torch.Tensor)
+ ):
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
+ return dict_to_expand
+
+ if input_ids is not None:
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
+
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
+
+ if is_encoder_decoder:
+ if model_kwargs.get("encoder_outputs") is None:
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
+
+ return input_ids, model_kwargs
+
+ def _update_model_kwargs_for_generation(
+ self,
+ outputs: ModelOutput,
+ model_kwargs: Dict[str, Any],
+ is_encoder_decoder: bool = False,
+ num_new_tokens: int = 1,
+ ) -> Dict[str, Any]:
+ # update past_key_values keeping its naming used in model code
+ for possible_cache_name in ALL_CACHE_NAMES:
+ if possible_cache_name in outputs:
+ # TODO (joao): remove output/input mismatch when these old models (xlnet, reformer) are deprecated
+ if possible_cache_name in ("past_buckets_states", "mems"):
+ cache_name = "past_key_values"
+ else:
+ cache_name = possible_cache_name
+ model_kwargs[cache_name] = getattr(outputs, possible_cache_name)
+ break
+
+ # update token_type_ids with last value
+ if "token_type_ids" in model_kwargs:
+ token_type_ids = model_kwargs["token_type_ids"]
+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)
+
+ if not is_encoder_decoder:
+ # update attention mask
+ if "attention_mask" in model_kwargs:
+ attention_mask = model_kwargs["attention_mask"]
+ model_kwargs["attention_mask"] = torch.cat(
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
+ )
+ else:
+ # update decoder attention mask
+ if "decoder_attention_mask" in model_kwargs:
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
+ model_kwargs["decoder_attention_mask"] = torch.cat(
+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
+ dim=-1,
+ )
+
+ if model_kwargs.get("use_cache", True):
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
+ else:
+ past_positions = model_kwargs.pop("cache_position")
+ new_positions = torch.arange(
+ past_positions[-1] + 1, past_positions[-1] + num_new_tokens + 1, dtype=past_positions.dtype
+ ).to(past_positions.device)
+ model_kwargs["cache_position"] = torch.cat((past_positions, new_positions))
+ return model_kwargs
+
+ def _reorder_cache(self, past_key_values, beam_idx):
+ raise NotImplementedError(
+ f"Make sure that a `_reorder_cache` function is correctly implemented in {self.__class__.__module__} to"
+ f" enable beam search for {self.__class__}"
+ )
+
+ def _get_candidate_generator(
+ self,
+ generation_config: GenerationConfig,
+ input_ids: torch.LongTensor,
+ inputs_tensor: torch.Tensor,
+ assistant_model: "PreTrainedModel",
+ logits_processor: LogitsProcessorList,
+ target_tokenizer: "PreTrainedTokenizerBase",
+ assistant_tokenizer: "PreTrainedTokenizerBase",
+ model_kwargs: Dict,
+ ) -> CandidateGenerator:
+ """
+ Returns the candidate generator to be used in `assisted_generation`
+ """
+ different_tokenizers = all(v is not None for v in (assistant_model, target_tokenizer, assistant_tokenizer))
+
+ if generation_config.assistant_early_exit is not None:
+ candidate_generator = EarlyExitCandidateGenerator(
+ input_ids=input_ids,
+ assistant_model=self,
+ generation_config=generation_config,
+ model_kwargs=model_kwargs,
+ inputs_tensor=inputs_tensor,
+ logits_processor=logits_processor,
+ )
+ elif generation_config.prompt_lookup_num_tokens is not None:
+ candidate_generator = PromptLookupCandidateGenerator(
+ eos_token_id=generation_config._eos_token_tensor,
+ num_output_tokens=generation_config.prompt_lookup_num_tokens,
+ max_matching_ngram_size=generation_config.max_matching_ngram_size,
+ max_length=generation_config.max_length,
+ )
+ elif different_tokenizers:
+ if generation_config.do_sample is True:
+ atm_translator = AssistantVocabTranslatorCache.get_translator(
+ target_tokenizer, assistant_tokenizer, self.config.vocab_size, assistant_model.device
+ )
+ candidate_generator = UniversalSpeculativeDecodingGenerator(
+ input_ids=input_ids,
+ assistant_model=assistant_model,
+ generation_config=generation_config,
+ model_kwargs=model_kwargs,
+ inputs_tensor=inputs_tensor,
+ logits_processor=logits_processor,
+ target_tokenizer=target_tokenizer,
+ assistant_tokenizer=assistant_tokenizer,
+ atm_translator=atm_translator,
+ )
+ elif generation_config.do_sample is False:
+ candidate_generator = AssistedCandidateGeneratorDifferentTokenizers(
+ input_ids=input_ids,
+ assistant_model=assistant_model,
+ generation_config=generation_config,
+ model_kwargs=model_kwargs,
+ inputs_tensor=inputs_tensor,
+ logits_processor=logits_processor,
+ target_tokenizer=target_tokenizer,
+ assistant_tokenizer=assistant_tokenizer,
+ )
+ else:
+ raise ValueError(
+ f"Invalid value for `do_sample`: expected a boolean, got {type(generation_config.do_sample).__name__}"
+ )
+ else:
+ candidate_generator = AssistedCandidateGenerator(
+ input_ids=input_ids,
+ assistant_model=assistant_model,
+ generation_config=generation_config,
+ model_kwargs=model_kwargs,
+ inputs_tensor=inputs_tensor,
+ logits_processor=logits_processor,
+ )
+ return candidate_generator
+
+ def _get_logits_processor(
+ self,
+ generation_config: GenerationConfig,
+ input_ids_seq_length: int,
+ encoder_input_ids: torch.LongTensor,
+ prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]],
+ logits_processor: Optional[LogitsProcessorList],
+ device: str = None,
+ model_kwargs: Optional[Dict[str, Any]] = None,
+ negative_prompt_ids: Optional[torch.Tensor] = None,
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
+ ) -> LogitsProcessorList:
+ """
+ This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsProcessor`]
+ instances used to modify the scores of the language model head.
+ """
+ # instantiate processors list
+ processors = LogitsProcessorList()
+
+ if generation_config.guidance_scale is not None and generation_config.guidance_scale != 1:
+ processors.append(
+ UnbatchedClassifierFreeGuidanceLogitsProcessor(
+ generation_config.guidance_scale,
+ self,
+ unconditional_ids=negative_prompt_ids,
+ unconditional_attention_mask=negative_prompt_attention_mask,
+ use_cache=generation_config.use_cache,
+ )
+ )
+ if generation_config.sequence_bias is not None:
+ processors.append(SequenceBiasLogitsProcessor(sequence_bias=generation_config.sequence_bias))
+
+ if generation_config.diversity_penalty is not None and generation_config.diversity_penalty > 0.0:
+ processors.append(
+ HammingDiversityLogitsProcessor(
+ diversity_penalty=generation_config.diversity_penalty,
+ num_beams=generation_config.num_beams,
+ num_beam_groups=generation_config.num_beam_groups,
+ )
+ )
+ if (
+ generation_config.encoder_repetition_penalty is not None
+ and generation_config.encoder_repetition_penalty != 1.0
+ ):
+ if len(encoder_input_ids.shape) == 2:
+ processors.append(
+ EncoderRepetitionPenaltyLogitsProcessor(
+ penalty=generation_config.encoder_repetition_penalty,
+ encoder_input_ids=encoder_input_ids,
+ )
+ )
+ else:
+ warnings.warn(
+ "Passing `encoder_repetition_penalty` requires some form of `input_ids` to be passed to "
+ "`generate`, ignoring the argument.",
+ UserWarning,
+ )
+ if generation_config.repetition_penalty is not None and generation_config.repetition_penalty != 1.0:
+ processors.append(RepetitionPenaltyLogitsProcessor(penalty=generation_config.repetition_penalty))
+ if generation_config.no_repeat_ngram_size is not None and generation_config.no_repeat_ngram_size > 0:
+ processors.append(NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size))
+ if (
+ generation_config.encoder_no_repeat_ngram_size is not None
+ and generation_config.encoder_no_repeat_ngram_size > 0
+ ):
+ if len(encoder_input_ids.shape) == 2:
+ processors.append(
+ EncoderNoRepeatNGramLogitsProcessor(
+ generation_config.encoder_no_repeat_ngram_size,
+ encoder_input_ids,
+ )
+ )
+ else:
+ warnings.warn(
+ "Passing `encoder_no_repeat_ngram_size` requires some form of `input_ids` to be passed to "
+ "`generate`, ignoring the argument.",
+ UserWarning,
+ )
+ if generation_config.bad_words_ids is not None:
+ processors.append(
+ NoBadWordsLogitsProcessor(
+ generation_config.bad_words_ids,
+ generation_config._eos_token_tensor,
+ )
+ )
+ if (
+ generation_config.min_length is not None
+ and generation_config._eos_token_tensor is not None
+ and generation_config.min_length > 0
+ ):
+ processors.append(
+ MinLengthLogitsProcessor(
+ generation_config.min_length,
+ generation_config._eos_token_tensor,
+ device=device,
+ )
+ )
+ if (
+ generation_config.min_new_tokens is not None
+ and generation_config._eos_token_tensor is not None
+ and generation_config.min_new_tokens > 0
+ ):
+ processors.append(
+ MinNewTokensLengthLogitsProcessor(
+ input_ids_seq_length,
+ generation_config.min_new_tokens,
+ generation_config._eos_token_tensor,
+ device=device,
+ )
+ )
+ if prefix_allowed_tokens_fn is not None:
+ processors.append(
+ PrefixConstrainedLogitsProcessor(
+ prefix_allowed_tokens_fn,
+ generation_config.num_beams // generation_config.num_beam_groups,
+ )
+ )
+ if generation_config.forced_bos_token_id is not None:
+ processors.append(
+ ForcedBOSTokenLogitsProcessor(
+ generation_config.forced_bos_token_id,
+ )
+ )
+ if generation_config.forced_eos_token_id is not None:
+ processors.append(
+ ForcedEOSTokenLogitsProcessor(
+ generation_config.max_length,
+ generation_config.forced_eos_token_id,
+ device=device,
+ )
+ )
+ if generation_config.remove_invalid_values is True:
+ processors.append(InfNanRemoveLogitsProcessor())
+ if generation_config.exponential_decay_length_penalty is not None:
+ processors.append(
+ ExponentialDecayLengthPenalty(
+ generation_config.exponential_decay_length_penalty,
+ generation_config._eos_token_tensor,
+ input_ids_seq_length,
+ )
+ )
+ if generation_config.suppress_tokens is not None:
+ processors.append(
+ SuppressTokensLogitsProcessor(
+ generation_config.suppress_tokens,
+ device=device,
+ )
+ )
+ if generation_config.begin_suppress_tokens is not None:
+ begin_index = input_ids_seq_length
+ begin_index = (
+ begin_index
+ if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
+ else begin_index + 1
+ )
+ processors.append(
+ SuppressTokensAtBeginLogitsProcessor(
+ generation_config.begin_suppress_tokens,
+ begin_index,
+ device=device,
+ )
+ )
+ if generation_config.forced_decoder_ids is not None:
+ # TODO (sanchit): move this exception to GenerationConfig.validate() when TF & FLAX are aligned with PT
+ raise ValueError(
+ "You have explicitly specified `forced_decoder_ids`. Please remove the `forced_decoder_ids` argument "
+ "in favour of `input_ids` or `decoder_input_ids` respectively.",
+ )
+
+ # TODO (joao): find a strategy to specify the order of the processors
+ processors = self._merge_criteria_processor_list(processors, logits_processor)
+
+ # Processors previously known as `LogitsWarpers`, only applied with sampling strategies
+ if generation_config.do_sample:
+ # In beam methods, we need to keep at least one non-eos token to explore continuations that might have a
+ # better score (i.e. keep len(list(generation_config._eos_token_tensor)) + 1)
+ if generation_config.num_beams > 1:
+ if isinstance(generation_config._eos_token_tensor, list):
+ min_tokens_to_keep = len(generation_config._eos_token_tensor) + 1
+ elif isinstance(generation_config._eos_token_tensor, torch.Tensor):
+ min_tokens_to_keep = generation_config._eos_token_tensor.shape[0] + 1
+ else:
+ min_tokens_to_keep = 2
+ else:
+ min_tokens_to_keep = 1
+
+ # the following idea is largely copied from this PR: https://github.com/huggingface/transformers/pull/5420/files
+ # all samplers can be found in `generation_utils_samplers.py`
+ if generation_config.temperature is not None and generation_config.temperature != 1.0:
+ processors.append(TemperatureLogitsWarper(generation_config.temperature))
+ if generation_config.top_k is not None and generation_config.top_k != 0:
+ processors.append(
+ TopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=min_tokens_to_keep)
+ )
+ if generation_config.top_p is not None and generation_config.top_p < 1.0:
+ processors.append(
+ TopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=min_tokens_to_keep)
+ )
+ if generation_config.min_p is not None:
+ # Applied after temperature scaling (see https://github.com/ggerganov/llama.cpp/pull/3841#issuecomment-2073826084)
+ processors.append(
+ MinPLogitsWarper(min_p=generation_config.min_p, min_tokens_to_keep=min_tokens_to_keep)
+ )
+ if generation_config.typical_p is not None and generation_config.typical_p < 1.0:
+ processors.append(
+ TypicalLogitsWarper(mass=generation_config.typical_p, min_tokens_to_keep=min_tokens_to_keep)
+ )
+ if generation_config.epsilon_cutoff is not None and 0.0 < generation_config.epsilon_cutoff < 1.0:
+ processors.append(
+ EpsilonLogitsWarper(
+ epsilon=generation_config.epsilon_cutoff, min_tokens_to_keep=min_tokens_to_keep
+ )
+ )
+ if generation_config.eta_cutoff is not None and 0.0 < generation_config.eta_cutoff < 1.0:
+ processors.append(
+ EtaLogitsWarper(
+ epsilon=generation_config.eta_cutoff, min_tokens_to_keep=min_tokens_to_keep, device=device
+ )
+ )
+
+ # Watermarking should be after all logits processing is finished (see #34630)
+ if generation_config.watermarking_config is not None:
+ processors.append(
+ generation_config.watermarking_config.construct_processor(self.config.vocab_size, device)
+ )
+
+ # `LogitNormalization` should always be the last logit processor, when present
+ if generation_config.renormalize_logits is True:
+ processors.append(LogitNormalization())
+ return processors
+
+ def _get_stopping_criteria(
+ self,
+ generation_config: GenerationConfig,
+ stopping_criteria: Optional[StoppingCriteriaList],
+ tokenizer: Optional["PreTrainedTokenizerBase"] = None,
+ **kwargs,
+ ) -> StoppingCriteriaList:
+ criteria = StoppingCriteriaList()
+ if generation_config.max_length is not None:
+ max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
+ criteria.append(
+ MaxLengthCriteria(
+ max_length=generation_config.max_length,
+ max_position_embeddings=max_position_embeddings,
+ )
+ )
+ if generation_config.max_time is not None:
+ criteria.append(MaxTimeCriteria(max_time=generation_config.max_time))
+ if generation_config.stop_strings is not None:
+ if tokenizer is None:
+ raise ValueError(
+ "There are one or more stop strings, either in the arguments to `generate` or in the "
+ "model's generation config, but we could not locate a tokenizer. When generating with "
+ "stop strings, you must pass the model's tokenizer to the `tokenizer` argument of `generate`."
+ )
+ criteria.append(StopStringCriteria(stop_strings=generation_config.stop_strings, tokenizer=tokenizer))
+ if generation_config._eos_token_tensor is not None:
+ criteria.append(EosTokenCriteria(eos_token_id=generation_config._eos_token_tensor))
+ if (
+ generation_config.is_assistant
+ and generation_config.assistant_confidence_threshold is not None
+ and generation_config.assistant_confidence_threshold > 0
+ ):
+ criteria.append(
+ ConfidenceCriteria(assistant_confidence_threshold=generation_config.assistant_confidence_threshold)
+ )
+ criteria = self._merge_criteria_processor_list(criteria, stopping_criteria)
+ return criteria
+
+ def _merge_criteria_processor_list(
+ self,
+ default_list: Union[LogitsProcessorList, StoppingCriteriaList],
+ custom_list: Union[LogitsProcessorList, StoppingCriteriaList],
+ ) -> Union[LogitsProcessorList, StoppingCriteriaList]:
+ if len(custom_list) == 0:
+ return default_list
+ for default in default_list:
+ for custom in custom_list:
+ if type(custom) is type(default):
+ object_type = "stopping criteria" if isinstance(custom, StoppingCriteria) else "logits processor"
+ raise ValueError(
+ f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"
+ f" `.generate()`, but it has already been created with the values {default}. {default} has been"
+ " created by passing the corresponding arguments to generate or by the model's config default"
+ f" values. If you just want to change the default values of {object_type} consider passing"
+ f" them as arguments to `.generate()` instead of using a custom {object_type}."
+ )
+ default_list.extend(custom_list)
+ return default_list
+
+ 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 scores (and beam indices, if beam search was
+ used). This is a convenient method to quicky obtain the scores of the selected tokens at generation time.
+
+ Parameters:
+ sequences (`torch.LongTensor`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or
+ shorter if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(torch.FloatTensor)`):
+ Transition scores for each vocabulary token at each generation step. Beam transition scores consisting
+ of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
+ Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
+ beam_indices (`torch.LongTensor`, *optional*):
+ Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at
+ generate-time.
+ normalize_logits (`bool`, *optional*, defaults to `False`):
+ Whether to normalize the logits (which, for legacy reasons, may be unnormalized).
+
+ Return:
+ `torch.Tensor`: A `torch.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing
+ the transition scores (logits)
+
+ Examples:
+
+ ```python
+ >>> from transformers import GPT2Tokenizer, AutoModelForCausalLM
+ >>> import numpy as np
+
+ >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> tokenizer.pad_token_id = tokenizer.eos_token_id
+ >>> inputs = tokenizer(["Today is"], return_tensors="pt")
+
+ >>> # Example 1: Print the scores for each token generated with Greedy Search
+ >>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
+ >>> transition_scores = model.compute_transition_scores(
+ ... outputs.sequences, outputs.scores, normalize_logits=True
+ ... )
+ >>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
+ >>> # encoder-decoder models, like BART or T5.
+ >>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
+ >>> generated_tokens = outputs.sequences[:, input_length:]
+ >>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
+ ... # | token | token string | log probability | probability
+ ... print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
+ | 262 | the | -1.414 | 24.33%
+ | 1110 | day | -2.609 | 7.36%
+ | 618 | when | -2.010 | 13.40%
+ | 356 | we | -1.859 | 15.58%
+ | 460 | can | -2.508 | 8.14%
+
+ >>> # Example 2: Reconstruct the sequence scores from Beam Search
+ >>> outputs = model.generate(
+ ... **inputs,
+ ... max_new_tokens=5,
+ ... num_beams=4,
+ ... num_return_sequences=4,
+ ... return_dict_in_generate=True,
+ ... output_scores=True,
+ ... )
+ >>> transition_scores = model.compute_transition_scores(
+ ... outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
+ ... )
+ >>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
+ >>> # Tip 1: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
+ >>> # use case, you might want to recompute it with `normalize_logits=True`.
+ >>> # Tip 2: the output length does NOT include the input length
+ >>> output_length = np.sum(transition_scores.numpy() < 0, axis=1)
+ >>> length_penalty = model.generation_config.length_penalty
+ >>> reconstructed_scores = transition_scores.sum(axis=1) / (output_length**length_penalty)
+ >>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
+ True
+ ```"""
+ # 1. In absence of `beam_indices`, we can assume that we come from e.g. greedy search, which is equivalent
+ # to a beam search approach were the first (and only) beam is always selected
+ if beam_indices is None:
+ beam_indices = torch.arange(scores[0].shape[0]).view(-1, 1).to(sequences.device)
+ beam_indices = beam_indices.expand(-1, len(scores))
+
+ # 2. reshape scores as [batch_size*vocab_size, # generation steps] with # generation steps being
+ # seq_len - input_length
+ scores = torch.stack(scores).reshape(len(scores), -1).transpose(0, 1)
+
+ # 3. Optionally normalize the logits (across the vocab dimension)
+ if normalize_logits:
+ scores = scores.reshape(-1, self.config.vocab_size, scores.shape[-1])
+ scores = torch.nn.functional.log_softmax(scores, dim=1)
+ scores = scores.reshape(-1, scores.shape[-1])
+
+ # 4. cut beam_indices to longest beam length
+ beam_indices_mask = beam_indices < 0
+ max_beam_length = (1 - beam_indices_mask.long()).sum(-1).max()
+ beam_indices = beam_indices.clone()[:, :max_beam_length]
+ beam_indices_mask = beam_indices_mask[:, :max_beam_length]
+
+ # 5. Set indices of beams that finished early to 0; such indices will be masked correctly afterwards
+ beam_indices[beam_indices_mask] = 0
+
+ # 6. multiply beam_indices with vocab size to gather correctly from scores
+ beam_sequence_indices = beam_indices * self.config.vocab_size
+
+ # 7. Define which indices contributed to scores
+ cut_idx = sequences.shape[-1] - max_beam_length
+ indices = sequences[:, cut_idx:] + beam_sequence_indices
+
+ # 8. Compute scores
+ transition_scores = scores.gather(0, indices)
+
+ # 9. Mask out transition_scores of beams that stopped early
+ transition_scores[beam_indices_mask] = 0
+
+ return transition_scores
+
+ def _validate_model_class(self):
+ """
+ Confirms that the model class is compatible with generation. If not, raises an exception that points to the
+ right class to use.
+ """
+ # TODO(joao): remove this function in v4.50, i.e. when we remove the inheritance of `GenerationMixin` from
+ # `PreTrainedModel`. With that inheritance removed, all model classes inheriting from `GenerationMixin` can
+ # safely call `GenerationMixin.generate`
+ if not is_torchdynamo_compiling() and not self.can_generate():
+ terminations_with_generation_support = [
+ "ForCausalLM",
+ "ForConditionalGeneration",
+ "ForSpeechSeq2Seq",
+ "ForVision2Seq",
+ ]
+ raise TypeError(
+ f"The current model class ({self.__class__.__name__}) is not compatible with `.generate()`, as "
+ "it doesn't have a language model head. Classes that support generation often end in one of these "
+ f"names: {terminations_with_generation_support}."
+ )
+
+ def _validate_assistant(self, assistant_model, tokenizer, assistant_tokenizer):
+ if assistant_model is None:
+ return
+
+ if self.config.is_encoder_decoder and not assistant_model.config.is_encoder_decoder:
+ attributes_to_check = ["encoder_attention_heads", "encoder_ffn_dim", "encoder_layers"]
+ attributes_to_check = [attr for attr in dir(assistant_model.config) if attr in attributes_to_check]
+ are_equal = all(
+ getattr(self.config, attr) == getattr(assistant_model.config, attr) for attr in attributes_to_check
+ )
+ if not are_equal:
+ raise ValueError(
+ "The main model and the assistant don't have compatible encoder-dependent input shapes. "
+ "Ensure you load the assistant with the correct encoder-decoder class, e.g. `AutoModelForSpeechSeq2Seq` for Whisper."
+ )
+
+ doc_reference = (
+ "(see https://huggingface.co/docs/transformers/en/generation_strategies#universal-assisted-decoding)"
+ )
+ if self.config.get_text_config().vocab_size == assistant_model.config.get_text_config().vocab_size:
+ if assistant_tokenizer is not None:
+ raise ValueError(
+ f"`assistant_tokenizer` is not required when the main and assistant models use the same tokenizer. Please omit `assistant_tokenizer` from `generate()` {doc_reference}."
+ )
+ else:
+ if tokenizer is None or assistant_tokenizer is None:
+ raise ValueError(
+ f"The main and assistant moedels have different tokenizers. Please provide `tokenizer` and `assistant_tokenizer` to `generate()` {doc_reference}."
+ )
+
+ def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
+ """Validates model kwargs for generation. Generate argument typos will also be caught here."""
+ # If a `Cache` instance is passed, checks whether the model is compatible with it
+ if isinstance(model_kwargs.get("past_key_values", None), Cache) and not self._supports_cache_class:
+ raise ValueError(
+ f"{self.__class__.__name__} does not support an instance of `Cache` as `past_key_values`. Please "
+ "check the model documentation for supported cache formats."
+ )
+
+ # Excludes arguments that are handled before calling any model function
+ if self.config.is_encoder_decoder:
+ for key in ["decoder_input_ids"]:
+ model_kwargs.pop(key, None)
+
+ unused_model_args = []
+ model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)
+ # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If
+ # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
+ if "kwargs" in model_args or "model_kwargs" in model_args:
+ model_args |= set(inspect.signature(self.forward).parameters)
+
+ # Encoder-Decoder models may also need Encoder arguments from `model_kwargs`
+ if self.config.is_encoder_decoder:
+ base_model = getattr(self, self.base_model_prefix, None)
+
+ # allow encoder kwargs
+ encoder = getattr(self, "encoder", None)
+ # `MusicgenForConditionalGeneration` has `text_encoder` and `audio_encoder`.
+ # Also, it has `base_model_prefix = "encoder_decoder"` but there is no `self.encoder_decoder`
+ # TODO: A better way to handle this.
+ if encoder is None and base_model is not None:
+ encoder = getattr(base_model, "encoder", None)
+
+ if encoder is not None:
+ encoder_model_args = set(inspect.signature(encoder.forward).parameters)
+ model_args |= encoder_model_args
+
+ # allow decoder kwargs
+ decoder = getattr(self, "decoder", None)
+ if decoder is None and base_model is not None:
+ decoder = getattr(base_model, "decoder", None)
+
+ if decoder is not None:
+ decoder_model_args = set(inspect.signature(decoder.forward).parameters)
+ model_args |= {f"decoder_{x}" for x in decoder_model_args}
+
+ for key, value in model_kwargs.items():
+ if value is not None and key not in model_args:
+ unused_model_args.append(key)
+
+ if unused_model_args:
+ raise ValueError(
+ f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"
+ " generate arguments will also show up in this list)"
+ )
+
+ def _validate_generated_length(self, generation_config, input_ids_length, has_default_max_length):
+ """Performs validation related to the resulting generated length"""
+
+ # Can't throw warnings/exceptions during compilation
+ if is_torchdynamo_compiling():
+ return
+
+ # 1. Max length warnings related to poor parameterization
+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
+ # 20 is the default max_length of the generation config
+ warnings.warn(
+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the "
+ "generation length. We recommend setting `max_new_tokens` to control the maximum length of the "
+ "generation.",
+ UserWarning,
+ )
+ if input_ids_length >= generation_config.max_length:
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
+ raise ValueError(
+ f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
+ " increasing `max_length` or, better yet, setting `max_new_tokens`."
+ )
+
+ # 2. Min length warnings due to unfeasible parameter combinations
+ min_length_error_suffix = (
+ " Generation will stop at the defined maximum length. You should decrease the minimum length and/or "
+ "increase the maximum length."
+ )
+ if has_default_max_length:
+ min_length_error_suffix += (
+ f" Note that `max_length` is set to {generation_config.max_length}, its default value."
+ )
+ if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
+ warnings.warn(
+ f"Unfeasible length constraints: `min_length` ({generation_config.min_length}) is larger than"
+ f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
+ UserWarning,
+ )
+ if generation_config.min_new_tokens is not None:
+ min_length = generation_config.min_new_tokens + input_ids_length
+ if min_length > generation_config.max_length:
+ warnings.warn(
+ f"Unfeasible length constraints: `min_new_tokens` ({generation_config.min_new_tokens}), when "
+ f"added to the prompt length ({input_ids_length}), is larger than"
+ f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
+ UserWarning,
+ )
+
+ def _prepare_generated_length(
+ self,
+ generation_config,
+ has_default_max_length,
+ has_default_min_length,
+ model_input_name,
+ input_ids_length,
+ inputs_tensor,
+ ):
+ """Prepared max and min length in generation configs to avoid clashes between similar attributes"""
+
+ if generation_config.max_new_tokens is not None:
+ if not has_default_max_length and generation_config.max_length is not None:
+ logger.warning(
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
+ "Please refer to the documentation for more information. "
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
+ )
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_length
+
+ # if both `inputs_embeds` and `input_ids` are passed, we do not correct the length
+ # otherwise we need total length [inputs-embeds-len + new-tokens-len] to not go beyond indicated `max_length``
+ elif (
+ model_input_name == "inputs_embeds"
+ and input_ids_length != inputs_tensor.shape[1]
+ and not self.config.is_encoder_decoder
+ ):
+ generation_config.max_length -= inputs_tensor.shape[1]
+ elif has_default_max_length: # by default let's always generate 20 new tokens
+ if generation_config.max_length == GenerationConfig().max_length:
+ generation_config.max_length = generation_config.max_length + input_ids_length
+ max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
+ if max_position_embeddings is not None:
+ generation_config.max_length = min(generation_config.max_length, max_position_embeddings)
+
+ # same for min length
+ if generation_config.min_new_tokens is not None:
+ if not has_default_min_length:
+ logger.warning(
+ f"Both `min_new_tokens` (={generation_config.min_new_tokens}) and `min_length`(="
+ f"{generation_config.min_length}) seem to have been set. `min_new_tokens` will take precedence. "
+ "Please refer to the documentation for more information. "
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
+ )
+ generation_config.min_length = generation_config.min_new_tokens + input_ids_length
+
+ elif (
+ model_input_name == "inputs_embeds"
+ and input_ids_length != inputs_tensor.shape[1]
+ and not self.config.is_encoder_decoder
+ ):
+ generation_config.min_length = max(generation_config.min_length - inputs_tensor.shape[1], 0)
+
+ return generation_config
+
+ def _prepare_generation_config(
+ self, generation_config: Optional[GenerationConfig], **kwargs: Dict
+ ) -> Tuple[GenerationConfig, Dict]:
+ """
+ Prepares the base generation config, then applies any generation configuration options from kwargs. This
+ function handles retrocompatibility with respect to configuration files.
+ """
+ # TODO joao: when we can detect `fullgraph=True` in `torch.compile` (https://github.com/pytorch/pytorch/pull/120400)
+ # replace `is_torchdynamo_compiling` by the corresponding check. As it is, we are being too restrictive with
+ # the parameterization in `fullgraph=False` so as to enable `fullgraph=True`.
+
+ # priority: `generation_config` argument > `model.generation_config` (the default generation config)
+ using_model_generation_config = False
+ if generation_config is None:
+ # legacy: users may modify the model configuration to control generation. To trigger this legacy behavior,
+ # the following conditions must be met
+ # 1) the generation config must have been created from the model config (`_from_model_config` field);
+ # 2) the generation config must have seen no modification since its creation (the hash is the same);
+ # 3) there are non-default generation parameters in the model config.
+ # 4) the user must have set new generation parameters in the model config.
+ # NOTE: `torch.compile` can't compile `hash`, this legacy support is disabled with compilation.
+ if (
+ not is_torchdynamo_compiling()
+ and self.generation_config._from_model_config # 1)
+ and self.generation_config._original_object_hash == hash(self.generation_config) # 2)
+ and len(self.config._get_non_default_generation_parameters()) > 0 # 3)
+ ):
+ new_generation_config = GenerationConfig.from_model_config(self.config)
+ if new_generation_config != self.generation_config: # 4)
+ warnings.warn(
+ "You have modified the pretrained model configuration to control generation. This is a"
+ " deprecated strategy to control generation and will be removed in v5."
+ " Please use and modify the model generation configuration (see"
+ " https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )",
+ UserWarning,
+ )
+ self.generation_config = new_generation_config
+
+ generation_config = self.generation_config
+ using_model_generation_config = True
+
+ # `torch.compile` can't compile `copy.deepcopy`, arguments in `kwargs` that are part of `generation_config`
+ # will mutate the object with `.update`. As such, passing these arguments through `kwargs` is disabled -- an
+ # exception will be raised in `_validate_model_kwargs`
+ if not is_torchdynamo_compiling():
+ generation_config = copy.deepcopy(generation_config)
+ model_kwargs = generation_config.update(**kwargs)
+ # If `generation_config` is provided, let's fallback ALL special tokens to the default values for the model
+ if not using_model_generation_config:
+ if generation_config.bos_token_id is None:
+ generation_config.bos_token_id = self.generation_config.bos_token_id
+ if generation_config.eos_token_id is None:
+ generation_config.eos_token_id = self.generation_config.eos_token_id
+ if generation_config.pad_token_id is None:
+ generation_config.pad_token_id = self.generation_config.pad_token_id
+ if generation_config.decoder_start_token_id is None:
+ generation_config.decoder_start_token_id = self.generation_config.decoder_start_token_id
+ else:
+ model_kwargs = kwargs
+
+ return generation_config, model_kwargs
+
+ def _get_initial_cache_position(self, input_ids, model_kwargs):
+ """Calculates `cache_position` for the pre-fill stage based on `input_ids` and optionally past length"""
+ # `torch.compile`-friendly `torch.arange` from a shape -- the lines below are equivalent to `torch.arange`
+ if "inputs_embeds" in model_kwargs and not self.config.is_encoder_decoder:
+ cache_position = torch.ones_like(model_kwargs["inputs_embeds"][0, :, 0], dtype=torch.int64).cumsum(0) - 1
+ elif "decoder_inputs_embeds" in model_kwargs and self.config.is_encoder_decoder:
+ cache_position = (
+ torch.ones_like(model_kwargs["decoder_inputs_embeds"][0, :, 0], dtype=torch.int64).cumsum(0) - 1
+ )
+ else:
+ cache_position = torch.ones_like(input_ids[0, :], dtype=torch.int64).cumsum(0) - 1
+
+ past_length = 0
+ if model_kwargs.get("past_key_values") is not None:
+ cache = model_kwargs["past_key_values"]
+ past_length = 0
+ if not isinstance(cache, Cache):
+ past_length = cache[0][0].shape[2]
+ elif hasattr(cache, "get_seq_length") and cache.get_seq_length() is not None:
+ past_length = cache.get_seq_length()
+
+ # TODO(joao): this is not torch.compile-friendly, find a work-around. If the cache is not empty,
+ # end-to-end compilation will yield bad results because `cache_position` will be incorrect.
+ if not is_torchdynamo_compiling():
+ cache_position = cache_position[past_length:]
+
+ model_kwargs["cache_position"] = cache_position
+ return model_kwargs
+
+ def _get_cache(
+ self, cache_implementation: str, batch_size: int, max_cache_len: int, device: torch.device, model_kwargs
+ ) -> Cache:
+ """
+ Sets a cache for `generate`, that will persist across calls. A new cache will only be initialized a
+ new `generate` call requires a larger cache or uses a different batch size.
+
+ Returns the resulting cache object.
+ """
+ cache_cls: Cache = NEED_SETUP_CACHE_CLASSES_MAPPING[cache_implementation]
+ requires_cross_attention_cache = (
+ self.config.is_encoder_decoder or model_kwargs.get("encoder_outputs") is not None
+ )
+
+ if hasattr(self, "_cache"):
+ cache_to_check = self._cache.self_attention_cache if requires_cross_attention_cache else self._cache
+
+ if cache_implementation == "sliding_window":
+ max_cache_len = min(self.config.sliding_window, max_cache_len)
+
+ need_new_cache = (
+ not hasattr(self, "_cache")
+ or (not isinstance(cache_to_check, cache_cls))
+ or cache_to_check.max_batch_size != batch_size
+ )
+ if cache_implementation != "mamba":
+ need_new_cache = need_new_cache or cache_to_check.max_cache_len < max_cache_len
+
+ if requires_cross_attention_cache and hasattr(self, "_cache"):
+ need_new_cache = (
+ need_new_cache
+ or self._cache.cross_attention_cache.max_cache_len != model_kwargs["encoder_outputs"][0].shape[1]
+ )
+
+ if need_new_cache:
+ if hasattr(self.config, "_pre_quantization_dtype"):
+ cache_dtype = self.config._pre_quantization_dtype
+ else:
+ if not is_torchdynamo_compiling():
+ cache_dtype = self.dtype
+ else:
+ # NOTE: self.dtype is not compatible with torch.compile, as it calls `self.parameters()`.
+ # Workaround: trust the lm_head, whose attribute name is somewhat consistent across generative
+ # models. May cause trobles with non-text modalities.
+ cache_dtype = self.get_output_embeddings().weight.dtype
+
+ cache_kwargs = {
+ "config": self.config.get_text_config(),
+ "max_batch_size": batch_size,
+ "max_cache_len": max_cache_len,
+ "dtype": cache_dtype,
+ "device": device if cache_implementation == "offloaded_static" else None,
+ }
+ self._cache = cache_cls(**cache_kwargs)
+ if requires_cross_attention_cache:
+ encoder_kwargs = cache_kwargs.copy()
+ encoder_kwargs["max_cache_len"] = model_kwargs["encoder_outputs"][0].shape[1]
+ self._cache = EncoderDecoderCache(self._cache, cache_cls(**encoder_kwargs))
+ else:
+ self._cache.reset()
+ return self._cache
+
+ def _supports_default_dynamic_cache(self) -> bool:
+ """
+ Return `True` if current model can use a `DynamicCache` instance when initializing the `past_key_values`.
+ This is mostly the same as `_supports_cache_class` attribute, but add exception for `Jamba` model which
+ uses its own `HybridMambaAttentionDynamicCache` and do not need to initialize the Cache in advance in
+ order to save memory (because no back and forth `to_legacy_cache` and `from_legacy_cache` will be performed
+ for `HybridMambaAttentionDynamicCache`).
+ """
+ return (
+ self._supports_cache_class
+ and "jamba" not in self.__class__.__name__.lower()
+ and "zamba" not in self.__class__.__name__.lower()
+ and "bamba" not in self.__class__.__name__.lower()
+ )
+
+ def _prepare_cache_for_generation(
+ self,
+ generation_config: GenerationConfig,
+ model_kwargs: Dict,
+ assistant_model: "PreTrainedModel",
+ batch_size: int,
+ max_cache_length: int,
+ device: torch.device,
+ ) -> bool:
+ """
+ Prepares the cache for generation (if applicable), given `generate`'s parameterization. If a cache is
+ instantiated, writes it to `model_kwargs`, under the name expected by the model.
+ """
+
+ cache_name = "past_key_values" if "mamba" not in self.__class__.__name__.lower() else "cache_params"
+ requires_cross_attention_cache = (
+ self.config.is_encoder_decoder or model_kwargs.get("encoder_outputs") is not None
+ )
+
+ # Quick escape route 1: if the user specifies a cache, we only need to:
+ # a) check for conflicting `generate` arguments
+ # b) convert to the new cache format (if the user passes a legacy cache and model supports it)
+ user_defined_cache = model_kwargs.get(cache_name)
+ if user_defined_cache is not None:
+ if generation_config.cache_implementation is not None:
+ raise ValueError(
+ f"Passing both `cache_implementation` (used to initialize certain caches) and `{cache_name}` (a "
+ "Cache object) is unsupported. Please use only one of the two."
+ )
+ if isinstance(user_defined_cache, tuple) and self._supports_default_dynamic_cache():
+ model_kwargs[cache_name] = (
+ DynamicCache.from_legacy_cache(user_defined_cache)
+ if not requires_cross_attention_cache
+ else EncoderDecoderCache.from_legacy_cache(user_defined_cache)
+ )
+ return
+
+ # Quick escape route 2: if the user specifies no cache is to be used. (conflicting arguments are handled in
+ # `generation_config.validate()`)
+ if generation_config.use_cache is False:
+ return
+
+ # Quick escape route 3: model that only supports legacy caches = nothing to prepare
+ if not self._supports_default_dynamic_cache():
+ if generation_config.cache_implementation is not None:
+ warnings.warn(
+ "This model does not support `Cache` instances, it only supports the legacy cache format (tuple "
+ f"of tuples). `cache_implementation` (set to {generation_config.cache_implementation}) will be "
+ "ignored.",
+ UserWarning,
+ )
+ return
+
+ # Otherwise we NEED to prepare a cache, based on `generation_config.cache_implementation`
+
+ # TODO(joao): support static caches in assisted generation. assisted generation needs to roll back caches,
+ # which is only supported in dynamic caches atm
+ if assistant_model is not None and generation_config.cache_implementation is not None:
+ logger.warning_once(
+ "An assistant model is provided, using a dynamic cache instead of a cache of type="
+ f"'{generation_config.cache_implementation}'."
+ )
+ generation_config.cache_implementation = None
+
+ if generation_config.cache_implementation is not None:
+ if generation_config.cache_implementation in NEED_SETUP_CACHE_CLASSES_MAPPING:
+ if generation_config.cache_implementation == "static" and not self._supports_static_cache:
+ raise ValueError(
+ "This model does not support `cache_implementation='static'`. Please check the following "
+ "issue: https://github.com/huggingface/transformers/issues/28981"
+ )
+ model_kwargs[cache_name] = self._get_cache(
+ cache_implementation=generation_config.cache_implementation,
+ batch_size=max(generation_config.num_beams, generation_config.num_return_sequences) * batch_size,
+ max_cache_len=max_cache_length,
+ device=device,
+ model_kwargs=model_kwargs,
+ )
+ elif generation_config.cache_implementation == "quantized":
+ if not self._supports_quantized_cache:
+ raise ValueError(
+ "This model does not support the quantized cache. If you want your model to support quantized "
+ "cache, please open an issue and tag @zucchini-nlp."
+ )
+
+ cache_config = (
+ generation_config.cache_config
+ if generation_config.cache_config is not None
+ else QuantizedCacheConfig()
+ )
+ cache_class = QUANT_BACKEND_CLASSES_MAPPING[cache_config.backend]
+
+ if cache_config.backend == "quanto" and not is_optimum_quanto_available():
+ raise ImportError(
+ "You need to install optimum-quanto in order to use KV cache quantization with optimum-quanto backend. "
+ "Please install it via with `pip install optimum-quanto`"
+ )
+ elif cache_config.backend == "HQQ" and not is_hqq_available():
+ raise ImportError(
+ "You need to install `HQQ` in order to use KV cache quantization with HQQ backend. "
+ "Please install it via with `pip install hqq`"
+ )
+
+ model_kwargs[cache_name] = cache_class(cache_config)
+ elif generation_config.cache_implementation == "offloaded":
+ model_kwargs[cache_name] = OffloadedCache()
+
+ # Use DynamicCache() instance by default. This will avoid back and forth from legacy format that
+ # keeps copying the cache thus using much more memory
+ else:
+ model_kwargs[cache_name] = (
+ DynamicCache()
+ if not requires_cross_attention_cache
+ else EncoderDecoderCache(DynamicCache(), DynamicCache())
+ )
+
+ def _supports_logits_to_keep(self) -> bool:
+ """
+ Return True if the current model supports the keyword argument `logits_to_keep` in forward()
+ to save memory. Checking it in this way allows to avoid using a new model attribute.
+ """
+ return "logits_to_keep" in set(inspect.signature(self.forward).parameters.keys())
+
+ def _prepare_special_tokens(
+ self,
+ generation_config: GenerationConfig,
+ kwargs_has_attention_mask: Optional[bool] = None,
+ device: Optional[Union[torch.device, str]] = None,
+ ):
+ """
+ Prepares the special tokens for generation, overwriting the generation config with their processed versions
+ converted to tensor.
+
+ Note that `generation_config` is changed in place and stops being serializable after this method is called.
+ That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the
+ function). However, if called outside `generate`, consider creating a copy of `generation_config` first.
+ """
+
+ # Convert special tokens to tensors
+ def _tensor_or_none(token, device=None):
+ if token is None:
+ return token
+
+ device = device if device is not None else self.device
+ if isinstance(token, torch.Tensor):
+ return token.to(device)
+ return torch.tensor(token, device=device, dtype=torch.long)
+
+ bos_token_tensor = _tensor_or_none(generation_config.bos_token_id, device=device)
+ eos_token_tensor = _tensor_or_none(generation_config.eos_token_id, device=device)
+ pad_token_tensor = _tensor_or_none(generation_config.pad_token_id, device=device)
+ decoder_start_token_tensor = _tensor_or_none(generation_config.decoder_start_token_id, device=device)
+
+ # for BC we also try to get `decoder_start_token_id` or `bos_token_id` (#30892)
+ if self.config.is_encoder_decoder:
+ decoder_start_token_tensor = (
+ decoder_start_token_tensor if decoder_start_token_tensor is not None else bos_token_tensor
+ )
+
+ # We can have more than one eos token. Always treat it as a 1D tensor (when it exists).
+ if eos_token_tensor is not None and eos_token_tensor.ndim == 0:
+ eos_token_tensor = eos_token_tensor.unsqueeze(0)
+
+ # Set pad token if unset (and there are conditions to do so)
+ if pad_token_tensor is None and eos_token_tensor is not None:
+ if not is_torchdynamo_compiling():
+ if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:
+ logger.warning(
+ "The attention mask and the pad token id were not set. As a consequence, you may observe "
+ "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
+ )
+ pad_token_tensor = eos_token_tensor[0]
+ logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{pad_token_tensor} for open-end generation.")
+
+ # Sanity checks/warnings
+ if self.config.is_encoder_decoder and decoder_start_token_tensor is None:
+ raise ValueError(
+ "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
+ )
+ if not is_torchdynamo_compiling(): # Checks that depend on tensor-dependent control flow
+ if (
+ eos_token_tensor is not None
+ and isin_mps_friendly(elements=eos_token_tensor, test_elements=pad_token_tensor).any()
+ ):
+ if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:
+ logger.warning_once(
+ "The attention mask is not set and cannot be inferred from input because pad token is same as "
+ "eos token. As a consequence, you may observe unexpected behavior. Please pass your input's "
+ "`attention_mask` to obtain reliable results."
+ )
+ if eos_token_tensor is not None and (
+ torch.is_floating_point(eos_token_tensor) or (eos_token_tensor < 0).any()
+ ):
+ logger.warning(
+ f"`eos_token_id` should consist of positive integers, but is {eos_token_tensor}. Your generation "
+ "will not stop until the maximum length is reached. Depending on other flags, it may even crash."
+ )
+
+ # Update generation config with the updated special tokens tensors
+ # NOTE: this must be written into a different attribute name than the one holding the original special tokens
+ # (in their non-tensor form), in order to enable end-to-end compilation. See
+ # https://pytorch.org/docs/stable/torch.compiler_cudagraph_trees.html#limitations
+ generation_config._bos_token_tensor = bos_token_tensor
+ generation_config._eos_token_tensor = eos_token_tensor
+ generation_config._pad_token_tensor = pad_token_tensor
+ generation_config._decoder_start_token_tensor = decoder_start_token_tensor
+
+ @torch.no_grad()
+ 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[[int, torch.Tensor], List[int]]] = None,
+ synced_gpus: Optional[bool] = None,
+ assistant_model: Optional["PreTrainedModel"] = None,
+ streamer: Optional["BaseStreamer"] = None,
+ negative_prompt_ids: Optional[torch.Tensor] = None,
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ r"""
+
+ Generates sequences of token ids for models with a language modeling head.
+
+
+
+ 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_config` by passing the corresponding
+ parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.
+
+ For an overview of generation strategies and code examples, check out the [following
+ guide](../generation_strategies).
+
+
+
+ Parameters:
+ inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):
+ The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
+ method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
+ should be in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of
+ `input_ids`, `input_values`, `input_features`, or `pixel_values`.
+ generation_config ([`~generation.GenerationConfig`], *optional*):
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
+ passed to generate matching the attributes of `generation_config` will override them. If
+ `generation_config` is not provided, the default will be used, which has the following loading
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
+ default values, whose documentation should be checked to parameterize generation.
+ logits_processor (`LogitsProcessorList`, *optional*):
+ Custom logits processors that complement the default logits processors built from arguments and
+ generation config. If a logit processor is passed that is already created with the arguments or a
+ generation config an error is thrown. This feature is intended for advanced users.
+ stopping_criteria (`StoppingCriteriaList`, *optional*):
+ Custom stopping criteria that complements the default stopping criteria built from arguments and a
+ generation config. If a stopping criteria is passed that is already created with the arguments or a
+ generation config an error is thrown. If your stopping criteria depends on the `scores` input, make
+ sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`. This feature is
+ intended for advanced users.
+ prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):
+ If provided, this function constraints the beam search to allowed tokens only at each step. If not
+ provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and
+ `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned
+ on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful
+ for constrained generation conditioned on the prefix, as described in [Autoregressive Entity
+ Retrieval](https://arxiv.org/abs/2010.00904).
+ synced_gpus (`bool`, *optional*):
+ Whether to continue running the while loop until max_length. Unless overridden, this flag will be set
+ to `True` if using `FullyShardedDataParallel` or DeepSpeed ZeRO Stage 3 with multiple GPUs to avoid
+ deadlocking if one GPU finishes generating before other GPUs. Otherwise, defaults to `False`.
+ assistant_model (`PreTrainedModel`, *optional*):
+ An assistant model that can be used to accelerate generation. The assistant model must have the exact
+ same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistant model
+ is much faster than running generation with the model you're calling generate from. As such, the
+ assistant model should be much smaller.
+ streamer (`BaseStreamer`, *optional*):
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ negative_prompt_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ The negative prompt needed for some processors such as CFG. The batch size must match the input batch
+ size. This is an experimental feature, subject to breaking API changes in future versions.
+ negative_prompt_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Attention_mask for `negative_prompt_ids`.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Ad hoc parametrization of `generation_config` and/or additional model-specific kwargs that will be
+ forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
+ specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
+
+ Return:
+ [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`
+ or when `config.return_dict_in_generate=True`) or a `torch.LongTensor`.
+
+ If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible
+ [`~utils.ModelOutput`] types are:
+
+ - [`~generation.GenerateDecoderOnlyOutput`],
+ - [`~generation.GenerateBeamDecoderOnlyOutput`]
+
+ If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible
+ [`~utils.ModelOutput`] types are:
+
+ - [`~generation.GenerateEncoderDecoderOutput`],
+ - [`~generation.GenerateBeamEncoderDecoderOutput`]
+ """
+
+ # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
+ self._validate_model_class()
+ tokenizer = kwargs.pop("tokenizer", None) # Pull this out first, we only use it for stopping criteria
+ assistant_tokenizer = kwargs.pop("assistant_tokenizer", None) # only used for assisted generation
+
+ generation_config, model_kwargs = self._prepare_generation_config(generation_config, **kwargs)
+ self._validate_model_kwargs(model_kwargs.copy())
+ self._validate_assistant(assistant_model, tokenizer, assistant_tokenizer)
+
+ # 2. Set generation parameters if not already defined
+ if synced_gpus is None:
+ synced_gpus = (is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)) and dist.get_world_size() > 1
+
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
+
+ accepts_attention_mask = "attention_mask" in set(inspect.signature(self.forward).parameters.keys())
+ requires_attention_mask = "encoder_outputs" not in model_kwargs
+ kwargs_has_attention_mask = model_kwargs.get("attention_mask", None) is not None
+
+ # 3. Define model inputs
+ inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(
+ inputs, generation_config.bos_token_id, model_kwargs
+ )
+ batch_size = inputs_tensor.shape[0]
+
+ device = inputs_tensor.device
+ self._prepare_special_tokens(generation_config, kwargs_has_attention_mask, device=device)
+
+ # decoder-only models must use left-padding for batched generation.
+ if not self.config.is_encoder_decoder and not is_torchdynamo_compiling():
+ # If `input_ids` was given, check if the last id in any sequence is `pad_token_id`
+ # Note: If using, `inputs_embeds` this check does not work, because we want to be more hands-off.
+ if (
+ generation_config._pad_token_tensor is not None
+ and batch_size > 1
+ and len(inputs_tensor.shape) == 2
+ and torch.sum(inputs_tensor[:, -1] == generation_config._pad_token_tensor) > 0
+ ):
+ logger.warning(
+ "A decoder-only architecture is being used, but right-padding was detected! For correct "
+ "generation results, please set `padding_side='left'` when initializing the tokenizer."
+ )
+
+ # 4. Define other model kwargs
+ # decoder-only models with inputs_embeds forwarding must use caching (otherwise we can't detect whether we are
+ # generating the first new token or not, and we only want to use the embeddings for the first new token)
+ if not self.config.is_encoder_decoder and model_input_name == "inputs_embeds":
+ generation_config.use_cache = True
+
+ if not kwargs_has_attention_mask and requires_attention_mask and accepts_attention_mask:
+ model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(
+ inputs_tensor, generation_config, model_kwargs
+ )
+ elif kwargs_has_attention_mask:
+ # TODO (joao): generalize this check with other types of inputs
+ if model_input_name == "input_ids" and len(model_kwargs["attention_mask"].shape) > 2:
+ raise ValueError("`attention_mask` passed to `generate` must be 2D.")
+
+ if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
+ # if model is encoder decoder encoder_outputs are created and added to `model_kwargs`
+ model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(
+ inputs_tensor, model_kwargs, model_input_name, generation_config
+ )
+
+ # 5. Prepare `input_ids` which will be used for auto-regressive generation
+ if self.config.is_encoder_decoder:
+ input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
+ batch_size=batch_size,
+ model_input_name=model_input_name,
+ model_kwargs=model_kwargs,
+ decoder_start_token_id=generation_config._decoder_start_token_tensor,
+ device=inputs_tensor.device,
+ )
+ else:
+ input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")
+
+ if generation_config.token_healing:
+ input_ids = self.heal_tokens(input_ids, tokenizer)
+
+ if streamer is not None:
+ streamer.put(input_ids.cpu())
+
+ # 6. Prepare `max_length` depending on other stopping criteria.
+ input_ids_length = input_ids.shape[-1]
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
+ has_default_min_length = kwargs.get("min_length") is None and generation_config.min_length is not None
+ generation_config = self._prepare_generated_length(
+ generation_config=generation_config,
+ has_default_max_length=has_default_max_length,
+ has_default_min_length=has_default_min_length,
+ model_input_name=model_input_name,
+ inputs_tensor=inputs_tensor,
+ input_ids_length=input_ids_length,
+ )
+
+ # If the model supports `logits_to_keep` in forward(), set it to 1 to avoid computing the whole
+ # logit matrix. This can save a lot of memory during the first forward pass. Note that assisted decoding
+ # dynamically overrides this value as it can need more than the last token logits
+ if self._supports_logits_to_keep() and "logits_to_keep" not in model_kwargs:
+ model_kwargs["logits_to_keep"] = 1
+
+ self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)
+
+ # 7. Prepare the cache.
+ # - `model_kwargs` may be updated in place with a cache as defined by the parameters in `generation_config`.
+ # - different models have a different cache name expected by the model (default = "past_key_values")
+ # - `max_length`, prepared above, is used to determine the maximum cache length
+ max_cache_length = generation_config.max_length - 1
+ if (
+ inputs_tensor.shape[1] != input_ids_length
+ and model_input_name == "inputs_embeds"
+ and not self.config.is_encoder_decoder
+ ):
+ max_cache_length += inputs_tensor.shape[1]
+ self._prepare_cache_for_generation(
+ generation_config, model_kwargs, assistant_model, batch_size, max_cache_length, device
+ )
+
+ # 8. determine generation mode
+ generation_mode = generation_config.get_generation_mode(assistant_model)
+
+ if streamer is not None and (generation_config.num_beams > 1):
+ raise ValueError(
+ "`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1."
+ )
+
+ if not is_torchdynamo_compiling() and self.device.type != input_ids.device.type:
+ warnings.warn(
+ "You are calling .generate() with the `input_ids` being on a device type different"
+ f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
+ f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
+ " Please make sure that you have put `input_ids` to the"
+ f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
+ " running `.generate()`.",
+ UserWarning,
+ )
+
+ # 9. prepare logits processors and stopping criteria
+ prepared_logits_processor = self._get_logits_processor(
+ generation_config=generation_config,
+ input_ids_seq_length=input_ids_length,
+ encoder_input_ids=inputs_tensor,
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
+ logits_processor=logits_processor,
+ device=inputs_tensor.device,
+ model_kwargs=model_kwargs,
+ negative_prompt_ids=negative_prompt_ids,
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
+ )
+ prepared_stopping_criteria = self._get_stopping_criteria(
+ generation_config=generation_config, stopping_criteria=stopping_criteria, tokenizer=tokenizer, **kwargs
+ )
+
+ # Set model_kwargs `use_cache` so we can use it later in forward runs
+ model_kwargs["use_cache"] = generation_config.use_cache
+
+ # 10. go into different generation modes
+ if generation_mode == GenerationMode.ASSISTED_GENERATION:
+ if generation_config.num_return_sequences > 1:
+ raise ValueError(
+ "num_return_sequences has to be 1 when doing assisted generate, "
+ f"but is {generation_config.num_return_sequences}."
+ )
+ if batch_size > 1:
+ raise ValueError("assisted generate is only supported for batch_size = 1")
+ if not model_kwargs["use_cache"]:
+ raise ValueError("assisted generate requires `use_cache=True`")
+ if generation_config.cache_implementation in ["static", "hybrid", "sliding_window"]:
+ raise ValueError("assisted generate is not supported with Static cache classes`")
+ if self._is_stateful:
+ # In assisted generation we need the ability to confirm whether the model would pick certain tokens,
+ # which is not possible with stateful models (they can't reset to a previous subset of generated text)
+ raise ValueError(
+ f"assisted generation is not supported with stateful models, such as {self.__class__.__name__}"
+ )
+
+ # 11. Get the candidate generator, given the parameterization
+ candidate_generator = self._get_candidate_generator(
+ generation_config=generation_config,
+ input_ids=input_ids,
+ inputs_tensor=inputs_tensor,
+ assistant_model=assistant_model,
+ logits_processor=logits_processor,
+ target_tokenizer=tokenizer,
+ assistant_tokenizer=assistant_tokenizer,
+ model_kwargs=model_kwargs,
+ )
+
+ # 12. run assisted generate
+ result = self._assisted_decoding(
+ input_ids,
+ candidate_generator=candidate_generator,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ streamer=streamer,
+ **model_kwargs,
+ )
+ elif generation_mode == GenerationMode.DOLA_GENERATION:
+ if self._is_stateful:
+ # DoLa decoding was not designed for stateful models, and would require some changes
+ raise ValueError(
+ f"dola decoding is not supported with stateful models, such as {self.__class__.__name__}"
+ )
+ result = self._dola_decoding(
+ input_ids,
+ dola_layers=generation_config.dola_layers,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ streamer=streamer,
+ **model_kwargs,
+ )
+
+ elif generation_mode == GenerationMode.CONTRASTIVE_SEARCH:
+ if not model_kwargs["use_cache"]:
+ raise ValueError("Contrastive search requires `use_cache=True`")
+ if self._is_stateful:
+ # Just like assisted generation, we need to be able to rollback to a previous state (see comment above)
+ raise ValueError(
+ f"contrastive search is not supported with stateful models, such as {self.__class__.__name__}"
+ )
+
+ result = self._contrastive_search(
+ input_ids,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ streamer=streamer,
+ **model_kwargs,
+ )
+
+ elif generation_mode in (GenerationMode.SAMPLE, GenerationMode.GREEDY_SEARCH):
+ # 11. expand input_ids with `num_return_sequences` additional sequences per batch
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_return_sequences,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+
+ # 12. run sample (it degenerates to greedy search when `generation_config.do_sample=False`)
+ result = self._sample(
+ input_ids,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ streamer=streamer,
+ **model_kwargs,
+ )
+
+ elif generation_mode in (GenerationMode.BEAM_SAMPLE, GenerationMode.BEAM_SEARCH):
+ # 11. prepare beam search scorer
+ beam_scorer = BeamSearchScorer(
+ batch_size=batch_size,
+ num_beams=generation_config.num_beams,
+ device=inputs_tensor.device,
+ length_penalty=generation_config.length_penalty,
+ do_early_stopping=generation_config.early_stopping,
+ num_beam_hyps_to_keep=generation_config.num_return_sequences,
+ max_length=generation_config.max_length,
+ )
+
+ # 12. interleave input_ids with `num_beams` additional sequences per batch
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_beams,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+
+ # 13. run beam sample
+ result = self._beam_search(
+ input_ids,
+ beam_scorer,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ **model_kwargs,
+ )
+
+ elif generation_mode == GenerationMode.GROUP_BEAM_SEARCH:
+ # 11. prepare beam search scorer
+ beam_scorer = BeamSearchScorer(
+ batch_size=batch_size,
+ num_beams=generation_config.num_beams,
+ device=inputs_tensor.device,
+ length_penalty=generation_config.length_penalty,
+ do_early_stopping=generation_config.early_stopping,
+ num_beam_hyps_to_keep=generation_config.num_return_sequences,
+ num_beam_groups=generation_config.num_beam_groups,
+ max_length=generation_config.max_length,
+ )
+ # 12. interleave input_ids with `num_beams` additional sequences per batch
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_beams,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+ # 13. run beam search
+ result = self._group_beam_search(
+ input_ids,
+ beam_scorer,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ **model_kwargs,
+ )
+
+ elif generation_mode == GenerationMode.CONSTRAINED_BEAM_SEARCH:
+ final_constraints = []
+ if generation_config.constraints is not None:
+ final_constraints = generation_config.constraints
+
+ if generation_config.force_words_ids is not None:
+
+ def typeerror():
+ raise ValueError(
+ "`force_words_ids` has to either be a `List[List[List[int]]]` or `List[List[int]]` "
+ f"of positive integers, but is {generation_config.force_words_ids}."
+ )
+
+ if (
+ not isinstance(generation_config.force_words_ids, list)
+ or len(generation_config.force_words_ids) == 0
+ ):
+ typeerror()
+
+ for word_ids in generation_config.force_words_ids:
+ if isinstance(word_ids[0], list):
+ if not isinstance(word_ids, list) or len(word_ids) == 0:
+ typeerror()
+ if any(not isinstance(token_ids, list) for token_ids in word_ids):
+ typeerror()
+ if any(
+ any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids)
+ for token_ids in word_ids
+ ):
+ typeerror()
+
+ constraint = DisjunctiveConstraint(word_ids)
+ else:
+ if not isinstance(word_ids, list) or len(word_ids) == 0:
+ typeerror()
+ if any((not isinstance(token_id, int) or token_id < 0) for token_id in word_ids):
+ typeerror()
+
+ constraint = PhrasalConstraint(word_ids)
+ final_constraints.append(constraint)
+
+ # 11. prepare beam search scorer
+ constrained_beam_scorer = ConstrainedBeamSearchScorer(
+ constraints=final_constraints,
+ batch_size=batch_size,
+ num_beams=generation_config.num_beams,
+ device=inputs_tensor.device,
+ length_penalty=generation_config.length_penalty,
+ do_early_stopping=generation_config.early_stopping,
+ num_beam_hyps_to_keep=generation_config.num_return_sequences,
+ max_length=generation_config.max_length,
+ )
+ # 12. interleave input_ids with `num_beams` additional sequences per batch
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_beams,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+ # 13. run beam search
+ result = self._constrained_beam_search(
+ input_ids,
+ constrained_beam_scorer=constrained_beam_scorer,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ **model_kwargs,
+ )
+
+ # Convert to legacy cache format if requested
+ if (
+ generation_config.return_legacy_cache is True
+ and not is_torchdynamo_compiling()
+ and hasattr(result, "past_key_values")
+ and getattr(result.past_key_values, "to_legacy_cache") is not None
+ ):
+ result.past_key_values = result.past_key_values.to_legacy_cache()
+ return result
+
+ def _has_unfinished_sequences(
+ self,
+ this_peer_finished: bool,
+ synced_gpus: bool,
+ device: torch.device,
+ cur_len: Optional[int] = None,
+ max_length: Optional[int] = None,
+ ) -> bool:
+ """
+ Returns whether there are still unfinished sequences in the device. The existence of unfinished sequences is
+ fed through `this_peer_finished`. ZeRO stage 3-friendly.
+ """
+ # torch.compile does not support data-dependent control flow. This is a workaround to allow torch.compile,
+ # although we lose the ability to stop when all sequences return an EOS token (and other stopping criteria)
+ # TODO (joao): remove this when torch's support for control flow is not experimental (https://pytorch.org/docs/stable/generated/torch.cond.html)
+ if is_torchdynamo_compiling():
+ return cur_len < max_length
+ else:
+ if synced_gpus:
+ # Under synced_gpus the `forward` call must continue until all gpus complete their sequence.
+ # The following logic allows an early break if all peers finished generating their sequence
+ this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(device)
+ # send 0.0 if we finished, 1.0 otherwise
+ dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)
+ # did all peers finish? the reduced sum will be 0.0 then
+ if this_peer_finished_flag.item() == 0.0:
+ return False
+ elif this_peer_finished:
+ return False
+ return True
+
+ def heal_tokens(
+ self, input_ids: torch.LongTensor, tokenizer: Optional["PreTrainedTokenizerBase"] = None
+ ) -> torch.LongTensor:
+ r"""
+ Generates sequences of token ids for models with a language modeling head.
+ Parameters:
+ input_ids (`torch.LongTensor`): The sequence used as a prompt for the generation.
+ tokenizer (`PreTrainedTokenizerBase`, *optional*): The tokenizer used to decode the input ids.
+ Return:
+ `torch.LongTensor` where each sequence has its tail token replaced with its appropriate extension.
+ """
+ if tokenizer is None:
+ raise ValueError(
+ " When generating with token healing, you must pass the model's tokenizer to the `tokenizer` "
+ "argument of `generate`."
+ )
+
+ bos_token_id, pad_token_id = tokenizer.bos_token_id, tokenizer.pad_token_id
+ vocab_trie = ExtensionsTrie(tokenizer.get_vocab())
+ generation_config = GenerationConfig(max_new_tokens=1, pad_token_id=pad_token_id)
+
+ # assumption: leading/trailing whitespace is not meaningful, so the prompts are
+ # stripped before re-tokenizing to desensitize generation to whitespace artefacts
+ prompts = [p.strip() for p in tokenizer.batch_decode(input_ids, skip_special_tokens=True)]
+ input_ids = tokenizer(
+ prompts,
+ return_tensors="pt",
+ padding=True,
+ ).input_ids.to(input_ids.device)
+
+ # replace bos with pad to not condition healing on it
+ input_ids = torch.where(input_ids == bos_token_id, pad_token_id, input_ids)
+
+ """
+ the latter code assumes the input_ids is not empty,
+ input_id has to be checked if contains elements
+ """
+ if input_ids.numel() == 0:
+ return input_ids
+
+ tail_ids = input_ids[:, -1].tolist()
+
+ space_tok = tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids(" "))[0]
+ # tail tokens are used for a prefix search, thus, whitespaces are replaced with
+ # their tokenization (e.g. 'Ġ') to enable search for tokens prefixed with a whitespace
+ tail_toks = (tokenizer.decode(t).replace(" ", space_tok) for t in tail_ids)
+
+ for batch_idx, (tail_id, tail_tok) in enumerate(zip(tail_ids, tail_toks)):
+ batch_ids = input_ids[batch_idx]
+ if torch.all(batch_ids == pad_token_id).item():
+ continue # skip empty sequences (all pad ids)
+
+ # apply bias for alternatives (extensions) to the tail token
+ """
+ seq_bias key has to be tuple with int so have to use
+ tokenizer function to convert str to int
+ """
+ seq_bias = {
+ (tokenizer.convert_tokens_to_ids(alt_tok),): 10.0 for alt_tok in vocab_trie.extensions(prefix=tail_tok)
+ }
+
+ if len(seq_bias) == 1:
+ continue # skip if there are no token alternatives to heal with
+
+ # slightly favor original token to limit aggressive healing e.g. 'http' -> 'https'
+ seq_bias[(tail_id,)] += 1.0
+ generation_config.update(sequence_bias=seq_bias)
+
+ trimmed_ids = batch_ids[:-1]
+
+ """
+ the latter code assumes trimmed_ids is not empty
+ so have to check the its element count
+ """
+ if trimmed_ids.numel() == 0:
+ continue
+
+ # if the prompt is a single (non-pad) token, regenerate from bos
+ if len(batch_ids[batch_ids != pad_token_id]) == 1:
+ trimmed_ids[-1] = bos_token_id
+
+ input_ids[batch_idx] = self.generate(trimmed_ids.unsqueeze(0), generation_config=generation_config)
+
+ return input_ids
+
+ def _dola_decoding(
+ self,
+ input_ids: torch.LongTensor,
+ dola_layers: Union[str, List[int]],
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ streamer: "BaseStreamer",
+ **model_kwargs,
+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **dola decoding** and can be
+ used for decoder-only text models.
+ The method is based on the paper "DoLa: Decoding by Contrasting Layers Improves Factuality in Large Language
+ Models" (https://arxiv.org/abs/2309.03883) in ICLR 2024.
+
+ Parameters:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ dola_layers (`Union[str, List[int]]`):
+ The candidate layers used in contrasting layers of DoLa. It can be either 1) 'low' or 'high', which
+ means the lower part or higher part of the model layers, respectively, or 2) a list of layer indices
+ to be used for candidate layers. The 0-th layer is the word embedding layer of the model.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`, *optional*):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ streamer (`BaseStreamer`, *optional*):
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ model_kwargs:
+ Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
+ If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]
+ or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+
+ if self.config.is_encoder_decoder:
+ raise ValueError("DoLa decoding is only available for decoder-only models.")
+ # init values
+
+ pad_token_id = generation_config._pad_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
+ do_sample = generation_config.do_sample
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # keep track of which sequences are already finished
+ batch_size = input_ids.shape[0]
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ this_peer_finished = False
+
+ # prepare layers for DoLa decoding
+ final_layer = self.config.get_text_config().num_hidden_layers
+ # if the model has tied word embeddings, we skip the word embeddings (0-th) layer and start from the 2nd layer,
+ # as the early exit from word embeddings will become identity function
+ # if the model is really shallow (<=2 layers), we use the 1st layer if it's not the final layer and the 0-th
+ # layer otherwise. Notice that DoLa does not help shallow models much.
+ if not self.config.tie_word_embeddings:
+ start_layer = 0
+ elif final_layer > 2:
+ start_layer = 2
+ elif final_layer == 2:
+ start_layer = 1
+ else:
+ start_layer = 0
+
+ # For `N`-layer models with `N <= 40` layers, the layers of `range(0, N // 2, 2)` and `range(N // 2, N, 2)`
+ # are used for `'low'` and `'high'` layers, respectively.
+ # For models with `N > 40` layers, the layers of `range(0, 20, 2)` and `range(N - 20, N, 2)` are used for
+ # `'low'` and `'high'` layers, respectively.
+ if isinstance(dola_layers, str) and dola_layers == "low":
+ if start_layer == final_layer // 2:
+ candidate_premature_layers = [start_layer]
+ else:
+ candidate_premature_layers = (
+ list(range(start_layer, final_layer // 2, 2))
+ if final_layer <= 40
+ else list(range(start_layer, 20, 2))
+ )
+ elif isinstance(dola_layers, str) and dola_layers == "high":
+ candidate_premature_layers = (
+ list(range(final_layer // 2, final_layer, 2))
+ if final_layer <= 40
+ else list(range(final_layer - 20, final_layer, 2))
+ )
+ # Set the `dola_layers` to a list of integers for layer indices to contrast manually specified layers.
+ elif isinstance(dola_layers, list):
+ candidate_premature_layers = [i for i in dola_layers if i < final_layer]
+ else:
+ raise ValueError("dola_layers must be either 'low', 'high' or a list of integers.")
+
+ lm_head = self.get_output_embeddings()
+ if lm_head is None:
+ raise ValueError("DoLa is not supported for models that don't have output embeddings.")
+
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ # prepare model inputs
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # forward pass to get next token
+ outputs = self(
+ **model_inputs,
+ return_dict=True,
+ output_attentions=output_attentions,
+ output_hidden_states=True,
+ )
+
+ # .float() is needed to retain precision for later logits manipulations
+ final_layer_next_token_logits = outputs.logits[:, -1, :].detach().clone().float()
+ final_logits = outputs.logits[:, -1, :].float()
+ candidate_premature_logits = {}
+ for candidate_premature_layer in candidate_premature_layers:
+ candidate_premature_logits[candidate_premature_layer] = lm_head(
+ outputs.hidden_states[candidate_premature_layer][:, -1, :]
+ ).to(final_logits.device)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ continue
+
+ next_token_logits = _dola_select_contrast(
+ candidate_premature_layers, candidate_premature_logits, final_logits
+ )
+ next_token_logits = next_token_logits.to(input_ids.device)
+ # pre-process distribution
+ next_token_scores = logits_processor(input_ids, next_token_logits)
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_scores:
+ scores += (next_token_scores,)
+ if output_logits:
+ raw_logits += (final_layer_next_token_logits,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ if do_sample: # sample
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
+ else: # argmax
+ next_tokens = torch.argmax(next_token_scores, dim=-1)
+
+ # finished sentences should have their next token be a padding token
+ if has_eos_stopping_criteria:
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
+
+ # update generated ids, model inputs, and length for next step
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
+ if streamer is not None:
+ streamer.put(next_tokens.cpu())
+
+ # stop when each sentence is finished
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
+ this_peer_finished = unfinished_sequences.max() == 0
+
+ if streamer is not None:
+ streamer.end()
+
+ if return_dict_in_generate:
+ return GenerateDecoderOnlyOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return input_ids
+
+ @torch.no_grad()
+ def _contrastive_search(
+ self,
+ input_ids: torch.LongTensor,
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ streamer: Optional["BaseStreamer"],
+ **model_kwargs,
+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **contrastive search** 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)`):
+ The sequence used as a prompt for the generation.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ streamer (`BaseStreamer`, *optional*):
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ model_kwargs:
+ Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
+ If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]
+ or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
+ top_k = generation_config.top_k
+ penalty_alpha = generation_config.penalty_alpha
+ pad_token_id = generation_config._pad_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+ sequential = generation_config.low_memory
+
+ # init attention / hidden states / scores tuples
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ scores = () if (return_dict_in_generate and output_scores) else None
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # keep track of which sequences are already finished
+ batch_size = input_ids.shape[0]
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ # Create cosine_matrix_mask based on the attention_mask
+ cosine_matrix_mask = torch.ones_like(input_ids, dtype=torch.long)
+ if self.config.is_encoder_decoder:
+ if "decoder_attention_mask" in model_kwargs and model_kwargs["decoder_attention_mask"] is not None:
+ cosine_matrix_mask = model_kwargs["decoder_attention_mask"]
+ else:
+ cosine_matrix_mask = model_kwargs["attention_mask"]
+ cosine_matrix_mask = cosine_matrix_mask.repeat_interleave(top_k, dim=0)
+
+ this_peer_finished = False
+
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ # if the first step in the loop, encode all the prefix and obtain: (1) past_key_values;
+ # (2) last_hidden_states; (3) logit_for_next_step; (4) update model kwargs for the next step
+ if model_kwargs.get("past_key_values") is None or (
+ isinstance(model_kwargs["past_key_values"], (Cache, EncoderDecoderCache))
+ and model_kwargs["past_key_values"].get_seq_length() == 0
+ ):
+ # prepare inputs
+ model_kwargs["use_cache"] = True
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # encode the given prefix and prepare model inputs; encoder-decoder model process the prefix and save
+ # the `encoder_outputs`
+ outputs = self(
+ **model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
+ )
+
+ # last decoder hidden states will be used to compute the degeneration penalty (cosine similarity with
+ # previous tokens)
+ if self.config.is_encoder_decoder:
+ last_hidden_states = outputs.decoder_hidden_states[-1]
+ else:
+ last_hidden_states = outputs.hidden_states[-1]
+
+ # next logit for contrastive search to select top-k candidate tokens
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for this first iteration
+ # (the clone itself is always small)
+ # .float() is needed to retain precision for later logits manipulations
+ logit_for_next_step = outputs.logits[:, -1, :].clone().float()
+ logit_for_next_step = logit_for_next_step.to(input_ids.device)
+
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+
+ if not sequential:
+ # Expands model inputs top_k times, for batched forward passes (akin to beam search).
+ # input_ids is required for expanding visual inputs in qwen2vl
+ _, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=top_k,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+
+ past_key_values = model_kwargs.get("past_key_values")
+ if past_key_values is None:
+ raise ValueError(
+ f"{self.__class__.__name__} does not support caching and therefore **can't** be used "
+ "for contrastive search."
+ )
+ elif (
+ not isinstance(past_key_values[0], (tuple, torch.Tensor))
+ or past_key_values[0][0].shape[0] != batch_size
+ ):
+ raise ValueError(
+ f"{self.__class__.__name__} does not have a standard cache format and therefore **can't** be "
+ "used for contrastive search without further modifications."
+ )
+
+ # contrastive_search main logic start:
+ # contrastive search decoding consists of two steps: (1) candidate tokens recall; (2) candidate re-rank by
+ # degeneration penalty
+ processed_logit_for_next_step = logits_processor(input_ids, logit_for_next_step)
+ next_probs = nn.functional.softmax(processed_logit_for_next_step, dim=-1)
+
+ top_k_probs, top_k_ids = torch.topk(next_probs, dim=-1, k=top_k)
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_logits:
+ raw_logits += (logit_for_next_step,)
+ if output_scores:
+ scores += (processed_logit_for_next_step,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ # This is needed to properly delete outputs.logits which may be very large for this first iteration
+ # Otherwise a reference to outputs.logits is kept all along until after the next call to self.forward()
+ del outputs
+
+ if not sequential:
+ # Replicates the new past_key_values to match the `top_k` candidates
+ past = model_kwargs["past_key_values"]
+ # If it is a static cache, modify it in-place layer after layer to save memory
+ if isinstance(past, DynamicCache) or (
+ isinstance(past, EncoderDecoderCache) and isinstance(past.self_attention_cache, DynamicCache)
+ ):
+ past.batch_repeat_interleave(top_k)
+ else:
+ new_key_values = []
+ for layer in past:
+ items = []
+ # item is either the key or the value matrix
+ for item in layer:
+ items.append(item.repeat_interleave(top_k, dim=0))
+ new_key_values.append(tuple(items))
+
+ past = tuple(new_key_values)
+
+ model_kwargs["past_key_values"] = past
+
+ if sequential:
+ all_outputs = []
+ for i in range(top_k):
+ # compute the candidate tokens by the language model and collect their hidden_states
+ next_model_inputs = self.prepare_inputs_for_generation(top_k_ids[:, i].view(-1, 1), **model_kwargs)
+
+ outputs = self(
+ **next_model_inputs,
+ return_dict=True,
+ output_hidden_states=True,
+ output_attentions=output_attentions,
+ )
+ if isinstance(outputs["past_key_values"], DynamicCache) or (
+ isinstance(outputs["past_key_values"], EncoderDecoderCache)
+ and isinstance(outputs["past_key_values"].self_attention_cache, DynamicCache)
+ ):
+ # Remove past K-V from output since we don't need to stack later
+ outputs["past_key_values"] = None
+ # Remove last token from past K-V since we don't want to append it at this point
+ model_kwargs["past_key_values"].crop(-1)
+
+ all_outputs.append(outputs)
+ outputs = stack_model_outputs(all_outputs, self.config.get_text_config())
+
+ else:
+ # compute the candidate tokens by the language model and collect their hidden_states
+ # assembles top_k_ids into batch of size k
+ next_model_inputs = self.prepare_inputs_for_generation(top_k_ids.view(-1, 1), **model_kwargs)
+
+ outputs = self(
+ **next_model_inputs,
+ return_dict=True,
+ output_hidden_states=True,
+ output_attentions=output_attentions,
+ )
+
+ # This is essential to avoid having a last reference to the big past K-V and double the necessary memory
+ # in the next loop
+ del next_model_inputs
+
+ # name is different for encoder-decoder and decoder-only models
+ if self.config.is_encoder_decoder:
+ next_hidden = outputs.decoder_hidden_states[-1]
+ full_hidden_states = outputs.decoder_hidden_states
+ else:
+ next_hidden = outputs.hidden_states[-1]
+ full_hidden_states = outputs.hidden_states
+
+ # .float() is needed to retain precision for later logits manipulations
+ logits = outputs.logits[:, -1, :].float()
+ context_hidden = last_hidden_states.repeat_interleave(top_k, dim=0)
+
+ # compute the degeneration penalty and re-rank the candidates based on the degeneration penalty and the
+ # model confidence. Keeping `selected_idx` on CPU enables multi-device contrastive search and doesn't
+ # introduce (noticeable) slowdowns on single-device runs.
+ selected_idx = _ranking_fast(
+ context_hidden, next_hidden, top_k_probs, cosine_matrix_mask, penalty_alpha, top_k
+ )
+ cosine_matrix_mask = torch.cat(
+ [cosine_matrix_mask, cosine_matrix_mask.new_ones((cosine_matrix_mask.shape[0], 1))], dim=-1
+ )
+ selected_idx = selected_idx.to("cpu")
+
+ # This will be used instead of the previous inneficient torch.stack(torch.split())
+ augmented_idx = torch.tensor([x + i * top_k for i, x in enumerate(selected_idx)])
+
+ # prepare for the next step: (1) next token_id; (2) past_key_values; (3) last_hidden_states for computing
+ # the degeneration penalty; (4) logits for selecting next top-k candidates; (5) selected tokens scores
+ # (model confidence minus degeneration penalty); (6) decoder hidden_states
+ next_tokens = top_k_ids[range(len(top_k_ids)), selected_idx]
+ next_hidden = torch.stack(torch.split(next_hidden.squeeze(dim=1), top_k))
+ next_hidden = next_hidden[range(batch_size), selected_idx, :]
+ last_hidden_states = torch.cat([last_hidden_states, next_hidden.unsqueeze(1)], dim=1)
+
+ next_decoder_hidden_states = ()
+ for layer in full_hidden_states:
+ layer = torch.stack(torch.split(layer, top_k))[range(batch_size), selected_idx, :]
+ next_decoder_hidden_states += (layer,)
+
+ # generate past_key_values cache of only the selected token
+ if sequential:
+ next_model_input = self.prepare_inputs_for_generation(
+ top_k_ids[:, selected_idx].view(-1, 1), **model_kwargs
+ )
+
+ selected_outputs = self(
+ **next_model_input,
+ return_dict=True,
+ output_hidden_states=False,
+ output_attentions=False,
+ )
+ next_past_key_values = selected_outputs["past_key_values"]
+
+ else:
+ next_past_key_values = None
+ for possible_cache_name in ALL_CACHE_NAMES:
+ next_past_key_values = next_past_key_values or getattr(outputs, possible_cache_name, None)
+ # Do it in-place layer per layer to save memory
+ if isinstance(next_past_key_values, DynamicCache) or (
+ isinstance(next_past_key_values, EncoderDecoderCache)
+ and isinstance(next_past_key_values.self_attention_cache, DynamicCache)
+ ):
+ next_past_key_values.batch_select_indices(augmented_idx)
+ else:
+ new_key_values = []
+ for layer in next_past_key_values:
+ items = []
+ # item is either the key or the value matrix
+ for item in layer:
+ items.append(item[augmented_idx, ...])
+ new_key_values.append(tuple(items))
+
+ next_past_key_values = tuple(new_key_values)
+
+ logit_for_next_step = torch.stack(torch.split(logits, top_k))[range(batch_size), selected_idx, :]
+ logit_for_next_step = logit_for_next_step.to(input_ids.device)
+
+ # Rebuilds the relevant parts of the model output for the selected token, for use in the next iteration
+ if self.config.is_encoder_decoder:
+ next_step_cross_attentions = ()
+ next_step_decoder_attentions = ()
+ if output_attentions:
+ for layer in outputs.cross_attentions:
+ layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
+ next_step_cross_attentions += (layer,)
+ for layer in outputs.decoder_attentions:
+ layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
+ next_step_decoder_attentions += (layer,)
+ outputs = Seq2SeqLMOutput(
+ past_key_values=next_past_key_values,
+ decoder_hidden_states=next_decoder_hidden_states,
+ decoder_attentions=next_step_decoder_attentions or None,
+ cross_attentions=next_step_cross_attentions or None,
+ )
+ else:
+ next_step_attentions = ()
+ if output_attentions:
+ for layer in outputs.attentions:
+ layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
+ next_step_attentions += (layer,)
+ outputs = CausalLMOutputWithPast(
+ past_key_values=next_past_key_values,
+ hidden_states=next_decoder_hidden_states,
+ attentions=next_step_attentions or None,
+ )
+ # contrastive_search main logic end
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ continue
+
+ # finished sentences should have their next token be a padding token
+ if has_eos_stopping_criteria:
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
+
+ # update generated ids, model inputs, and length for next step
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
+ if streamer is not None:
+ streamer.put(next_tokens.cpu())
+
+ # stop when each sentence is finished
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
+ this_peer_finished = unfinished_sequences.max() == 0
+
+ if streamer is not None:
+ streamer.end()
+
+ if return_dict_in_generate:
+ # Contrastive search works by forward looking at the next token, so we need to exclude it from
+ # `past_key_values` to be consistent with the other decoding methods
+ if model_kwargs.get("past_key_values") is not None:
+ if isinstance(model_kwargs["past_key_values"], DynamicCache) or (
+ isinstance(model_kwargs["past_key_values"], EncoderDecoderCache)
+ and isinstance(model_kwargs["past_key_values"].self_attention_cache, DynamicCache)
+ ):
+ model_kwargs["past_key_values"].crop(-1)
+ else:
+ past_key_values = []
+ for layer in model_kwargs["past_key_values"]:
+ layer_past_key_values = []
+ for item in layer:
+ layer_past_key_values.append(item[..., :-1, :])
+ past_key_values.append(tuple(layer_past_key_values))
+ model_kwargs["past_key_values"] = tuple(past_key_values)
+
+ if self.config.is_encoder_decoder:
+ return GenerateEncoderDecoderOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateDecoderOnlyOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return input_ids
+
+ def _sample(
+ self,
+ input_ids: torch.LongTensor,
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ streamer: Optional["BaseStreamer"],
+ **model_kwargs,
+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
+ r"""
+ 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)`):
+ The sequence used as a prompt for the generation.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ streamer (`BaseStreamer`, *optional*):
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ model_kwargs:
+ Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
+ an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or `torch.LongTensor`:
+ A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ pad_token_id = generation_config._pad_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+ max_length = generation_config.max_length
+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
+ do_sample = generation_config.do_sample
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # keep track of which sequences are already finished
+ batch_size, cur_len = input_ids.shape
+ this_peer_finished = False
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ model_forward = self.__call__
+ if isinstance(model_kwargs.get("past_key_values"), Cache):
+ is_compileable = model_kwargs["past_key_values"].is_compileable and self._supports_static_cache
+ is_compileable = is_compileable and not self.generation_config.disable_compile
+ if is_compileable and (
+ self.device.type == "cuda" or generation_config.compile_config._compile_all_devices
+ ):
+ os.environ["TOKENIZERS_PARALLELISM"] = "0"
+ model_forward = self.get_compiled_call(generation_config.compile_config)
+
+ is_prefill = True
+ while self._has_unfinished_sequences(
+ this_peer_finished, synced_gpus, device=input_ids.device, cur_len=cur_len, max_length=max_length
+ ):
+ # prepare model inputs
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # prepare variable output controls (note: some models won't accept all output controls)
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
+
+ if is_prefill:
+ outputs = self(**model_inputs, return_dict=True)
+ is_prefill = False
+ else:
+ outputs = model_forward(**model_inputs, return_dict=True)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ continue
+
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
+ # (the clone itself is always small)
+ next_token_logits = outputs.logits[:, -1, :].clone().float()
+ next_token_logits = next_token_logits.to(input_ids.device)
+
+ # pre-process distribution
+ next_token_scores = logits_processor(input_ids, next_token_logits)
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_scores:
+ scores += (next_token_scores,)
+ if output_logits:
+ raw_logits += (next_token_logits,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ # token selection
+ if do_sample:
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
+ # TODO (joao): this OP throws "skipping cudagraphs due to ['incompatible ops']", find solution
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
+ else:
+ next_tokens = torch.argmax(next_token_scores, dim=-1)
+
+ # finished sentences should have their next token be a padding token
+ if has_eos_stopping_criteria:
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
+
+ # update generated ids, model inputs, and length for next step
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
+ if streamer is not None:
+ streamer.put(next_tokens.cpu())
+
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
+ this_peer_finished = unfinished_sequences.max() == 0
+ cur_len += 1
+
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
+ del outputs
+
+ if streamer is not None:
+ streamer.end()
+
+ if return_dict_in_generate:
+ if self.config.is_encoder_decoder:
+ return GenerateEncoderDecoderOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateDecoderOnlyOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return input_ids
+
+ def _temporary_reorder_cache(self, past_key_values, beam_idx):
+ """
+ Temporary function to handle the different types of cache reordering processes while we roll out `Cache`.
+
+ TODO: standardize cache formats and make all models compatible with `Cache`. It would remove the need
+ for this function, with `Cache.reorder_cache` being the sole remaining code path
+ """
+ model_class = self.__class__.__name__.lower()
+ # Exception 1: code path for models using the legacy cache format
+ if isinstance(past_key_values, (tuple, list)):
+ past_key_values = self._reorder_cache(past_key_values, beam_idx)
+ # Exception 2: models with different cache formats. These are limited to `DynamicCache` until their
+ # cache format is standardized, to avoid adding complexity to the codebase.
+ elif "gptbigcode" in model_class:
+ if not isinstance(past_key_values, (DynamicCache, EncoderDecoderCache)):
+ raise ValueError(
+ f"Using an unsupported cache format with {model_class}. Currently, it only supports the "
+ "legacy tuple format or `DynamicCache`"
+ )
+ past_key_values = self._reorder_cache(past_key_values, beam_idx)
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
+ # Standard code path: use the `Cache.reorder_cache`
+ else:
+ past_key_values.reorder_cache(beam_idx)
+ return past_key_values
+
+ def _beam_search(
+ self,
+ input_ids: torch.LongTensor,
+ beam_scorer: BeamScorer,
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ **model_kwargs,
+ ) -> Union[GenerateBeamOutput, torch.LongTensor]:
+ r"""
+ 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)`):
+ The sequence used as a prompt for the generation.
+ beam_scorer (`BeamScorer`):
+ An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
+ sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`:
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ model_kwargs:
+ Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
+ an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ pad_token_id = generation_config._pad_token_tensor
+ eos_token_id = generation_config._eos_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+ sequential = generation_config.low_memory
+ do_sample = generation_config.do_sample
+
+ batch_size = len(beam_scorer._beam_hyps)
+ num_beams = beam_scorer.num_beams
+
+ batch_beam_size, cur_len = input_ids.shape
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ if num_beams * batch_size != batch_beam_size:
+ raise ValueError(
+ f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
+ )
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ beam_indices = (
+ tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
+ )
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
+ # of the first beam are considered to avoid sampling the exact same tokens across all beams.
+ beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
+ beam_scores[:, 1:] = -1e9
+ beam_scores = beam_scores.view((batch_size * num_beams,))
+
+ this_peer_finished = False
+
+ decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder
+
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # prepare variable output controls (note: some models won't accept all output controls)
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
+
+ # if sequential is True, split the input to batches of batch_size and run sequentially
+ if sequential:
+ if any(
+ model_name in self.__class__.__name__.lower()
+ for model_name in [
+ "fsmt",
+ "reformer",
+ "ctrl",
+ "gpt_bigcode",
+ "transo_xl",
+ "xlnet",
+ "cpm",
+ "jamba",
+ ]
+ ):
+ raise RuntimeError(
+ f"Currently generation for {self.__class__.__name__} is not supported "
+ f"for `low_memory beam_search`. Please open an issue on GitHub if you need this feature."
+ )
+
+ inputs_per_sub_batches = _split_model_inputs(
+ model_inputs,
+ split_size=batch_size,
+ full_batch_size=batch_beam_size,
+ config=self.config.get_text_config(),
+ )
+ outputs_per_sub_batch = [
+ self(**inputs_per_sub_batch, return_dict=True) for inputs_per_sub_batch in inputs_per_sub_batches
+ ]
+
+ outputs = stack_model_outputs(outputs_per_sub_batch, self.config.get_text_config())
+
+ else: # Unchanged original behavior
+ outputs = self(**model_inputs, return_dict=True)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ cur_len = cur_len + 1
+ continue
+
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
+ # (the clone itself is always small)
+ # .float() is needed to retain precision for later logits manipulations
+ next_token_logits = outputs.logits[:, -1, :].clone().float()
+ next_token_logits = next_token_logits.to(input_ids.device)
+ next_token_scores = nn.functional.log_softmax(
+ next_token_logits, dim=-1
+ ) # (batch_size * num_beams, vocab_size)
+
+ next_token_scores_processed = logits_processor(input_ids, next_token_scores)
+ next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(
+ next_token_scores_processed
+ )
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_scores:
+ scores += (next_token_scores_processed,)
+ if output_logits:
+ raw_logits += (next_token_logits,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ # reshape for beam search
+ vocab_size = next_token_scores.shape[-1]
+ next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)
+
+ # Beam token selection: pick 1 + eos_token_id.shape[0] next tokens for each beam so we have at least 1
+ # non eos token per beam.
+ n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
+ n_tokens_to_keep = max(2, 1 + n_eos_tokens) * num_beams
+ if do_sample:
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
+ next_tokens = torch.multinomial(probs, num_samples=n_tokens_to_keep)
+ next_token_scores = torch.gather(next_token_scores, -1, next_tokens)
+ next_token_scores, _indices = torch.sort(next_token_scores, descending=True, dim=1)
+ next_tokens = torch.gather(next_tokens, -1, _indices)
+ else:
+ next_token_scores, next_tokens = torch.topk(
+ next_token_scores, n_tokens_to_keep, dim=1, largest=True, sorted=True
+ )
+
+ next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
+ next_tokens = next_tokens % vocab_size
+
+ # stateless
+ beam_outputs = beam_scorer.process(
+ input_ids,
+ next_token_scores,
+ next_tokens,
+ next_indices,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ beam_indices=beam_indices,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+
+ beam_scores = beam_outputs["next_beam_scores"]
+ beam_next_tokens = beam_outputs["next_beam_tokens"]
+ beam_idx = beam_outputs["next_beam_indices"]
+
+ input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
+
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
+ # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory
+ # (that way the memory peak does not include outputs.logits)
+ del outputs
+
+ if model_kwargs.get("past_key_values", None) is not None:
+ model_kwargs["past_key_values"] = self._temporary_reorder_cache(
+ model_kwargs["past_key_values"], beam_idx
+ )
+
+ if return_dict_in_generate and output_scores:
+ beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))
+
+ # increase cur_len
+ cur_len = cur_len + 1
+
+ if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
+ this_peer_finished = True
+
+ sequence_outputs = beam_scorer.finalize(
+ input_ids,
+ beam_scores,
+ next_tokens,
+ next_indices,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ max_length=stopping_criteria.max_length,
+ beam_indices=beam_indices,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+
+ if return_dict_in_generate:
+ if not output_scores:
+ sequence_outputs["sequence_scores"] = None
+
+ if self.config.is_encoder_decoder:
+ return GenerateBeamEncoderDecoderOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateBeamDecoderOnlyOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return sequence_outputs["sequences"]
+
+ 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, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ beam_scorer (`BeamScorer`):
+ An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
+ sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ model_kwargs:
+ Additional model specific kwargs that will be forwarded to the `forward` function of the model. If
+ model is an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ pad_token_id = generation_config._pad_token_tensor
+ eos_token_id = generation_config._eos_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+
+ num_beams = beam_scorer.num_beams
+ num_beam_groups = beam_scorer.num_beam_groups
+ num_sub_beams = num_beams // num_beam_groups
+ batch_size = len(beam_scorer._beam_hyps) // num_beam_groups
+ device = input_ids.device
+
+ batch_beam_size, cur_len = input_ids.shape
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ if return_dict_in_generate and output_scores:
+ beam_indices = [tuple(() for _ in range(num_sub_beams * batch_size)) for _ in range(num_beam_groups)]
+ else:
+ beam_indices = None
+
+ if num_beams * batch_size != batch_beam_size:
+ raise ValueError(
+ f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
+ )
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # initialise score of first beam of each group with 0 and the rest with -1e9. This ensures that the beams in
+ # the same group don't produce same tokens every time.
+ beam_scores = torch.full((batch_size, num_beams), -1e9, dtype=torch.float, device=device)
+ beam_scores[:, ::num_sub_beams] = 0
+ beam_scores = beam_scores.view((batch_size * num_beams,))
+
+ this_peer_finished = False
+
+ decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ # predicted tokens in cur_len step
+ current_tokens = torch.zeros(batch_size * num_beams, dtype=input_ids.dtype, device=device)
+
+ # indices which will form the beams in the next time step
+ reordering_indices = torch.zeros(batch_size * num_beams, dtype=torch.long, device=device)
+
+ # do one decoder step on all beams of all sentences in batch
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # prepare variable output controls (note: some models won't accept all output controls)
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
+
+ outputs = self(**model_inputs, return_dict=True)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ cur_len = cur_len + 1
+ continue
+
+ if output_scores:
+ processed_score = torch.zeros_like(outputs.logits[:, -1, :])
+ if output_logits:
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
+ # (the clone itself is always small)
+ raw_logit_score = outputs.logits[:, -1, :].clone()
+ raw_logit_score = raw_logit_score.to(input_ids.device)
+
+ for beam_group_idx in range(num_beam_groups):
+ group_start_idx = beam_group_idx * num_sub_beams
+ group_end_idx = min(group_start_idx + num_sub_beams, num_beams)
+ group_size = group_end_idx - group_start_idx
+
+ # indices of beams of current group among all sentences in batch
+ batch_group_indices = []
+
+ for batch_idx in range(batch_size):
+ batch_group_indices.extend(
+ [batch_idx * num_beams + idx for idx in range(group_start_idx, group_end_idx)]
+ )
+ group_input_ids = input_ids[batch_group_indices]
+
+ # select outputs of beams of current group only
+ # No need to clone() the logits here as they will not retain outputs.logits at the end of the loop
+ # .float() is needed to retain precision for later logits manipulations
+ next_token_logits = outputs.logits[batch_group_indices, -1, :].float()
+ next_token_logits = next_token_logits.to(input_ids.device)
+
+ next_token_scores = nn.functional.log_softmax(
+ next_token_logits, dim=-1
+ ) # (batch_size * group_size, vocab_size)
+ vocab_size = next_token_scores.shape[-1]
+
+ next_token_scores_processed = logits_processor(
+ group_input_ids, next_token_scores, current_tokens=current_tokens, beam_group_idx=beam_group_idx
+ )
+ next_token_scores = next_token_scores_processed + beam_scores[batch_group_indices].unsqueeze(-1)
+ next_token_scores = next_token_scores.expand_as(next_token_scores_processed)
+
+ if output_scores:
+ processed_score[batch_group_indices] = next_token_scores_processed
+
+ # reshape for beam search
+ next_token_scores = next_token_scores.view(batch_size, group_size * vocab_size)
+
+ # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
+ n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
+ next_token_scores, next_tokens = torch.topk(
+ next_token_scores, max(2, 1 + n_eos_tokens) * group_size, dim=1, largest=True, sorted=True
+ )
+
+ next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
+ next_tokens = next_tokens % vocab_size
+
+ # stateless
+ process_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None
+ beam_outputs = beam_scorer.process(
+ group_input_ids,
+ next_token_scores,
+ next_tokens,
+ next_indices,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ beam_indices=process_beam_indices,
+ group_index=beam_group_idx,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+ beam_scores[batch_group_indices] = beam_outputs["next_beam_scores"]
+ beam_next_tokens = beam_outputs["next_beam_tokens"]
+ beam_idx = beam_outputs["next_beam_indices"]
+
+ if return_dict_in_generate and output_scores:
+ beam_indices[beam_group_idx] = tuple(
+ beam_indices[beam_group_idx][beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices[0]))
+ )
+
+ input_ids[batch_group_indices] = group_input_ids[beam_idx]
+ group_input_ids = torch.cat([group_input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
+ current_tokens[batch_group_indices] = group_input_ids[:, -1]
+
+ # (beam_idx // group_size) -> batch_idx
+ # (beam_idx % group_size) -> offset of idx inside the group
+ reordering_indices[batch_group_indices] = (
+ num_beams * torch.div(beam_idx, group_size, rounding_mode="floor")
+ + group_start_idx
+ + (beam_idx % group_size)
+ )
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_scores:
+ scores += (processed_score,)
+ if output_logits:
+ raw_logits += (raw_logit_score,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ input_ids = torch.cat([input_ids, current_tokens.unsqueeze(-1)], dim=-1)
+
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
+ # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory
+ # (that way the memory peak does not include outputs.logits)
+ del outputs
+
+ if model_kwargs.get("past_key_values", None) is not None:
+ model_kwargs["past_key_values"] = self._temporary_reorder_cache(
+ model_kwargs["past_key_values"], reordering_indices
+ )
+
+ # increase cur_len
+ cur_len = cur_len + 1
+
+ if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
+ this_peer_finished = True
+
+ final_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None
+ sequence_outputs = beam_scorer.finalize(
+ input_ids,
+ beam_scores,
+ next_tokens,
+ next_indices,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ max_length=stopping_criteria.max_length,
+ beam_indices=final_beam_indices,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+
+ if return_dict_in_generate:
+ if not output_scores:
+ sequence_outputs["sequence_scores"] = None
+
+ if self.config.is_encoder_decoder:
+ return GenerateBeamEncoderDecoderOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateBeamDecoderOnlyOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return sequence_outputs["sequences"]
+
+ 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,
+ **model_kwargs,
+ ) -> Union[GenerateBeamOutput, torch.LongTensor]:
+ r"""
+ 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_length)`):
+ The sequence used as a prompt for the generation.
+ constrained_beam_scorer (`ConstrainedBeamSearchScorer`):
+ A derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
+ sorted during generation, while satisfying a list of positive constraints. For more information, the
+ documentation of [`ConstrainedBeamSearchScorer`] should be read.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ model_kwargs:
+ Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
+ an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ pad_token_id = generation_config._pad_token_tensor
+ eos_token_id = generation_config._eos_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+
+ batch_size = len(constrained_beam_scorer._beam_hyps)
+ num_beams = constrained_beam_scorer.num_beams
+
+ batch_beam_size, cur_len = input_ids.shape
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ if num_beams * batch_size != batch_beam_size:
+ raise ValueError(
+ f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
+ )
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ beam_indices = (
+ tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
+ )
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
+ # of the first beam are considered to avoid sampling the exact same tokens across all beams.
+ beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
+ beam_scores[:, 1:] = -1e9
+ beam_scores = beam_scores.view((batch_size * num_beams,))
+
+ this_peer_finished = False
+
+ decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # prepare variable output controls (note: some models won't accept all output controls)
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
+
+ outputs = self(**model_inputs, return_dict=True)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ cur_len = cur_len + 1
+ continue
+
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
+ # (the clone itself is always small)
+ # .float() is needed to retain precision for later logits manipulations
+ next_token_logits = outputs.logits[:, -1, :].clone().float()
+ next_token_logits = next_token_logits.to(input_ids.device)
+ next_token_scores = nn.functional.log_softmax(
+ next_token_logits, dim=-1
+ ) # (batch_size * num_beams, vocab_size)
+
+ next_token_scores_processed = logits_processor(input_ids, next_token_scores)
+
+ next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(
+ next_token_scores_processed
+ )
+
+ scores_for_all_vocab = next_token_scores.clone()
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_scores:
+ scores += (next_token_scores,)
+ if output_logits:
+ raw_logits += (next_token_logits,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ # reshape for beam search
+ vocab_size = next_token_scores.shape[-1]
+ next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)
+
+ # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
+ n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
+ next_token_scores, next_tokens = torch.topk(
+ next_token_scores, max(2, 1 + n_eos_tokens) * num_beams, dim=1, largest=True, sorted=True
+ )
+
+ next_indices = (next_tokens / vocab_size).long()
+ next_tokens = next_tokens % vocab_size
+
+ # stateless
+ beam_outputs = constrained_beam_scorer.process(
+ input_ids,
+ next_token_scores,
+ next_tokens,
+ next_indices,
+ scores_for_all_vocab,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ beam_indices=beam_indices,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+ beam_scores = beam_outputs["next_beam_scores"]
+ beam_next_tokens = beam_outputs["next_beam_tokens"]
+ beam_idx = beam_outputs["next_beam_indices"]
+
+ input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
+
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
+ # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory
+ # (that way the memory peak does not include outputs.logits)
+ del outputs
+
+ if model_kwargs.get("past_key_values", None) is not None:
+ model_kwargs["past_key_values"] = self._temporary_reorder_cache(
+ model_kwargs["past_key_values"], beam_idx
+ )
+
+ if return_dict_in_generate and output_scores:
+ beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))
+
+ # increase cur_len
+ cur_len = cur_len + 1
+
+ if constrained_beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
+ this_peer_finished = True
+
+ sequence_outputs = constrained_beam_scorer.finalize(
+ input_ids,
+ beam_scores,
+ next_tokens,
+ next_indices,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ max_length=stopping_criteria.max_length,
+ beam_indices=beam_indices,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+
+ if return_dict_in_generate:
+ if not output_scores:
+ sequence_outputs["sequence_scores"] = None
+ if self.config.is_encoder_decoder:
+ return GenerateBeamEncoderDecoderOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateBeamDecoderOnlyOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return sequence_outputs["sequences"]
+
+ def _assisted_decoding(
+ self,
+ input_ids: torch.LongTensor,
+ candidate_generator: CandidateGenerator,
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ streamer: Optional["BaseStreamer"],
+ **model_kwargs,
+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **greedy decoding** or
+ **sample** (depending on `do_sample`), assisted by candidate sequences. Assisted generation is an example of a
+ candidate decoding strategy. 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)`):
+ The sequence used as a prompt for the generation.
+ candidate_generator (`CandidateGenerator`):
+ A derived instance of [`CandidateGenerator`] that defines how candidate sequences are generated. For
+ more information, the documentation of [`CandidateGenerator`] should be read.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ streamer (`BaseStreamer`, *optional*):
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ model_kwargs:
+ Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
+ If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or
+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ do_sample = generation_config.do_sample
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # keep track of which sequences are already finished
+ batch_size = input_ids.shape[0]
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ this_peer_finished = False
+ is_first_iteration = True # to preserve the same API in the output as other generation methods
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ cur_len = input_ids.shape[-1]
+
+ # 1. Fetch candidate sequences from a `CandidateGenerator` and move to the correct device
+ candidate_input_ids, candidate_logits = candidate_generator.get_candidates(input_ids)
+ candidate_input_ids = candidate_input_ids.to(self.device)
+ if candidate_logits is not None:
+ candidate_logits = candidate_logits.to(self.device)
+
+ candidate_length = candidate_input_ids.shape[1] - input_ids.shape[1]
+ is_done_candidate = stopping_criteria(candidate_input_ids, None)
+
+ # 2. Use the original model to obtain the next token logits given the candidate sequence. We obtain
+ # `candidate_length + 1` relevant logits from this process: in the event that all candidates are correct,
+ # we use this forward pass to also pick the subsequent logits in the original model.
+
+ # 2.1. Prepare the model inputs
+ candidate_kwargs = copy.copy(model_kwargs)
+ candidate_kwargs = _prepare_attention_mask(
+ candidate_kwargs, candidate_input_ids.shape[1], self.config.is_encoder_decoder
+ )
+ candidate_kwargs = _prepare_token_type_ids(candidate_kwargs, candidate_input_ids.shape[1])
+ if "cache_position" in candidate_kwargs:
+ candidate_kwargs["cache_position"] = torch.cat(
+ (
+ candidate_kwargs["cache_position"],
+ torch.arange(cur_len, cur_len + candidate_length, device=input_ids.device, dtype=torch.long),
+ ),
+ dim=0,
+ )
+
+ model_inputs = self.prepare_inputs_for_generation(candidate_input_ids, **candidate_kwargs)
+ if "logits_to_keep" in model_inputs:
+ model_inputs["logits_to_keep"] = candidate_length + 1
+
+ # 2.2. Run a forward pass on the candidate sequence
+ # prepare variable output controls (note: some models won't accept all output controls)
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
+
+ outputs = self(**model_inputs)
+
+ # 2.3. Process the new logits
+ # .float() is needed to retain precision for later logits manipulations
+ new_logits = outputs.logits[:, -candidate_length - 1 :].float() # excludes the input prompt if present
+ new_logits = new_logits.to(input_ids.device)
+ next_token_logits = new_logits.clone()
+ if len(logits_processor) > 0:
+ for i in range(candidate_length + 1):
+ new_logits[:, i, :] = logits_processor(candidate_input_ids[:, : cur_len + i], new_logits[:, i, :])
+
+ # 3. Select the accepted tokens. There are two possible cases:
+ # Case 1: `do_sample=True` and we have logits for the candidates (originally from speculative decoding)
+ # 👉 Apply algorithm 1 from the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf).
+ if do_sample and candidate_logits is not None:
+ valid_tokens, n_matches = _speculative_sampling(
+ candidate_input_ids,
+ candidate_logits,
+ candidate_length,
+ new_logits,
+ is_done_candidate,
+ )
+
+ # Case 2: all other cases (originally from assisted generation) 👉 Compare the tokens selected from the
+ # original model logits with the candidate tokens. We can keep the candidate tokens until the first
+ # mismatch, or until the max length is reached.
+ else:
+ if do_sample:
+ probs = new_logits.softmax(dim=-1)
+ selected_tokens = torch.multinomial(probs[0, :, :], num_samples=1).squeeze(1)[None, :]
+ else:
+ selected_tokens = new_logits.argmax(dim=-1)
+
+ candidate_new_tokens = candidate_input_ids[:, cur_len:]
+ n_matches = ((~(candidate_new_tokens == selected_tokens[:, :-1])).cumsum(dim=-1) < 1).sum()
+
+ # Ensure we don't generate beyond max_len or an EOS token
+ if is_done_candidate and n_matches == candidate_length:
+ n_matches -= 1
+ valid_tokens = selected_tokens[:, : n_matches + 1]
+
+ # 4. Update variables according to the number of matching assistant tokens. Remember: the token generated
+ # by the model after the last candidate match is also valid, as it is generated from a correct sequence.
+ # Because of this last token, assisted generation search reduces to a normal greedy search/sample if there
+ # is no match.
+
+ # 4.1. Get the valid continuation, after the matching tokens
+ input_ids = torch.cat((input_ids, valid_tokens), dim=-1)
+ if streamer is not None:
+ streamer.put(valid_tokens.cpu())
+ new_cur_len = input_ids.shape[-1]
+
+ # 4.2. Discard past key values relative to unused assistant tokens
+ new_cache_size = new_cur_len - 1
+ outputs.past_key_values = _crop_past_key_values(self, outputs.past_key_values, new_cache_size)
+
+ # 5. Update the candidate generation strategy if needed
+ candidate_generator.update_candidate_strategy(input_ids, new_logits, n_matches)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ num_new_tokens=n_matches + 1,
+ )
+ if synced_gpus and this_peer_finished:
+ continue
+
+ # Store scores, attentions and hidden_states when required
+ # Assistant: modified to append one tuple element per token, as in the other generation methods.
+ if return_dict_in_generate:
+ newly_added_length = n_matches + 1
+ if output_scores:
+ scores += tuple(new_logits[:, i, :] for i in range(newly_added_length))
+ if output_logits:
+ raw_logits += tuple(next_token_logits[:, i, :] for i in range(newly_added_length))
+
+ newly_added_length = new_cur_len if is_first_iteration else newly_added_length
+ if output_attentions:
+ if self.config.is_encoder_decoder:
+ cross_attentions = _split_model_outputs(
+ cross_attentions, outputs.cross_attentions, cur_len, newly_added_length
+ )
+ decoder_attentions = _split_model_outputs(
+ decoder_attentions,
+ outputs.decoder_attentions,
+ cur_len,
+ newly_added_length,
+ is_decoder_attention=True,
+ )
+ # some (V)LLMs have hard requirement on SDPA and thus never return attn
+ elif outputs.attentions[0] is not None:
+ decoder_attentions = _split_model_outputs(
+ decoder_attentions,
+ outputs.attentions,
+ cur_len,
+ newly_added_length,
+ is_decoder_attention=True,
+ )
+ if output_hidden_states:
+ if self.config.is_encoder_decoder:
+ decoder_hidden_states = _split_model_outputs(
+ decoder_hidden_states, outputs.decoder_hidden_states, cur_len, newly_added_length
+ )
+ else:
+ decoder_hidden_states = _split_model_outputs(
+ decoder_hidden_states, outputs.hidden_states, cur_len, newly_added_length
+ )
+
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
+ this_peer_finished = unfinished_sequences.max() == 0
+ is_first_iteration = False
+
+ if streamer is not None:
+ streamer.end()
+
+ if (
+ hasattr(candidate_generator, "assistant_model")
+ and candidate_generator.assistant_model.generation_config.num_assistant_tokens_schedule == "heuristic"
+ ):
+ candidate_generator.assistant_model.generation_config.num_assistant_tokens = (
+ candidate_generator.num_assistant_tokens
+ )
+ if return_dict_in_generate:
+ if self.config.is_encoder_decoder:
+ return GenerateEncoderDecoderOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateDecoderOnlyOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return input_ids
+
+
+def _speculative_sampling(
+ candidate_input_ids,
+ candidate_logits,
+ candidate_length,
+ new_logits,
+ is_done_candidate,
+):
+ """
+ Applies sampling as in the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf, algorithm 1). Returns
+ the selected tokens, as well as the number of candidate matches.
+
+ NOTE: Unless otherwise stated, the variable names match those in the paper.
+ """
+ new_candidate_input_ids = candidate_input_ids[:, -candidate_length:]
+ # Gets the probabilities from the logits. q_i and p_i denote the assistant and model probabilities of the tokens
+ # selected by the assistant, respectively.
+ q = candidate_logits.softmax(dim=-1)
+ q_i = q[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)
+ p = new_logits.softmax(dim=-1)
+ p_i = p[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)
+ probability_ratio = p_i / q_i
+
+ # When probability_ratio > 1 (i.e. q_i(x) < p_i(x), or "assistant probability of the candidate token is smaller
+ # than the model probability for the same token"), keep the token. Otherwise reject with p = 1 - probability_ratio
+ # (= keep with p = probability_ratio). Keep all the tokens until the first rejection
+ r_i = torch.rand_like(probability_ratio)
+ is_accepted = r_i <= probability_ratio
+ n_matches = ((~is_accepted).cumsum(dim=-1) < 1).sum() # this is `n` in algorithm 1
+
+ # Ensure we don't generate beyond max_len or an EOS token (not in algorithm 1, but needed for correct behavior)
+ if is_done_candidate and n_matches == candidate_length:
+ # Output length is assumed to be `n_matches + 1`. Since we won't generate another token with the target model
+ # due to acceptance on EOS we fix `n_matches`
+ n_matches -= 1
+ valid_tokens = new_candidate_input_ids[:, : n_matches + 1]
+ else:
+ # Next token selection: if there is a rejection, adjust the distribution from the main model before sampling.
+ gamma = candidate_logits.shape[1]
+ p_n_plus_1 = p[:, n_matches, :]
+ if n_matches < gamma:
+ q_n_plus_1 = q[:, n_matches, :]
+ p_prime = torch.clamp((p_n_plus_1 - q_n_plus_1), min=0)
+ p_prime.div_(p_prime.sum())
+ else:
+ p_prime = p_n_plus_1
+ t = torch.multinomial(p_prime, num_samples=1).squeeze(1)[None, :]
+
+ # The selected tokens include the matches (if any) plus the next sampled tokens
+ if n_matches > 0:
+ valid_tokens = torch.cat((new_candidate_input_ids[:, :n_matches], t), dim=-1)
+ else:
+ valid_tokens = t
+
+ return valid_tokens, n_matches
+
+
+def _split_model_outputs(outputs, new_outputs, cur_len, added_len, is_decoder_attention=False):
+ """
+ Given the (decoder/cross attentions)/(decoder hidden states) for multiple generated tokens, splits it into a tuple
+ where each member corresponds to a single generated token.
+ """
+ # Retrocompatibility: in our generation functions, the first iteration includes the attention/hidden states for the
+ # prompt.
+ if len(outputs) == 0:
+ new_tuple = ()
+ for layer in new_outputs:
+ last_dim_size = cur_len if is_decoder_attention else layer.shape[-1]
+ new_tuple += (layer[..., :cur_len, :last_dim_size],)
+ outputs += (new_tuple,)
+ # The first iteration contains the prompt + 1 generated token, let's update the length variables accordingly
+ cur_len += 1
+ added_len -= cur_len
+
+ for i in range(added_len):
+ new_tuple = ()
+ for layer in new_outputs:
+ last_dim_size = cur_len + i if is_decoder_attention else layer.shape[-1]
+ new_tuple += (layer[..., i : i + 1, :last_dim_size],)
+ outputs += (new_tuple,)
+ return outputs
+
+
+def _ranking_fast(
+ context_hidden: torch.FloatTensor,
+ next_hidden: torch.FloatTensor,
+ next_top_k_probs: torch.FloatTensor,
+ cosine_matrix_mask: torch.LongTensor,
+ alpha: float,
+ beam_width: int,
+) -> torch.FloatTensor:
+ """
+ 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.
+ """
+ norm_context_hidden = context_hidden / context_hidden.norm(dim=2, keepdim=True)
+ norm_next_hidden = next_hidden / next_hidden.norm(dim=2, keepdim=True)
+ cosine_matrix = torch.matmul(norm_context_hidden, norm_next_hidden.transpose(1, 2)).squeeze(-1) # [B*K, S]
+
+ # Penalize cosine_matrix based on the cosine_matrix_mask (ignore padding positions)
+ # Using a large negative value for masked positions
+ cosine_matrix_mask = cosine_matrix_mask.to(dtype=cosine_matrix.dtype)
+ cosine_matrix_mask = (1 - cosine_matrix_mask) * torch.finfo(cosine_matrix.dtype).min
+ cosine_matrix = cosine_matrix + cosine_matrix_mask
+
+ degeneration_penalty, _ = torch.max(cosine_matrix, dim=-1) # [B*K]
+ next_top_k_probs = next_top_k_probs.view(-1) # [B*K]
+ contrastive_score = (1.0 - alpha) * next_top_k_probs - alpha * degeneration_penalty
+ contrastive_score = torch.stack(torch.split(contrastive_score, beam_width)) # [B, K]
+ _, selected_idx = contrastive_score.max(dim=-1) # [B]
+ return selected_idx
+
+
+def _split(data, full_batch_size: int, split_size: int = None):
+ """
+ Takes care of three cases:
+ 1. data is a tensor: e.g. last_hidden_state, pooler_output etc. split them on the batch_size dim
+ 2. data is a tuple: e.g. hidden_states, attentions etc. Keep the tuple as it is and split each tensor in it and
+ return a list of tuples
+ 3. data is a tuple of tuples, e.g. past_key_values. Keep the tuple as it is and split each tuple in it and
+ return a list of tuples of tuples
+ (see documentation of ModelOutput)
+ """
+ if data is None:
+ return [None] * (full_batch_size // split_size)
+ if isinstance(data, torch.Tensor):
+ return [data[i : i + split_size] for i in range(0, full_batch_size, split_size)]
+ # New cache format
+ elif isinstance(data, DynamicCache) or (
+ isinstance(data, EncoderDecoderCache) and isinstance(data.self_attention_cache, DynamicCache)
+ ):
+ return data.batch_split(full_batch_size, split_size)
+ elif isinstance(data, tuple):
+ # If the elements of the tuple are also tuples (e.g., past_key_values in our earlier example)
+ if isinstance(data[0], tuple):
+ return [
+ tuple(tuple(tensor[i : i + split_size] for tensor in inner_tuple) for inner_tuple in data)
+ for i in range(0, full_batch_size, split_size)
+ ]
+
+ else:
+ return [
+ tuple(sub_tensor[i : i + split_size] for sub_tensor in data)
+ for i in range(0, full_batch_size, split_size)
+ ]
+ else:
+ raise TypeError(f"Unexpected attribute type: {type(data)}")
+
+
+def _split_model_inputs(
+ model_input: Union[ModelOutput, Dict], split_size: int, full_batch_size: int, config: PretrainedConfig
+) -> List[Union[ModelOutput, Dict]]:
+ """
+ Split a ModelOutput object (or its subclasses) or Dict into a list of same-class objects based on a specified split
+ size. The input object is dict when it was prepared for forward pass and ModelOutput when it was returned from
+ previous forward pass.
+ """
+ # Edge case: if model_input is None, return a list of Nones
+ # this happens with Whisper where encoder_outputs is None
+ if model_input is None:
+ return [model_input] * (full_batch_size // split_size)
+ # Infer the class from the object
+ model_output_cls = type(model_input)
+ if (full_batch_size % split_size) != 0:
+ raise ValueError("`full_batch_size` must be divisible by `split_size`")
+
+ if split_size > full_batch_size:
+ raise ValueError("`split_size` must be smaller or equal to `full_batch_size`")
+
+ # Helper function to split tensors or tuples of tensors
+
+ # Find all the dataclass fields (e.g., last_hidden_state, pooler_output etc.) and split them
+ keys = (
+ model_input.__dataclass_fields__.keys() if hasattr(model_input, "__dataclass_fields__") else model_input.keys()
+ )
+ # We only keep keys that are in the model_input
+ keys = [k for k in keys if k in model_input]
+ # Here we can have four types of values: tensors, tuples of tensors and booleans, and encoder_outputs which is a
+ # ModelOutput object.
+ # bool should not be split but replicated for each split
+ bool_keys = [k for k in keys if isinstance(model_input[k], bool) or k == "cache_position"]
+ keys_to_ignore = ["cache_position", "encoder_outputs", "logits_to_keep"]
+ non_bool_keys = [k for k in keys if not isinstance(model_input[k], bool) and k not in keys_to_ignore]
+
+ # we split the tensors and tuples of tensors
+ data_split_list = [
+ {k: _split(model_input[k], full_batch_size, split_size)[i] for k in non_bool_keys}
+ for i in range(full_batch_size // split_size)
+ ]
+ # bool values are the same and replicated for each split
+ bool_data = {k: model_input[k] for k in bool_keys}
+ # encoder_outputs is a ModelOutput object and should be split by its own
+ if "encoder_outputs" in model_input:
+ encoder_outputs_split = _split_model_inputs(
+ model_input["encoder_outputs"], split_size, full_batch_size, config.get_text_config()
+ )
+ data_split_list = [
+ {**data_split, "encoder_outputs": encoder_outputs_split[i]} for i, data_split in enumerate(data_split_list)
+ ]
+ # logits_to_keep should be replicated for each split, similar to bool values
+ if "logits_to_keep" in model_input:
+ data_split_list = [
+ {**data_split, "logits_to_keep": model_input["logits_to_keep"]} for data_split in data_split_list
+ ]
+
+ # Convert each dictionary in the list to an object of the inferred class
+ split_model_inputs: List[Union[ModelOutput, Dict]] = [
+ model_output_cls(**data_split, **bool_data) for data_split in data_split_list
+ ]
+
+ return split_model_inputs
+
+
+def stack_model_outputs(model_outputs: List[ModelOutput], config: PretrainedConfig) -> ModelOutput:
+ """
+ Stack a list of ModelOutput objects (or its subclasses) along the batch_size dimension. The function infers the
+ specific ModelOutput subclass from the list provided.
+ """
+ if not model_outputs:
+ raise ValueError("Input list is empty.")
+
+ # Infer the class from the first object in the list
+ model_output_cls = type(model_outputs[0])
+
+ # Ensure all objects are of the same type
+ if not all(isinstance(obj, model_output_cls) for obj in model_outputs):
+ raise ValueError("All elements in the list should be of the same type.")
+
+ # Helper function to concat tensors or tuples of tensors
+ def _concat(data):
+ """
+ Reverse of `_split` function above.
+ """
+ if any(data is None for data in data):
+ return None
+ if isinstance(data[0], torch.Tensor):
+ return torch.cat(data, dim=0)
+ # New cache format
+ elif isinstance(data[0], DynamicCache):
+ return DynamicCache.from_batch_splits(data)
+ elif isinstance(data[0], EncoderDecoderCache):
+ return EncoderDecoderCache.from_batch_splits(data)
+ elif isinstance(data[0], tuple):
+ # If the elements of the tuple are also tuples (e.g., past_key_values in our earlier example)
+ if isinstance(data[0][0], tuple):
+ return tuple(
+ tuple(torch.cat([attr[i][j] for attr in data], dim=0) for j in range(len(data[0][0])))
+ for i in range(len(data[0]))
+ )
+ else:
+ return tuple(torch.cat([attr[i] for attr in data], dim=0) for i in range(len(data[0])))
+ elif isinstance(data[0], (int, float)):
+ # If the elements are integers or floats, return a tensor
+ return torch.tensor(data)
+ else:
+ raise TypeError(f"Unexpected attribute type: {type(data[0])}")
+
+ # Use a dictionary comprehension to gather attributes from all objects and concatenate them
+ concatenated_data = {
+ k: _concat([getattr(model_output, k) for model_output in model_outputs])
+ for k in model_output_cls.__dataclass_fields__.keys()
+ }
+
+ # Return a new object of the inferred class with the concatenated attributes
+ return model_output_cls(**concatenated_data)
+
+
+def _relative_top_filter(
+ scores: torch.FloatTensor,
+ baseline_scores: torch.FloatTensor,
+ relative_top: float = 0.1,
+ filter_value: float = -float("Inf"),
+ base_filter_value=-1e-3,
+ min_tokens_to_keep: int = 1,
+) -> torch.FloatTensor:
+ """
+ Reference: https://github.com/XiangLi1999/ContrastiveDecoding/blob/170e9142e92159c1237d731e240f5eb14aabf428/transformers/src/transformers/generation_logits_process.py#L235
+ Apply filtering to only keep tokens with a probability above a certain threshold. The threshold is defined as `relative_top` * max probability in the distribution.
+ """
+ scores_normalized = scores.log_softmax(dim=-1)
+ baseline_scores_normalized = baseline_scores.log_softmax(dim=-1)
+ sorted_logits, sorted_indices = torch.sort(scores_normalized, descending=True)
+ min_thresh = sorted_logits[..., min_tokens_to_keep - 1]
+ probs_max = torch.max(scores_normalized, dim=-1).values
+ probs_thresh = probs_max + np.log(relative_top)
+ probs_thresh = torch.min(min_thresh, probs_thresh)
+ probs_thresh = probs_thresh.unsqueeze(-1)
+ baseline_scores_normalized[scores_normalized < probs_thresh] = base_filter_value
+ scores_normalized[scores_normalized < probs_thresh] = filter_value
+ return scores_normalized, baseline_scores_normalized
+
+
+def _dola_select_contrast(
+ candidate_premature_layers: List[int],
+ candidate_premature_logits: Dict[int, torch.FloatTensor],
+ final_logits: torch.FloatTensor,
+) -> torch.FloatTensor:
+ if len(candidate_premature_layers) == 1:
+ base_logits = candidate_premature_logits[candidate_premature_layers[0]]
+ final_logits, base_logits = _relative_top_filter(final_logits, base_logits)
+ logits = final_logits - base_logits
+ return logits
+
+ # 1. Stacking all premature_layers into a new dimension
+ stacked_premature_layers = torch.stack([candidate_premature_logits[i] for i in candidate_premature_layers], dim=0)
+
+ # 2. Calculate the softmax values for mature_layer and all premature_layers
+ # shape: (batch_size, vocab_size)
+ softmax_mature_layer = F.softmax(final_logits, dim=-1)
+ # shape: (num_premature_layers, batch_size, vocab_size)
+ softmax_premature_layers = F.softmax(stacked_premature_layers, dim=-1)
+
+ # 3. Calculate the average distribution
+ # shape: (num_premature_layers, batch_size, vocab_size)
+ avg_dist = 0.5 * (softmax_mature_layer[None, :, :] + softmax_premature_layers)
+
+ # 4. Calculate log-softmax for the KL divergence
+ # shape: (batch_size, vocab_size)
+ log_softmax_mature_layer = F.log_softmax(final_logits, dim=-1)
+ # shape: (num_premature_layers, batch_size, vocab_size)
+ log_softmax_premature_layers = F.log_softmax(stacked_premature_layers, dim=-1)
+
+ # 5. Calculate the KL divergences and then the JS divergences
+ # shape: (num_premature_layers, batch_size)
+ kl1 = F.kl_div(log_softmax_mature_layer[None, :, :], avg_dist, reduction="none").mean(-1)
+ # shape: (num_premature_layers, batch_size)
+ kl2 = F.kl_div(log_softmax_premature_layers, avg_dist, reduction="none").mean(-1)
+ js_divs = 0.5 * (kl1 + kl2) # shape: (num_premature_layers, batch_size)
+
+ # 6. Reduce the batchmean
+ js_divs = js_divs.mean(-1) # shape: (num_premature_layers,)
+ premature_layer = candidate_premature_layers[int(js_divs.argmax().cpu().item())]
+
+ base_logits = candidate_premature_logits[premature_layer]
+ final_logits, base_logits = _relative_top_filter(final_logits, base_logits)
+ logits = final_logits - base_logits
+ return logits
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/generation/watermarking.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/generation/watermarking.py
new file mode 100644
index 0000000000000000000000000000000000000000..da90c03dd0da89cdf98b2eede63f1eca2b3b9197
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/generation/watermarking.py
@@ -0,0 +1,549 @@
+# coding=utf-8
+# Copyright 2024 The HuggingFace Inc. team and Google DeepMind.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import collections
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, Dict, Optional, Tuple, Union
+
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import BCELoss
+
+from ..modeling_utils import PreTrainedModel
+from ..utils import ModelOutput, is_torch_available, logging
+from .configuration_utils import PretrainedConfig, WatermarkingConfig
+
+
+if is_torch_available():
+ import torch
+
+ from .logits_process import SynthIDTextWatermarkLogitsProcessor, WatermarkLogitsProcessor
+
+
+logger = logging.get_logger(__name__)
+
+
+@dataclass
+class WatermarkDetectorOutput:
+ """
+ Outputs of a watermark detector.
+
+ Args:
+ num_tokens_scored (np.array of shape (batch_size)):
+ Array containing the number of tokens scored for each element in the batch.
+ num_green_tokens (np.array of shape (batch_size)):
+ Array containing the number of green tokens for each element in the batch.
+ green_fraction (np.array of shape (batch_size)):
+ Array containing the fraction of green tokens for each element in the batch.
+ z_score (np.array of shape (batch_size)):
+ Array containing the z-score for each element in the batch. Z-score here shows
+ how many standard deviations away is the green token count in the input text
+ from the expected green token count for machine-generated text.
+ p_value (np.array of shape (batch_size)):
+ Array containing the p-value for each batch obtained from z-scores.
+ prediction (np.array of shape (batch_size)), *optional*:
+ Array containing boolean predictions whether a text is machine-generated for each element in the batch.
+ confidence (np.array of shape (batch_size)), *optional*:
+ Array containing confidence scores of a text being machine-generated for each element in the batch.
+ """
+
+ num_tokens_scored: np.array = None
+ num_green_tokens: np.array = None
+ green_fraction: np.array = None
+ z_score: np.array = None
+ p_value: np.array = None
+ prediction: Optional[np.array] = None
+ confidence: Optional[np.array] = None
+
+
+class WatermarkDetector:
+ r"""
+ Detector for detection of watermark generated text. The detector needs to be given the exact same settings that were
+ given during text generation to replicate the watermark greenlist generation and so detect the watermark. This includes
+ the correct device that was used during text generation, the correct watermarking arguments and the correct tokenizer vocab size.
+ The code was based on the [original repo](https://github.com/jwkirchenbauer/lm-watermarking/tree/main).
+
+ See [the paper](https://arxiv.org/abs/2306.04634) for more information.
+
+ Args:
+ model_config (`PretrainedConfig`):
+ The model config that will be used to get model specific arguments used when generating.
+ device (`str`):
+ The device which was used during watermarked text generation.
+ watermarking_config (Union[`WatermarkingConfig`, `Dict`]):
+ The exact same watermarking config and arguments used when generating text.
+ ignore_repeated_ngrams (`bool`, *optional*, defaults to `False`):
+ Whether to count every unique ngram only once or not.
+ max_cache_size (`int`, *optional*, defaults to 128):
+ The max size to be used for LRU caching of seeding/sampling algorithms called for every token.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkDetector, WatermarkingConfig
+
+ >>> model_id = "openai-community/gpt2"
+ >>> model = AutoModelForCausalLM.from_pretrained(model_id)
+ >>> tok = AutoTokenizer.from_pretrained(model_id)
+ >>> tok.pad_token_id = tok.eos_token_id
+ >>> tok.padding_side = "left"
+
+ >>> inputs = tok(["This is the beginning of a long story", "Alice and Bob are"], padding=True, return_tensors="pt")
+ >>> input_len = inputs["input_ids"].shape[-1]
+
+ >>> # first generate text with watermark and without
+ >>> watermarking_config = WatermarkingConfig(bias=2.5, seeding_scheme="selfhash")
+ >>> out_watermarked = model.generate(**inputs, watermarking_config=watermarking_config, do_sample=False, max_length=20)
+ >>> out = model.generate(**inputs, do_sample=False, max_length=20)
+
+ >>> # now we can instantiate the detector and check the generated text
+ >>> detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config=watermarking_config)
+ >>> detection_out_watermarked = detector(out_watermarked, return_dict=True)
+ >>> detection_out = detector(out, return_dict=True)
+ >>> detection_out_watermarked.prediction
+ array([ True, True])
+
+ >>> detection_out.prediction
+ array([False, False])
+ ```
+ """
+
+ def __init__(
+ self,
+ model_config: PretrainedConfig,
+ device: str,
+ watermarking_config: Union[WatermarkingConfig, Dict],
+ ignore_repeated_ngrams: bool = False,
+ max_cache_size: int = 128,
+ ):
+ if isinstance(watermarking_config, WatermarkingConfig):
+ watermarking_config = watermarking_config.to_dict()
+
+ self.bos_token_id = (
+ model_config.bos_token_id if not model_config.is_encoder_decoder else model_config.decoder_start_token_id
+ )
+ self.greenlist_ratio = watermarking_config["greenlist_ratio"]
+ self.ignore_repeated_ngrams = ignore_repeated_ngrams
+ self.processor = WatermarkLogitsProcessor(
+ vocab_size=model_config.vocab_size, device=device, **watermarking_config
+ )
+
+ # Expensive re-seeding and sampling is cached.
+ self._get_ngram_score_cached = lru_cache(maxsize=max_cache_size)(self._get_ngram_score)
+
+ def _get_ngram_score(self, prefix: torch.LongTensor, target: int):
+ greenlist_ids = self.processor._get_greenlist_ids(prefix)
+ return target in greenlist_ids
+
+ def _score_ngrams_in_passage(self, input_ids: torch.LongTensor):
+ batch_size, seq_length = input_ids.shape
+ selfhash = int(self.processor.seeding_scheme == "selfhash")
+ n = self.processor.context_width + 1 - selfhash
+ indices = torch.arange(n).unsqueeze(0) + torch.arange(seq_length - n + 1).unsqueeze(1)
+ ngram_tensors = input_ids[:, indices]
+
+ num_tokens_scored_batch = np.zeros(batch_size)
+ green_token_count_batch = np.zeros(batch_size)
+ for batch_idx in range(ngram_tensors.shape[0]):
+ frequencies_table = collections.Counter(ngram_tensors[batch_idx])
+ ngram_to_watermark_lookup = {}
+ for ngram_example in frequencies_table.keys():
+ prefix = ngram_example if selfhash else ngram_example[:-1]
+ target = ngram_example[-1]
+ ngram_to_watermark_lookup[ngram_example] = self._get_ngram_score_cached(prefix, target)
+
+ if self.ignore_repeated_ngrams:
+ # counts a green/red hit once per unique ngram.
+ # num total tokens scored becomes the number unique ngrams.
+ num_tokens_scored_batch[batch_idx] = len(frequencies_table.keys())
+ green_token_count_batch[batch_idx] = sum(ngram_to_watermark_lookup.values())
+ else:
+ num_tokens_scored_batch[batch_idx] = sum(frequencies_table.values())
+ green_token_count_batch[batch_idx] = sum(
+ freq * outcome
+ for freq, outcome in zip(frequencies_table.values(), ngram_to_watermark_lookup.values())
+ )
+ return num_tokens_scored_batch, green_token_count_batch
+
+ def _compute_z_score(self, green_token_count: np.array, total_num_tokens: np.array) -> np.array:
+ expected_count = self.greenlist_ratio
+ numer = green_token_count - expected_count * total_num_tokens
+ denom = np.sqrt(total_num_tokens * expected_count * (1 - expected_count))
+ z = numer / denom
+ return z
+
+ def _compute_pval(self, x, loc=0, scale=1):
+ z = (x - loc) / scale
+ return 1 - (0.5 * (1 + np.sign(z) * (1 - np.exp(-2 * z**2 / np.pi))))
+
+ 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 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 sensitivity of the detector. Higher z threshold gives less
+ sensitivity and vice versa for lower z threshold.
+ return_dict (`bool`, *optional*, defaults to `False`):
+ Whether to return `~generation.WatermarkDetectorOutput` or not. If not it will return boolean predictions,
+ ma
+ Return:
+ [`~generation.WatermarkDetectorOutput`] or `np.array`: A [`~generation.WatermarkDetectorOutput`]
+ if `return_dict=True` otherwise a `np.array`.
+
+ """
+
+ # Let's assume that if one batch start with `bos`, all batched also do
+ if input_ids[0, 0] == self.bos_token_id:
+ input_ids = input_ids[:, 1:]
+
+ if input_ids.shape[-1] - self.processor.context_width < 1:
+ raise ValueError(
+ f"Must have at least `1` token to score after the first "
+ f"min_prefix_len={self.processor.context_width} tokens required by the seeding scheme."
+ )
+
+ num_tokens_scored, green_token_count = self._score_ngrams_in_passage(input_ids)
+ z_score = self._compute_z_score(green_token_count, num_tokens_scored)
+ prediction = z_score > z_threshold
+
+ if return_dict:
+ p_value = self._compute_pval(z_score)
+ confidence = 1 - p_value
+
+ return WatermarkDetectorOutput(
+ num_tokens_scored=num_tokens_scored,
+ num_green_tokens=green_token_count,
+ green_fraction=green_token_count / num_tokens_scored,
+ z_score=z_score,
+ p_value=p_value,
+ prediction=prediction,
+ confidence=confidence,
+ )
+ return prediction
+
+
+class BayesianDetectorConfig(PretrainedConfig):
+ """
+ This is the configuration class to store the configuration of a [`BayesianDetectorModel`]. It is used to
+ instantiate a Bayesian Detector model according to the specified arguments.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ watermarking_depth (`int`, *optional*):
+ The number of tournament layers.
+ base_rate (`float1`, *optional*, defaults to 0.5):
+ Prior probability P(w) that a text is watermarked.
+ """
+
+ def __init__(self, watermarking_depth: int = None, base_rate: float = 0.5, **kwargs):
+ self.watermarking_depth = watermarking_depth
+ self.base_rate = base_rate
+ # These can be set later to store information about this detector.
+ self.model_name = None
+ self.watermarking_config = None
+
+ super().__init__(**kwargs)
+
+ def set_detector_information(self, model_name, watermarking_config):
+ self.model_name = model_name
+ self.watermarking_config = watermarking_config
+
+
+@dataclass
+class BayesianWatermarkDetectorModelOutput(ModelOutput):
+ """
+ Base class for outputs of models predicting if the text is watermarked.
+
+ Args:
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss.
+ posterior_probabilities (`torch.FloatTensor` of shape `(1,)`):
+ Multiple choice classification loss.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ posterior_probabilities: Optional[torch.FloatTensor] = None
+
+
+class BayesianDetectorWatermarkedLikelihood(nn.Module):
+ """Watermarked likelihood model for binary-valued g-values.
+
+ This takes in g-values and returns p(g_values|watermarked).
+ """
+
+ def __init__(self, watermarking_depth: int):
+ """Initializes the model parameters."""
+ super().__init__()
+ self.watermarking_depth = watermarking_depth
+ self.beta = torch.nn.Parameter(-2.5 + 0.001 * torch.randn(1, 1, watermarking_depth))
+ self.delta = torch.nn.Parameter(0.001 * torch.randn(1, 1, self.watermarking_depth, watermarking_depth))
+
+ 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:
+ p_one_unique_token and p_two_unique_tokens, both of shape
+ [batch_size, seq_len, watermarking_depth]. p_one_unique_token[i,t,l]
+ gives the probability of there being one unique token in a tournament
+ match on layer l, on timestep t, for batch item i.
+ p_one_unique_token[i,t,l] + p_two_unique_token[i,t,l] = 1.
+ """
+ # Tile g-values to produce feature vectors for predicting the latents
+ # for each layer in the tournament; our model for the latents psi is a
+ # logistic regression model psi = sigmoid(delta * x + beta).
+
+ # [batch_size, seq_len, watermarking_depth, watermarking_depth]
+ x = torch.repeat_interleave(torch.unsqueeze(g_values, dim=-2), self.watermarking_depth, axis=-2)
+
+ # mask all elements above -1 diagonal for autoregressive factorization
+ x = torch.tril(x, diagonal=-1)
+
+ # [batch_size, seq_len, watermarking_depth]
+ # (i, j, k, l) x (i, j, k, l) -> (i, j, k) einsum equivalent
+ logits = (self.delta[..., None, :] @ x.type(self.delta.dtype)[..., None]).squeeze() + self.beta
+
+ p_two_unique_tokens = torch.sigmoid(logits)
+ p_one_unique_token = 1 - p_two_unique_tokens
+ return p_one_unique_token, p_two_unique_tokens
+
+ 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) of shape [batch_size, seq_len, watermarking_depth].
+ """
+ p_one_unique_token, p_two_unique_tokens = self._compute_latents(g_values)
+
+ # P(g_tl | watermarked) is equal to
+ # 0.5 * [ (g_tl+0.5) * p_two_unique_tokens + p_one_unique_token].
+ return 0.5 * ((g_values + 0.5) * p_two_unique_tokens + p_one_unique_token)
+
+
+class BayesianDetectorModel(PreTrainedModel):
+ r"""
+ Bayesian classifier for watermark detection.
+
+ This detector uses Bayes' rule to compute a watermarking score, which is the sigmoid of the log of ratio of the
+ posterior probabilities P(watermarked|g_values) and P(unwatermarked|g_values). Please see the section on
+ BayesianScore in the paper for further details.
+ Paper URL: https://www.nature.com/articles/s41586-024-08025-4
+
+ Note that this detector only works with non-distortionary Tournament-based watermarking using the Bernoulli(0.5)
+ g-value distribution.
+
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`BayesianDetectorConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+ """
+
+ config_class = BayesianDetectorConfig
+ base_model_prefix = "model"
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.watermarking_depth = config.watermarking_depth
+ self.base_rate = config.base_rate
+ self.likelihood_model_watermarked = BayesianDetectorWatermarkedLikelihood(
+ watermarking_depth=self.watermarking_depth
+ )
+ self.prior = torch.nn.Parameter(torch.tensor([self.base_rate]))
+
+ def _init_weights(self, module):
+ """Initialize the weights."""
+ if isinstance(module, nn.Parameter):
+ module.weight.data.normal_(mean=0.0, std=0.02)
+
+ 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:
+ 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 shape `(batch, length, depth)`):
+ Likelihoods P(g_values|unwatermarked) of g-values under unwatermarked model.
+ mask (`torch.Tensor` of shape `(batch, length)`):
+ A binary array indicating which g-values should be used. g-values with mask value 0 are discarded.
+ prior (`float`):
+ the prior probability P(w) that the text is watermarked.
+
+ Returns:
+ Posterior probability P(watermarked|g_values), shape [batch].
+ """
+ mask = torch.unsqueeze(mask, dim=-1)
+ prior = torch.clamp(prior, min=1e-5, max=1 - 1e-5)
+ log_likelihoods_watermarked = torch.log(torch.clamp(likelihoods_watermarked, min=1e-30, max=float("inf")))
+ log_likelihoods_unwatermarked = torch.log(torch.clamp(likelihoods_unwatermarked, min=1e-30, max=float("inf")))
+ log_odds = log_likelihoods_watermarked - log_likelihoods_unwatermarked
+
+ # Sum relative surprisals (log odds) across all token positions and layers.
+ relative_surprisal_likelihood = torch.einsum("i...->i", log_odds * mask)
+
+ # Compute the relative surprisal prior
+ relative_surprisal_prior = torch.log(prior) - torch.log(1 - prior)
+
+ # Combine prior and likelihood.
+ # [batch_size]
+ relative_surprisal = relative_surprisal_prior + relative_surprisal_likelihood
+
+ # Compute the posterior probability P(w|g) = sigmoid(relative_surprisal).
+ return torch.sigmoid(relative_surprisal)
+
+ 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).
+
+ 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 g-values should be used. g-values with mask
+ value 0 are discarded.
+
+ Returns:
+ p(watermarked | g_values), of shape [batch_size].
+ """
+
+ likelihoods_watermarked = self.likelihood_model_watermarked(g_values)
+ likelihoods_unwatermarked = 0.5 * torch.ones_like(g_values)
+ out = self._compute_posterior(
+ likelihoods_watermarked=likelihoods_watermarked,
+ likelihoods_unwatermarked=likelihoods_unwatermarked,
+ mask=mask,
+ prior=self.prior,
+ )
+
+ loss = None
+ if labels is not None:
+ loss_fct = BCELoss()
+ loss_unwweight = torch.sum(self.likelihood_model_watermarked.delta**2)
+ loss_weight = loss_unwweight * loss_batch_weight
+ loss = loss_fct(torch.clamp(out, 1e-5, 1 - 1e-5), labels) + loss_weight
+
+ if not return_dict:
+ return (out,) if loss is None else (out, loss)
+
+ return BayesianWatermarkDetectorModelOutput(loss=loss, posterior_probabilities=out)
+
+
+class SynthIDTextWatermarkDetector:
+ r"""
+ SynthID text watermark detector class.
+
+ This class has to be initialized with the trained bayesian detector module check script
+ in examples/synthid_text/detector_training.py for example in training/saving/loading this
+ detector module. The folder also showcases example use case of this detector.
+
+ Parameters:
+ detector_module ([`BayesianDetectorModel`]):
+ Bayesian detector module object initialized with parameters.
+ Check examples/research_projects/synthid_text/detector_training.py for usage.
+ logits_processor (`SynthIDTextWatermarkLogitsProcessor`):
+ The logits processor used for watermarking.
+ tokenizer (`Any`):
+ The tokenizer used for the model.
+
+ Examples:
+ ```python
+ >>> from transformers import (
+ ... AutoTokenizer, BayesianDetectorModel, SynthIDTextWatermarkLogitsProcessor, SynthIDTextWatermarkDetector
+ ... )
+
+ >>> # Load the detector. See examples/research_projects/synthid_text for training a detector.
+ >>> detector_model = BayesianDetectorModel.from_pretrained("joaogante/dummy_synthid_detector")
+ >>> logits_processor = SynthIDTextWatermarkLogitsProcessor(
+ ... **detector_model.config.watermarking_config, device="cpu"
+ ... )
+ >>> tokenizer = AutoTokenizer.from_pretrained(detector_model.config.model_name)
+ >>> detector = SynthIDTextWatermarkDetector(detector_model, logits_processor, tokenizer)
+
+ >>> # Test whether a certain string is watermarked
+ >>> test_input = tokenizer(["This is a test input"], return_tensors="pt")
+ >>> is_watermarked = detector(test_input.input_ids)
+ ```
+ """
+
+ def __init__(
+ self,
+ detector_module: BayesianDetectorModel,
+ logits_processor: SynthIDTextWatermarkLogitsProcessor,
+ tokenizer: Any,
+ ):
+ self.detector_module = detector_module
+ self.logits_processor = logits_processor
+ self.tokenizer = tokenizer
+
+ def __call__(self, tokenized_outputs: torch.Tensor):
+ # eos mask is computed, skip first ngram_len - 1 tokens
+ # eos_mask will be of shape [batch_size, output_len]
+ eos_token_mask = self.logits_processor.compute_eos_token_mask(
+ input_ids=tokenized_outputs,
+ eos_token_id=self.tokenizer.eos_token_id,
+ )[:, self.logits_processor.ngram_len - 1 :]
+
+ # context repetition mask is computed
+ context_repetition_mask = self.logits_processor.compute_context_repetition_mask(
+ input_ids=tokenized_outputs,
+ )
+ # context repitition mask shape [batch_size, output_len - (ngram_len - 1)]
+
+ combined_mask = context_repetition_mask * eos_token_mask
+
+ g_values = self.logits_processor.compute_g_values(
+ input_ids=tokenized_outputs,
+ )
+ # g values shape [batch_size, output_len - (ngram_len - 1), depth]
+ return self.detector_module(g_values, combined_mask)
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/hf_argparser.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/hf_argparser.py
new file mode 100644
index 0000000000000000000000000000000000000000..625c6b90f511416069808a434bc92cd563d8cbcb
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/hf_argparser.py
@@ -0,0 +1,442 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import dataclasses
+import json
+import os
+import sys
+import types
+from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
+from copy import copy
+from enum import Enum
+from inspect import isclass
+from pathlib import Path
+from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints
+
+import yaml
+
+
+DataClass = NewType("DataClass", Any)
+DataClassType = NewType("DataClassType", Any)
+
+
+# From https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
+def string_to_bool(v):
+ if isinstance(v, bool):
+ return v
+ if v.lower() in ("yes", "true", "t", "y", "1"):
+ return True
+ elif v.lower() in ("no", "false", "f", "n", "0"):
+ return False
+ else:
+ raise ArgumentTypeError(
+ f"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)."
+ )
+
+
+def make_choice_type_function(choices: list) -> Callable[[str], Any]:
+ """
+ Creates a mapping function from each choices string representation to the actual value. Used to support multiple
+ value types for a single argument.
+
+ Args:
+ choices (list): List of choices.
+
+ Returns:
+ Callable[[str], Any]: Mapping function from string representation to actual value for each choice.
+ """
+ str_to_choice = {str(choice): choice for choice in choices}
+ return lambda arg: str_to_choice.get(arg, arg)
+
+
+def HfArg(
+ *,
+ aliases: Union[str, List[str]] = None,
+ help: str = None,
+ default: Any = dataclasses.MISSING,
+ default_factory: Callable[[], Any] = dataclasses.MISSING,
+ metadata: dict = None,
+ **kwargs,
+) -> dataclasses.Field:
+ """Argument helper enabling a concise syntax to create dataclass fields for parsing with `HfArgumentParser`.
+
+ Example comparing the use of `HfArg` and `dataclasses.field`:
+ ```
+ @dataclass
+ class Args:
+ regular_arg: str = dataclasses.field(default="Huggingface", metadata={"aliases": ["--example", "-e"], "help": "This syntax could be better!"})
+ hf_arg: str = HfArg(default="Huggingface", aliases=["--example", "-e"], help="What a nice syntax!")
+ ```
+
+ Args:
+ aliases (Union[str, List[str]], optional):
+ Single string or list of strings of aliases to pass on to argparse, e.g. `aliases=["--example", "-e"]`.
+ Defaults to None.
+ help (str, optional): Help string to pass on to argparse that can be displayed with --help. Defaults to None.
+ default (Any, optional):
+ Default value for the argument. If not default or default_factory is specified, the argument is required.
+ Defaults to dataclasses.MISSING.
+ default_factory (Callable[[], Any], optional):
+ The default_factory is a 0-argument function called to initialize a field's value. It is useful to provide
+ default values for mutable types, e.g. lists: `default_factory=list`. Mutually exclusive with `default=`.
+ Defaults to dataclasses.MISSING.
+ metadata (dict, optional): Further metadata to pass on to `dataclasses.field`. Defaults to None.
+
+ Returns:
+ Field: A `dataclasses.Field` with the desired properties.
+ """
+ if metadata is None:
+ # Important, don't use as default param in function signature because dict is mutable and shared across function calls
+ metadata = {}
+ if aliases is not None:
+ metadata["aliases"] = aliases
+ if help is not None:
+ metadata["help"] = help
+
+ return dataclasses.field(metadata=metadata, default=default, default_factory=default_factory, **kwargs)
+
+
+class HfArgumentParser(ArgumentParser):
+ """
+ This subclass of `argparse.ArgumentParser` uses type hints on dataclasses to generate arguments.
+
+ The class is designed to play well with the native argparse. In particular, you can add more (non-dataclass backed)
+ arguments to the parser after initialization and you'll get the output back after parsing as an additional
+ namespace. Optional: To create sub argument groups use the `_argument_group_name` attribute in the dataclass.
+
+ Args:
+ dataclass_types (`DataClassType` or `Iterable[DataClassType]`, *optional*):
+ Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Passed to `argparse.ArgumentParser()` in the regular way.
+ """
+
+ dataclass_types: Iterable[DataClassType]
+
+ def __init__(self, dataclass_types: Optional[Union[DataClassType, Iterable[DataClassType]]] = None, **kwargs):
+ # Make sure dataclass_types is an iterable
+ if dataclass_types is None:
+ dataclass_types = []
+ elif not isinstance(dataclass_types, Iterable):
+ dataclass_types = [dataclass_types]
+
+ # To make the default appear when using --help
+ if "formatter_class" not in kwargs:
+ kwargs["formatter_class"] = ArgumentDefaultsHelpFormatter
+ super().__init__(**kwargs)
+ if dataclasses.is_dataclass(dataclass_types):
+ dataclass_types = [dataclass_types]
+ self.dataclass_types = list(dataclass_types)
+ for dtype in self.dataclass_types:
+ self._add_dataclass_arguments(dtype)
+
+ @staticmethod
+ def _parse_dataclass_field(parser: ArgumentParser, field: dataclasses.Field):
+ # Long-option strings are conventionlly separated by hyphens rather
+ # than underscores, e.g., "--long-format" rather than "--long_format".
+ # Argparse converts hyphens to underscores so that the destination
+ # string is a valid attribute name. Hf_argparser should do the same.
+ long_options = [f"--{field.name}"]
+ if "_" in field.name:
+ long_options.append(f"--{field.name.replace('_', '-')}")
+
+ kwargs = field.metadata.copy()
+ # field.metadata is not used at all by Data Classes,
+ # it is provided as a third-party extension mechanism.
+ if isinstance(field.type, str):
+ raise RuntimeError(
+ "Unresolved type detected, which should have been done with the help of "
+ "`typing.get_type_hints` method by default"
+ )
+
+ aliases = kwargs.pop("aliases", [])
+ if isinstance(aliases, str):
+ aliases = [aliases]
+
+ origin_type = getattr(field.type, "__origin__", field.type)
+ if origin_type is Union or (hasattr(types, "UnionType") and isinstance(origin_type, types.UnionType)):
+ if str not in field.type.__args__ and (
+ len(field.type.__args__) != 2 or type(None) not in field.type.__args__
+ ):
+ raise ValueError(
+ "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because"
+ " the argument parser only supports one type per argument."
+ f" Problem encountered in field '{field.name}'."
+ )
+ if type(None) not in field.type.__args__:
+ # filter `str` in Union
+ field.type = field.type.__args__[0] if field.type.__args__[1] is str else field.type.__args__[1]
+ origin_type = getattr(field.type, "__origin__", field.type)
+ elif bool not in field.type.__args__:
+ # filter `NoneType` in Union (except for `Union[bool, NoneType]`)
+ field.type = (
+ field.type.__args__[0] if isinstance(None, field.type.__args__[1]) else field.type.__args__[1]
+ )
+ origin_type = getattr(field.type, "__origin__", field.type)
+
+ # A variable to store kwargs for a boolean field, if needed
+ # so that we can init a `no_*` complement argument (see below)
+ bool_kwargs = {}
+ if origin_type is Literal or (isinstance(field.type, type) and issubclass(field.type, Enum)):
+ if origin_type is Literal:
+ kwargs["choices"] = field.type.__args__
+ else:
+ kwargs["choices"] = [x.value for x in field.type]
+
+ kwargs["type"] = make_choice_type_function(kwargs["choices"])
+
+ if field.default is not dataclasses.MISSING:
+ kwargs["default"] = field.default
+ else:
+ kwargs["required"] = True
+ elif field.type is bool or field.type == Optional[bool]:
+ # Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
+ # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
+ bool_kwargs = copy(kwargs)
+
+ # Hack because type=bool in argparse does not behave as we want.
+ kwargs["type"] = string_to_bool
+ if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
+ # Default value is False if we have no default when of type bool.
+ default = False if field.default is dataclasses.MISSING else field.default
+ # This is the value that will get picked if we don't include --{field.name} in any way
+ kwargs["default"] = default
+ # This tells argparse we accept 0 or 1 value after --{field.name}
+ kwargs["nargs"] = "?"
+ # This is the value that will get picked if we do --{field.name} (without value)
+ kwargs["const"] = True
+ elif isclass(origin_type) and issubclass(origin_type, list):
+ kwargs["type"] = field.type.__args__[0]
+ kwargs["nargs"] = "+"
+ if field.default_factory is not dataclasses.MISSING:
+ kwargs["default"] = field.default_factory()
+ elif field.default is dataclasses.MISSING:
+ kwargs["required"] = True
+ else:
+ kwargs["type"] = field.type
+ if field.default is not dataclasses.MISSING:
+ kwargs["default"] = field.default
+ elif field.default_factory is not dataclasses.MISSING:
+ kwargs["default"] = field.default_factory()
+ else:
+ kwargs["required"] = True
+ parser.add_argument(*long_options, *aliases, **kwargs)
+
+ # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
+ # Order is important for arguments with the same destination!
+ # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
+ # here and we do not need those changes/additional keys.
+ if field.default is True and (field.type is bool or field.type == Optional[bool]):
+ bool_kwargs["default"] = False
+ parser.add_argument(
+ f"--no_{field.name}",
+ f"--no-{field.name.replace('_', '-')}",
+ action="store_false",
+ dest=field.name,
+ **bool_kwargs,
+ )
+
+ def _add_dataclass_arguments(self, dtype: DataClassType):
+ if hasattr(dtype, "_argument_group_name"):
+ parser = self.add_argument_group(dtype._argument_group_name)
+ else:
+ parser = self
+
+ try:
+ type_hints: Dict[str, type] = get_type_hints(dtype)
+ except NameError:
+ raise RuntimeError(
+ f"Type resolution failed for {dtype}. Try declaring the class in global scope or "
+ "removing line of `from __future__ import annotations` which opts in Postponed "
+ "Evaluation of Annotations (PEP 563)"
+ )
+ except TypeError as ex:
+ # Remove this block when we drop Python 3.9 support
+ if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(ex):
+ python_version = ".".join(map(str, sys.version_info[:3]))
+ raise RuntimeError(
+ f"Type resolution failed for {dtype} on Python {python_version}. Try removing "
+ "line of `from __future__ import annotations` which opts in union types as "
+ "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To "
+ "support Python versions that lower than 3.10, you need to use "
+ "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of "
+ "`X | None`."
+ ) from ex
+ raise
+
+ for field in dataclasses.fields(dtype):
+ if not field.init:
+ continue
+ field.type = type_hints[field.name]
+ self._parse_dataclass_field(parser, field)
+
+ def parse_args_into_dataclasses(
+ self,
+ args=None,
+ return_remaining_strings=False,
+ look_for_args_file=True,
+ args_filename=None,
+ args_file_flag=None,
+ ) -> Tuple[DataClass, ...]:
+ """
+ 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. The default is taken from sys.argv. (same as argparse.ArgumentParser)
+ return_remaining_strings:
+ If true, also return a list of remaining argument strings.
+ look_for_args_file:
+ If true, will look for a ".args" file with the same base name as the entry point script for this
+ process, and will append its potential content to the command line args.
+ args_filename:
+ If not None, will uses this file instead of the ".args" file specified in the previous argument.
+ args_file_flag:
+ If not None, will look for a file in the command-line args specified with this flag. The flag can be
+ specified multiple times and precedence is determined by the order (last one wins).
+
+ Returns:
+ Tuple consisting of:
+
+ - the dataclass instances in the same order as they were passed to the initializer.abspath
+ - if applicable, an additional namespace for more (non-dataclass backed) arguments added to the parser
+ after initialization.
+ - The potential list of remaining argument strings. (same as argparse.ArgumentParser.parse_known_args)
+ """
+
+ if args_file_flag or args_filename or (look_for_args_file and len(sys.argv)):
+ args_files = []
+
+ if args_filename:
+ args_files.append(Path(args_filename))
+ elif look_for_args_file and len(sys.argv):
+ args_files.append(Path(sys.argv[0]).with_suffix(".args"))
+
+ # args files specified via command line flag should overwrite default args files so we add them last
+ if args_file_flag:
+ # Create special parser just to extract the args_file_flag values
+ args_file_parser = ArgumentParser()
+ args_file_parser.add_argument(args_file_flag, type=str, action="append")
+
+ # Use only remaining args for further parsing (remove the args_file_flag)
+ cfg, args = args_file_parser.parse_known_args(args=args)
+ cmd_args_file_paths = vars(cfg).get(args_file_flag.lstrip("-"), None)
+
+ if cmd_args_file_paths:
+ args_files.extend([Path(p) for p in cmd_args_file_paths])
+
+ file_args = []
+ for args_file in args_files:
+ if args_file.exists():
+ file_args += args_file.read_text().split()
+
+ # in case of duplicate arguments the last one has precedence
+ # args specified via the command line should overwrite args from files, so we add them last
+ args = file_args + args if args is not None else file_args + sys.argv[1:]
+ namespace, remaining_args = self.parse_known_args(args=args)
+ outputs = []
+ for dtype in self.dataclass_types:
+ keys = {f.name for f in dataclasses.fields(dtype) if f.init}
+ inputs = {k: v for k, v in vars(namespace).items() if k in keys}
+ for k in keys:
+ delattr(namespace, k)
+ obj = dtype(**inputs)
+ outputs.append(obj)
+ if len(namespace.__dict__) > 0:
+ # additional namespace.
+ outputs.append(namespace)
+ if return_remaining_strings:
+ return (*outputs, remaining_args)
+ else:
+ if remaining_args:
+ raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {remaining_args}")
+
+ return (*outputs,)
+
+ 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 containing config values
+ allow_extra_keys (`bool`, *optional*, defaults to `False`):
+ Defaults to False. If False, will raise an exception if the dict contains keys that are not parsed.
+
+ Returns:
+ Tuple consisting of:
+
+ - the dataclass instances in the same order as they were passed to the initializer.
+ """
+ unused_keys = set(args.keys())
+ outputs = []
+ for dtype in self.dataclass_types:
+ keys = {f.name for f in dataclasses.fields(dtype) if f.init}
+ inputs = {k: v for k, v in args.items() if k in keys}
+ unused_keys.difference_update(inputs.keys())
+ obj = dtype(**inputs)
+ outputs.append(obj)
+ if not allow_extra_keys and unused_keys:
+ raise ValueError(f"Some keys are not used by the HfArgumentParser: {sorted(unused_keys)}")
+ return tuple(outputs)
+
+ def parse_json_file(
+ self, json_file: Union[str, os.PathLike], 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`):
+ File name of the json file to parse
+ allow_extra_keys (`bool`, *optional*, defaults to `False`):
+ Defaults to False. If False, will raise an exception if the json file contains keys that are not
+ parsed.
+
+ Returns:
+ Tuple consisting of:
+
+ - the dataclass instances in the same order as they were passed to the initializer.
+ """
+ with open(Path(json_file), encoding="utf-8") as open_json_file:
+ data = json.loads(open_json_file.read())
+ outputs = self.parse_dict(data, allow_extra_keys=allow_extra_keys)
+ return tuple(outputs)
+
+ def parse_yaml_file(
+ self, yaml_file: Union[str, os.PathLike], allow_extra_keys: bool = False
+ ) -> Tuple[DataClass, ...]:
+ """
+ Alternative helper method that does not use `argparse` at all, instead loading a yaml file and populating the
+ dataclass types.
+
+ Args:
+ yaml_file (`str` or `os.PathLike`):
+ File name of the yaml file to parse
+ allow_extra_keys (`bool`, *optional*, defaults to `False`):
+ Defaults to False. If False, will raise an exception if the json file contains keys that are not
+ parsed.
+
+ Returns:
+ Tuple consisting of:
+
+ - the dataclass instances in the same order as they were passed to the initializer.
+ """
+ outputs = self.parse_dict(yaml.safe_load(Path(yaml_file).read_text()), allow_extra_keys=allow_extra_keys)
+ return tuple(outputs)
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/hyperparameter_search.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/hyperparameter_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..c14165165ca1f92fb28e27b718c8bd81e1bc3a93
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/hyperparameter_search.py
@@ -0,0 +1,141 @@
+# coding=utf-8
+# Copyright 2023-present the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from .integrations import (
+ is_optuna_available,
+ is_ray_tune_available,
+ is_sigopt_available,
+ is_wandb_available,
+ run_hp_search_optuna,
+ run_hp_search_ray,
+ run_hp_search_sigopt,
+ run_hp_search_wandb,
+)
+from .trainer_utils import (
+ HPSearchBackend,
+ default_hp_space_optuna,
+ default_hp_space_ray,
+ default_hp_space_sigopt,
+ default_hp_space_wandb,
+)
+from .utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class HyperParamSearchBackendBase:
+ name: str
+ pip_package: str = None
+
+ @staticmethod
+ def is_available():
+ raise NotImplementedError
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ raise NotImplementedError
+
+ def default_hp_space(self, trial):
+ raise NotImplementedError
+
+ def ensure_available(self):
+ if not self.is_available():
+ raise RuntimeError(
+ f"You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}."
+ )
+
+ @classmethod
+ def pip_install(cls):
+ return f"`pip install {cls.pip_package or cls.name}`"
+
+
+class OptunaBackend(HyperParamSearchBackendBase):
+ name = "optuna"
+
+ @staticmethod
+ def is_available():
+ return is_optuna_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_optuna(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_optuna(trial)
+
+
+class RayTuneBackend(HyperParamSearchBackendBase):
+ name = "ray"
+ pip_package = "'ray[tune]'"
+
+ @staticmethod
+ def is_available():
+ return is_ray_tune_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_ray(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_ray(trial)
+
+
+class SigOptBackend(HyperParamSearchBackendBase):
+ name = "sigopt"
+
+ @staticmethod
+ def is_available():
+ return is_sigopt_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_sigopt(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_sigopt(trial)
+
+
+class WandbBackend(HyperParamSearchBackendBase):
+ name = "wandb"
+
+ @staticmethod
+ def is_available():
+ return is_wandb_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_wandb(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_wandb(trial)
+
+
+ALL_HYPERPARAMETER_SEARCH_BACKENDS = {
+ HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
+}
+
+
+def default_hp_search_backend() -> str:
+ available_backends = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
+ if len(available_backends) > 0:
+ name = available_backends[0].name
+ if len(available_backends) > 1:
+ logger.info(
+ f"{len(available_backends)} hyperparameter search backends available. Using {name} as the default."
+ )
+ return name
+ raise RuntimeError(
+ "No hyperparameter search backend available.\n"
+ + "\n".join(
+ f" - To install {backend.name} run {backend.pip_install()}"
+ for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values()
+ )
+ )
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_processing_base.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_processing_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6ce7af3fa8076958d4a4ac87ca3ab13716c7955
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_processing_base.py
@@ -0,0 +1,559 @@
+# coding=utf-8
+# Copyright 2020 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import copy
+import json
+import os
+import warnings
+from io import BytesIO
+from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union
+
+import numpy as np
+import requests
+
+from .dynamic_module_utils import custom_object_save
+from .feature_extraction_utils import BatchFeature as BaseBatchFeature
+from .utils import (
+ IMAGE_PROCESSOR_NAME,
+ PushToHubMixin,
+ add_model_info_to_auto_map,
+ add_model_info_to_custom_pipelines,
+ cached_file,
+ copy_func,
+ download_url,
+ is_offline_mode,
+ is_remote_url,
+ is_vision_available,
+ logging,
+)
+
+
+if is_vision_available():
+ from PIL import Image
+
+
+ImageProcessorType = TypeVar("ImageProcessorType", bound="ImageProcessingMixin")
+
+
+logger = logging.get_logger(__name__)
+
+
+# TODO: Move BatchFeature to be imported by both image_processing_utils and image_processing_utils
+# We override the class string here, but logic is the same.
+class BatchFeature(BaseBatchFeature):
+ r"""
+ Holds the output of the image processor specific `__call__` methods.
+
+ This class is derived from a python dictionary and can be used as a dictionary.
+
+ Args:
+ data (`dict`):
+ Dictionary of lists/arrays/tensors returned by the __call__ method ('pixel_values', etc.).
+ tensor_type (`Union[None, str, TensorType]`, *optional*):
+ You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
+ initialization.
+ """
+
+
+# TODO: (Amy) - factor out the common parts of this and the feature extractor
+class ImageProcessingMixin(PushToHubMixin):
+ """
+ This is an image processor mixin used to provide saving/loading functionality for sequential and image feature
+ extractors.
+ """
+
+ _auto_class = None
+
+ def __init__(self, **kwargs):
+ """Set elements of `kwargs` as attributes."""
+ # This key was saved while we still used `XXXFeatureExtractor` for image processing. Now we use
+ # `XXXImageProcessor`, this attribute and its value are misleading.
+ kwargs.pop("feature_extractor_type", None)
+ # Pop "processor_class" as it should be saved as private attribute
+ self._processor_class = kwargs.pop("processor_class", None)
+ # Additional attributes without default values
+ for key, value in kwargs.items():
+ try:
+ setattr(self, key, value)
+ except AttributeError as err:
+ logger.error(f"Can't set {key} with value {value} for {self}")
+ raise err
+
+ def _set_processor_class(self, processor_class: str):
+ """Sets processor class as an attribute."""
+ self._processor_class = processor_class
+
+ @classmethod
+ def from_pretrained(
+ cls: Type[ImageProcessorType],
+ pretrained_model_name_or_path: Union[str, os.PathLike],
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
+ force_download: bool = False,
+ local_files_only: bool = False,
+ token: Optional[Union[str, bool]] = None,
+ revision: str = "main",
+ **kwargs,
+ ) -> ImageProcessorType:
+ r"""
+ Instantiate a type of [`~image_processing_utils.ImageProcessingMixin`] from an image processor.
+
+ Args:
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
+ This can be either:
+
+ - a string, the *model id* of a pretrained image_processor hosted inside a model repo on
+ huggingface.co.
+ - a path to a *directory* containing a image processor file saved using the
+ [`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g.,
+ `./my_model_directory/`.
+ - a path or url to a saved image processor JSON *file*, e.g.,
+ `./my_model_directory/preprocessor_config.json`.
+ cache_dir (`str` or `os.PathLike`, *optional*):
+ Path to a directory in which a downloaded pretrained model image processor should be cached if the
+ standard cache should not be used.
+ force_download (`bool`, *optional*, defaults to `False`):
+ Whether or not to force to (re-)download the image processor files and override the cached versions if
+ they exist.
+ resume_download:
+ Deprecated and ignored. All downloads are now resumed by default when possible.
+ Will be removed in v5 of Transformers.
+ proxies (`Dict[str, str]`, *optional*):
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
+ token (`str` or `bool`, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
+ the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
+ revision (`str`, *optional*, defaults to `"main"`):
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
+ identifier allowed by git.
+
+
+
+
+ To test a pull request you made on the Hub, you can pass `revision="refs/pr/"`.
+
+
+
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
+ If `False`, then this function returns just the final image processor object. If `True`, then this
+ functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary
+ consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part of
+ `kwargs` which has not been used to update `image_processor` and is otherwise ignored.
+ subfolder (`str`, *optional*, defaults to `""`):
+ In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
+ specify the folder name here.
+ kwargs (`Dict[str, Any]`, *optional*):
+ The values in kwargs of any keys which are image processor attributes will be used to override the
+ loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is
+ controlled by the `return_unused_kwargs` keyword parameter.
+
+ Returns:
+ A image processor of type [`~image_processing_utils.ImageProcessingMixin`].
+
+ Examples:
+
+ ```python
+ # We can't instantiate directly the base class *ImageProcessingMixin* so let's show the examples on a
+ # derived class: *CLIPImageProcessor*
+ image_processor = CLIPImageProcessor.from_pretrained(
+ "openai/clip-vit-base-patch32"
+ ) # Download image_processing_config from huggingface.co and cache.
+ image_processor = CLIPImageProcessor.from_pretrained(
+ "./test/saved_model/"
+ ) # E.g. image processor (or model) was saved using *save_pretrained('./test/saved_model/')*
+ image_processor = CLIPImageProcessor.from_pretrained("./test/saved_model/preprocessor_config.json")
+ image_processor = CLIPImageProcessor.from_pretrained(
+ "openai/clip-vit-base-patch32", do_normalize=False, foo=False
+ )
+ assert image_processor.do_normalize is False
+ image_processor, unused_kwargs = CLIPImageProcessor.from_pretrained(
+ "openai/clip-vit-base-patch32", do_normalize=False, foo=False, return_unused_kwargs=True
+ )
+ assert image_processor.do_normalize is False
+ assert unused_kwargs == {"foo": False}
+ ```"""
+ kwargs["cache_dir"] = cache_dir
+ kwargs["force_download"] = force_download
+ kwargs["local_files_only"] = local_files_only
+ kwargs["revision"] = revision
+
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
+ FutureWarning,
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
+ if token is not None:
+ kwargs["token"] = token
+
+ image_processor_dict, kwargs = cls.get_image_processor_dict(pretrained_model_name_or_path, **kwargs)
+
+ return cls.from_dict(image_processor_dict, **kwargs)
+
+ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
+ """
+ Save an image processor object to the directory `save_directory`, so that it can be re-loaded using the
+ [`~image_processing_utils.ImageProcessingMixin.from_pretrained`] class method.
+
+ Args:
+ save_directory (`str` or `os.PathLike`):
+ Directory where the image processor JSON file will be saved (will be created if it does not exist).
+ push_to_hub (`bool`, *optional*, defaults to `False`):
+ Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
+ namespace).
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
+ """
+ use_auth_token = kwargs.pop("use_auth_token", None)
+
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
+ FutureWarning,
+ )
+ if kwargs.get("token", None) is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ kwargs["token"] = use_auth_token
+
+ if os.path.isfile(save_directory):
+ raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
+
+ os.makedirs(save_directory, exist_ok=True)
+
+ if push_to_hub:
+ commit_message = kwargs.pop("commit_message", None)
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
+ repo_id = self._create_repo(repo_id, **kwargs)
+ files_timestamps = self._get_files_timestamps(save_directory)
+
+ # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
+ # loaded from the Hub.
+ if self._auto_class is not None:
+ custom_object_save(self, save_directory, config=self)
+
+ # If we save using the predefined names, we can load using `from_pretrained`
+ output_image_processor_file = os.path.join(save_directory, IMAGE_PROCESSOR_NAME)
+
+ self.to_json_file(output_image_processor_file)
+ logger.info(f"Image processor saved in {output_image_processor_file}")
+
+ if push_to_hub:
+ self._upload_modified_files(
+ save_directory,
+ repo_id,
+ files_timestamps,
+ commit_message=commit_message,
+ token=kwargs.get("token"),
+ )
+
+ return [output_image_processor_file]
+
+ @classmethod
+ def get_image_processor_dict(
+ cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
+ """
+ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
+ image processor of type [`~image_processor_utils.ImageProcessingMixin`] using `from_dict`.
+
+ Parameters:
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
+ The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
+ subfolder (`str`, *optional*, defaults to `""`):
+ In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
+ specify the folder name here.
+ image_processor_filename (`str`, *optional*, defaults to `"config.json"`):
+ The name of the file in the model directory to use for the image processor config.
+
+ Returns:
+ `Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the image processor object.
+ """
+ cache_dir = kwargs.pop("cache_dir", None)
+ force_download = kwargs.pop("force_download", False)
+ resume_download = kwargs.pop("resume_download", None)
+ proxies = kwargs.pop("proxies", None)
+ token = kwargs.pop("token", None)
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ local_files_only = kwargs.pop("local_files_only", False)
+ revision = kwargs.pop("revision", None)
+ subfolder = kwargs.pop("subfolder", "")
+ image_processor_filename = kwargs.pop("image_processor_filename", IMAGE_PROCESSOR_NAME)
+
+ from_pipeline = kwargs.pop("_from_pipeline", None)
+ from_auto_class = kwargs.pop("_from_auto", False)
+
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
+ FutureWarning,
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
+ user_agent = {"file_type": "image processor", "from_auto_class": from_auto_class}
+ if from_pipeline is not None:
+ user_agent["using_pipeline"] = from_pipeline
+
+ if is_offline_mode() and not local_files_only:
+ logger.info("Offline mode: forcing local_files_only=True")
+ local_files_only = True
+
+ pretrained_model_name_or_path = str(pretrained_model_name_or_path)
+ is_local = os.path.isdir(pretrained_model_name_or_path)
+ if os.path.isdir(pretrained_model_name_or_path):
+ image_processor_file = os.path.join(pretrained_model_name_or_path, image_processor_filename)
+ if os.path.isfile(pretrained_model_name_or_path):
+ resolved_image_processor_file = pretrained_model_name_or_path
+ is_local = True
+ elif is_remote_url(pretrained_model_name_or_path):
+ image_processor_file = pretrained_model_name_or_path
+ resolved_image_processor_file = download_url(pretrained_model_name_or_path)
+ else:
+ image_processor_file = image_processor_filename
+ try:
+ # Load from local folder or from cache or download from model Hub and cache
+ resolved_image_processor_file = cached_file(
+ pretrained_model_name_or_path,
+ image_processor_file,
+ cache_dir=cache_dir,
+ force_download=force_download,
+ proxies=proxies,
+ resume_download=resume_download,
+ local_files_only=local_files_only,
+ token=token,
+ user_agent=user_agent,
+ revision=revision,
+ subfolder=subfolder,
+ )
+ except EnvironmentError:
+ # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
+ # the original exception.
+ raise
+ except Exception:
+ # For any other exception, we throw a generic error.
+ raise EnvironmentError(
+ f"Can't load image processor for '{pretrained_model_name_or_path}'. If you were trying to load"
+ " it from 'https://huggingface.co/models', make sure you don't have a local directory with the"
+ f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
+ f" directory containing a {image_processor_filename} file"
+ )
+
+ try:
+ # Load image_processor dict
+ with open(resolved_image_processor_file, "r", encoding="utf-8") as reader:
+ text = reader.read()
+ image_processor_dict = json.loads(text)
+
+ except json.JSONDecodeError:
+ raise EnvironmentError(
+ f"It looks like the config file at '{resolved_image_processor_file}' is not a valid JSON file."
+ )
+
+ if is_local:
+ logger.info(f"loading configuration file {resolved_image_processor_file}")
+ else:
+ logger.info(
+ f"loading configuration file {image_processor_file} from cache at {resolved_image_processor_file}"
+ )
+ if "auto_map" in image_processor_dict:
+ image_processor_dict["auto_map"] = add_model_info_to_auto_map(
+ image_processor_dict["auto_map"], pretrained_model_name_or_path
+ )
+ if "custom_pipelines" in image_processor_dict:
+ image_processor_dict["custom_pipelines"] = add_model_info_to_custom_pipelines(
+ image_processor_dict["custom_pipelines"], pretrained_model_name_or_path
+ )
+
+ return image_processor_dict, kwargs
+
+ @classmethod
+ def from_dict(cls, image_processor_dict: Dict[str, Any], **kwargs):
+ """
+ Instantiates a type of [`~image_processing_utils.ImageProcessingMixin`] from a Python dictionary of parameters.
+
+ Args:
+ image_processor_dict (`Dict[str, Any]`):
+ Dictionary that will be used to instantiate the image processor object. Such a dictionary can be
+ retrieved from a pretrained checkpoint by leveraging the
+ [`~image_processing_utils.ImageProcessingMixin.to_dict`] method.
+ kwargs (`Dict[str, Any]`):
+ Additional parameters from which to initialize the image processor object.
+
+ Returns:
+ [`~image_processing_utils.ImageProcessingMixin`]: The image processor object instantiated from those
+ parameters.
+ """
+ image_processor_dict = image_processor_dict.copy()
+ return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
+
+ # The `size` parameter is a dict and was previously an int or tuple in feature extractors.
+ # We set `size` here directly to the `image_processor_dict` so that it is converted to the appropriate
+ # dict within the image processor and isn't overwritten if `size` is passed in as a kwarg.
+ if "size" in kwargs and "size" in image_processor_dict:
+ image_processor_dict["size"] = kwargs.pop("size")
+ if "crop_size" in kwargs and "crop_size" in image_processor_dict:
+ image_processor_dict["crop_size"] = kwargs.pop("crop_size")
+
+ image_processor = cls(**image_processor_dict)
+
+ # Update image_processor with kwargs if needed
+ to_remove = []
+ for key, value in kwargs.items():
+ if hasattr(image_processor, key):
+ setattr(image_processor, key, value)
+ to_remove.append(key)
+ for key in to_remove:
+ kwargs.pop(key, None)
+
+ logger.info(f"Image processor {image_processor}")
+ if return_unused_kwargs:
+ return image_processor, kwargs
+ else:
+ return image_processor
+
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary.
+
+ Returns:
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this image processor instance.
+ """
+ output = copy.deepcopy(self.__dict__)
+ output["image_processor_type"] = self.__class__.__name__
+
+ return output
+
+ @classmethod
+ def from_json_file(cls, json_file: Union[str, os.PathLike]):
+ """
+ Instantiates a image processor of type [`~image_processing_utils.ImageProcessingMixin`] from the path to a JSON
+ file of parameters.
+
+ Args:
+ json_file (`str` or `os.PathLike`):
+ Path to the JSON file containing the parameters.
+
+ Returns:
+ A image processor of type [`~image_processing_utils.ImageProcessingMixin`]: The image_processor object
+ instantiated from that JSON file.
+ """
+ with open(json_file, "r", encoding="utf-8") as reader:
+ text = reader.read()
+ image_processor_dict = json.loads(text)
+ return cls(**image_processor_dict)
+
+ def to_json_string(self) -> str:
+ """
+ Serializes this instance to a JSON string.
+
+ Returns:
+ `str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
+ """
+ dictionary = self.to_dict()
+
+ for key, value in dictionary.items():
+ if isinstance(value, np.ndarray):
+ dictionary[key] = value.tolist()
+
+ # make sure private name "_processor_class" is correctly
+ # saved as "processor_class"
+ _processor_class = dictionary.pop("_processor_class", None)
+ if _processor_class is not None:
+ dictionary["processor_class"] = _processor_class
+
+ return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
+
+ def to_json_file(self, json_file_path: Union[str, os.PathLike]):
+ """
+ Save this instance to a JSON file.
+
+ Args:
+ json_file_path (`str` or `os.PathLike`):
+ Path to the JSON file in which this image_processor instance's parameters will be saved.
+ """
+ with open(json_file_path, "w", encoding="utf-8") as writer:
+ writer.write(self.to_json_string())
+
+ def __repr__(self):
+ return f"{self.__class__.__name__} {self.to_json_string()}"
+
+ @classmethod
+ def register_for_auto_class(cls, auto_class="AutoImageProcessor"):
+ """
+ Register this class with a given auto class. This should only be used for custom image processors as the ones
+ in the library are already mapped with `AutoImageProcessor `.
+
+
+
+ This API is experimental and may have some slight breaking changes in the next releases.
+
+
+
+ Args:
+ auto_class (`str` or `type`, *optional*, defaults to `"AutoImageProcessor "`):
+ The auto class to register this new image processor with.
+ """
+ if not isinstance(auto_class, str):
+ auto_class = auto_class.__name__
+
+ import transformers.models.auto as auto_module
+
+ if not hasattr(auto_module, auto_class):
+ raise ValueError(f"{auto_class} is not a valid auto class.")
+
+ cls._auto_class = auto_class
+
+ def fetch_images(self, image_url_or_urls: Union[str, List[str]]):
+ """
+ Convert a single or a list of urls into the corresponding `PIL.Image` objects.
+
+ If a single url is passed, the return value will be a single object. If a list is passed a list of objects is
+ returned.
+ """
+ headers = {
+ "User-Agent": (
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0"
+ " Safari/537.36"
+ )
+ }
+ if isinstance(image_url_or_urls, list):
+ return [self.fetch_images(x) for x in image_url_or_urls]
+ elif isinstance(image_url_or_urls, str):
+ response = requests.get(image_url_or_urls, stream=True, headers=headers)
+ response.raise_for_status()
+ return Image.open(BytesIO(response.content))
+ else:
+ raise TypeError(f"only a single or a list of entries is supported but got type={type(image_url_or_urls)}")
+
+
+ImageProcessingMixin.push_to_hub = copy_func(ImageProcessingMixin.push_to_hub)
+if ImageProcessingMixin.push_to_hub.__doc__ is not None:
+ ImageProcessingMixin.push_to_hub.__doc__ = ImageProcessingMixin.push_to_hub.__doc__.format(
+ object="image processor", object_class="AutoImageProcessor", object_files="image processor file"
+ )
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_processing_utils.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_processing_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..59aea9b8a5a8d7e207455d72d3e42b0705f1bd7c
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_processing_utils.py
@@ -0,0 +1,308 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Dict, Iterable, Optional, Union
+
+import numpy as np
+
+from .image_processing_base import BatchFeature, ImageProcessingMixin
+from .image_transforms import center_crop, normalize, rescale
+from .image_utils import ChannelDimension, get_image_size
+from .utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+INIT_SERVICE_KWARGS = [
+ "processor_class",
+ "image_processor_type",
+]
+
+
+class BaseImageProcessor(ImageProcessingMixin):
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ def __call__(self, images, **kwargs) -> BatchFeature:
+ """Preprocess an image or a batch of images."""
+ return self.preprocess(images, **kwargs)
+
+ def preprocess(self, images, **kwargs) -> BatchFeature:
+ raise NotImplementedError("Each image processor must implement its own preprocess method")
+
+ def rescale(
+ self,
+ image: np.ndarray,
+ scale: float,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Rescale an image by a scale factor. image = image * scale.
+
+ Args:
+ image (`np.ndarray`):
+ Image to rescale.
+ scale (`float`):
+ The scaling factor to rescale pixel values by.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+
+ Returns:
+ `np.ndarray`: The rescaled image.
+ """
+ return rescale(image, scale=scale, data_format=data_format, input_data_format=input_data_format, **kwargs)
+
+ def normalize(
+ self,
+ image: np.ndarray,
+ mean: Union[float, Iterable[float]],
+ std: Union[float, Iterable[float]],
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Normalize an image. image = (image - image_mean) / image_std.
+
+ Args:
+ image (`np.ndarray`):
+ Image to normalize.
+ mean (`float` or `Iterable[float]`):
+ Image mean to use for normalization.
+ std (`float` or `Iterable[float]`):
+ Image standard deviation to use for normalization.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+
+ Returns:
+ `np.ndarray`: The normalized image.
+ """
+ return normalize(
+ image, mean=mean, std=std, data_format=data_format, input_data_format=input_data_format, **kwargs
+ )
+
+ def center_crop(
+ self,
+ image: np.ndarray,
+ size: Dict[str, int],
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Center crop an image to `(size["height"], size["width"])`. If the input size is smaller than `crop_size` along
+ any edge, the image is padded with 0's and then center cropped.
+
+ Args:
+ image (`np.ndarray`):
+ Image to center crop.
+ size (`Dict[str, int]`):
+ Size of the output image.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ """
+ size = get_size_dict(size)
+ if "height" not in size or "width" not in size:
+ raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}")
+ return center_crop(
+ image,
+ size=(size["height"], size["width"]),
+ data_format=data_format,
+ input_data_format=input_data_format,
+ **kwargs,
+ )
+
+ def to_dict(self):
+ encoder_dict = super().to_dict()
+ encoder_dict.pop("_valid_processor_keys", None)
+ return encoder_dict
+
+
+VALID_SIZE_DICT_KEYS = (
+ {"height", "width"},
+ {"shortest_edge"},
+ {"shortest_edge", "longest_edge"},
+ {"longest_edge"},
+ {"max_height", "max_width"},
+)
+
+
+def is_valid_size_dict(size_dict):
+ if not isinstance(size_dict, dict):
+ return False
+
+ size_dict_keys = set(size_dict.keys())
+ for allowed_keys in VALID_SIZE_DICT_KEYS:
+ if size_dict_keys == allowed_keys:
+ return True
+ return False
+
+
+def convert_to_size_dict(
+ size, max_size: Optional[int] = None, default_to_square: bool = True, height_width_order: bool = True
+):
+ # By default, if size is an int we assume it represents a tuple of (size, size).
+ if isinstance(size, int) and default_to_square:
+ if max_size is not None:
+ raise ValueError("Cannot specify both size as an int, with default_to_square=True and max_size")
+ return {"height": size, "width": size}
+ # In other configs, if size is an int and default_to_square is False, size represents the length of
+ # the shortest edge after resizing.
+ elif isinstance(size, int) and not default_to_square:
+ size_dict = {"shortest_edge": size}
+ if max_size is not None:
+ size_dict["longest_edge"] = max_size
+ return size_dict
+ # Otherwise, if size is a tuple it's either (height, width) or (width, height)
+ elif isinstance(size, (tuple, list)) and height_width_order:
+ return {"height": size[0], "width": size[1]}
+ elif isinstance(size, (tuple, list)) and not height_width_order:
+ return {"height": size[1], "width": size[0]}
+ elif size is None and max_size is not None:
+ if default_to_square:
+ raise ValueError("Cannot specify both default_to_square=True and max_size")
+ return {"longest_edge": max_size}
+
+ raise ValueError(f"Could not convert size input to size dict: {size}")
+
+
+def get_size_dict(
+ size: Union[int, Iterable[int], Dict[str, int]] = None,
+ max_size: Optional[int] = None,
+ height_width_order: bool = True,
+ default_to_square: bool = True,
+ param_name="size",
+) -> dict:
+ """
+ Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards
+ compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,
+ width) or (width, height) format.
+
+ - If `size` is tuple, it is converted to `{"height": size[0], "width": size[1]}` or `{"height": size[1], "width":
+ size[0]}` if `height_width_order` is `False`.
+ - If `size` is an int, and `default_to_square` is `True`, it is converted to `{"height": size, "width": size}`.
+ - If `size` is an int and `default_to_square` is False, it is converted to `{"shortest_edge": size}`. If `max_size`
+ is set, it is added to the dict as `{"longest_edge": max_size}`.
+
+ Args:
+ size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):
+ The `size` parameter to be cast into a size dictionary.
+ max_size (`Optional[int]`, *optional*):
+ The `max_size` parameter to be cast into a size dictionary.
+ height_width_order (`bool`, *optional*, defaults to `True`):
+ If `size` is a tuple, whether it's in (height, width) or (width, height) order.
+ default_to_square (`bool`, *optional*, defaults to `True`):
+ If `size` is an int, whether to default to a square image or not.
+ """
+ if not isinstance(size, dict):
+ size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)
+ logger.info(
+ f"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}."
+ f" Converted to {size_dict}.",
+ )
+ else:
+ size_dict = size
+
+ if not is_valid_size_dict(size_dict):
+ raise ValueError(
+ f"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}"
+ )
+ return size_dict
+
+
+def select_best_resolution(original_size: tuple, possible_resolutions: list) -> tuple:
+ """
+ Selects the best resolution from a list of possible resolutions based on the original size.
+
+ This is done by calculating the effective and wasted resolution for each possible resolution.
+
+ The best fit resolution is the one that maximizes the effective resolution and minimizes the wasted resolution.
+
+ Args:
+ original_size (tuple):
+ The original size of the image in the format (height, width).
+ possible_resolutions (list):
+ A list of possible resolutions in the format [(height1, width1), (height2, width2), ...].
+
+ Returns:
+ tuple: The best fit resolution in the format (height, width).
+ """
+ original_height, original_width = original_size
+ best_fit = None
+ max_effective_resolution = 0
+ min_wasted_resolution = float("inf")
+
+ for height, width in possible_resolutions:
+ scale = min(width / original_width, height / original_height)
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
+ wasted_resolution = (width * height) - effective_resolution
+
+ if effective_resolution > max_effective_resolution or (
+ effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution
+ ):
+ max_effective_resolution = effective_resolution
+ min_wasted_resolution = wasted_resolution
+ best_fit = (height, width)
+
+ return best_fit
+
+
+def get_patch_output_size(image, target_resolution, input_data_format):
+ """
+ Given an image and a target resolution, calculate the output size of the image after cropping to the target
+ """
+ original_height, original_width = get_image_size(image, channel_dim=input_data_format)
+ target_height, target_width = target_resolution
+
+ scale_w = target_width / original_width
+ scale_h = target_height / original_height
+
+ if scale_w < scale_h:
+ new_width = target_width
+ new_height = min(math.ceil(original_height * scale_w), target_height)
+ else:
+ new_height = target_height
+ new_width = min(math.ceil(original_width * scale_h), target_width)
+
+ return new_height, new_width
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_processing_utils_fast.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_processing_utils_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..f990ce100d9db6501c9babbe7c96c513af0be8c1
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_processing_utils_fast.py
@@ -0,0 +1,705 @@
+# coding=utf-8
+# Copyright 2024 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from functools import lru_cache, partial
+from typing import Any, Dict, Iterable, List, Optional, Tuple, TypedDict, Union
+
+import numpy as np
+
+from .image_processing_utils import (
+ BaseImageProcessor,
+ BatchFeature,
+ get_size_dict,
+)
+from .image_transforms import (
+ convert_to_rgb,
+ get_resize_output_image_size,
+ get_size_with_aspect_ratio,
+ group_images_by_shape,
+ reorder_images,
+)
+from .image_utils import (
+ ChannelDimension,
+ ImageInput,
+ ImageType,
+ SizeDict,
+ get_image_size,
+ get_image_size_for_max_height_width,
+ get_image_type,
+ infer_channel_dimension_format,
+ make_flat_list_of_images,
+ validate_fast_preprocess_arguments,
+ validate_kwargs,
+)
+from .processing_utils import Unpack
+from .utils import (
+ TensorType,
+ add_start_docstrings,
+ is_torch_available,
+ is_torchvision_available,
+ is_torchvision_v2_available,
+ is_vision_available,
+ logging,
+)
+
+
+if is_vision_available():
+ from .image_utils import PILImageResampling
+
+if is_torch_available():
+ import torch
+
+if is_torchvision_available():
+ from .image_utils import pil_torch_interpolation_mapping
+
+ if is_torchvision_v2_available():
+ from torchvision.transforms.v2 import functional as F
+ else:
+ from torchvision.transforms import functional as F
+
+logger = logging.get_logger(__name__)
+
+
+def safe_squeeze(tensor: "torch.Tensor", axis: Optional[int] = None) -> "torch.Tensor":
+ """
+ Squeezes a tensor, but only if the axis specified has dim 1.
+ """
+ if axis is None:
+ return tensor.squeeze()
+
+ try:
+ return tensor.squeeze(axis=axis)
+ except ValueError:
+ return tensor
+
+
+def max_across_indices(values: Iterable[Any]) -> List[Any]:
+ """
+ Return the maximum value across all indices of an iterable of values.
+ """
+ return [max(values_i) for values_i in zip(*values)]
+
+
+def get_max_height_width(images: List["torch.Tensor"]) -> Tuple[int]:
+ """
+ Get the maximum height and width across all images in a batch.
+ """
+
+ _, max_height, max_width = max_across_indices([img.shape for img in images])
+
+ return (max_height, max_width)
+
+
+def divide_to_patches(
+ image: Union[np.array, "torch.Tensor"], patch_size: int
+) -> List[Union[np.array, "torch.Tensor"]]:
+ """
+ Divides an image into patches of a specified size.
+
+ Args:
+ image (`Union[np.array, "torch.Tensor"]`):
+ The input image.
+ patch_size (`int`):
+ The size of each patch.
+ Returns:
+ list: A list of Union[np.array, "torch.Tensor"] representing the patches.
+ """
+ patches = []
+ height, width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ for i in range(0, height, patch_size):
+ for j in range(0, width, patch_size):
+ patch = image[:, i : i + patch_size, j : j + patch_size]
+ patches.append(patch)
+
+ return patches
+
+
+class DefaultFastImageProcessorInitKwargs(TypedDict, total=False):
+ do_resize: Optional[bool]
+ size: Optional[Dict[str, int]]
+ default_to_square: Optional[bool]
+ resample: Optional[Union["PILImageResampling", "F.InterpolationMode"]]
+ do_center_crop: Optional[bool]
+ crop_size: Optional[Dict[str, int]]
+ do_rescale: Optional[bool]
+ rescale_factor: Optional[Union[int, float]]
+ do_normalize: Optional[bool]
+ image_mean: Optional[Union[float, List[float]]]
+ image_std: Optional[Union[float, List[float]]]
+ do_convert_rgb: Optional[bool]
+
+
+class DefaultFastImageProcessorPreprocessKwargs(DefaultFastImageProcessorInitKwargs):
+ return_tensors: Optional[Union[str, TensorType]]
+ data_format: Optional[ChannelDimension]
+ input_data_format: Optional[Union[str, ChannelDimension]]
+ device: Optional["torch.device"]
+
+
+BASE_IMAGE_PROCESSOR_FAST_DOCSTRING = r"""
+
+ Args:
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
+ `do_resize` parameter in the `preprocess` method.
+ size (`dict`, *optional*, defaults to `self.size`):
+ Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
+ method.
+ default_to_square (`bool`, *optional*, defaults to `self.default_to_square`):
+ Whether to default to a square image when resizing, if size is an int.
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
+ Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be
+ overridden by the `resample` parameter in the `preprocess` method.
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
+ `preprocess` method.
+ crop_size (`Dict[str, int]` *optional*, defaults to `self.crop_size`):
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
+ method.
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
+ `do_rescale` parameter in the `preprocess` method.
+ rescale_factor (`int` or `float`, *optional*, defaults to `self.rescale_factor`):
+ Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
+ overridden by the `rescale_factor` parameter in the `preprocess` method.
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
+ method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
+ overridden by the `image_mean` parameter in the `preprocess` method.
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
+ do_convert_rgb (`bool`, *optional*, defaults to `self.image_std`):
+ Whether to convert the image to RGB."""
+
+BASE_IMAGE_PROCESSOR_FAST_DOCSTRING_PREPROCESS = r"""
+ Preprocess an image or batch of images.
+
+ Args:
+ images (`ImageInput`):
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
+ Whether to resize the image.
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
+ Describes the maximum input dimensions to the model.
+ resample (`PILImageResampling` or `InterpolationMode`, *optional*, defaults to `self.resample`):
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
+ has an effect if `do_resize` is set to `True`.
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
+ Whether to center crop the image.
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
+ Size of the output image after applying `center_crop`.
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
+ Whether to rescale the image.
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
+ Whether to normalize the image.
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
+ `True`.
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
+ Whether to convert the image to RGB.
+ return_tensors (`str` or `TensorType`, *optional*):
+ Returns stacked tensors if set to `pt, otherwise returns a list of tensors.
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
+ The channel dimension format for the output image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - Unset: Use the channel dimension format of the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+ device (`torch.device`, *optional*):
+ The device to process the images on. If unset, the device is inferred from the input images."""
+
+
+@add_start_docstrings(
+ "Constructs a fast base image processor.",
+ BASE_IMAGE_PROCESSOR_FAST_DOCSTRING,
+)
+class BaseImageProcessorFast(BaseImageProcessor):
+ resample = None
+ image_mean = None
+ image_std = None
+ size = None
+ default_to_square = True
+ crop_size = None
+ do_resize = None
+ do_center_crop = None
+ do_rescale = None
+ rescale_factor = 1 / 255
+ do_normalize = None
+ do_convert_rgb = None
+ model_input_names = ["pixel_values"]
+ valid_init_kwargs = DefaultFastImageProcessorInitKwargs
+ valid_preprocess_kwargs = DefaultFastImageProcessorPreprocessKwargs
+
+ def __init__(
+ self,
+ **kwargs: Unpack[DefaultFastImageProcessorInitKwargs],
+ ) -> None:
+ super().__init__(**kwargs)
+ size = kwargs.pop("size", self.size)
+ self.size = (
+ get_size_dict(size=size, default_to_square=kwargs.pop("default_to_square", self.default_to_square))
+ if size is not None
+ else None
+ )
+ crop_size = kwargs.pop("crop_size", self.crop_size)
+ self.crop_size = get_size_dict(crop_size, param_name="crop_size") if crop_size is not None else None
+ for key in self.valid_init_kwargs.__annotations__.keys():
+ kwarg = kwargs.pop(key, None)
+ if kwarg is not None:
+ setattr(self, key, kwarg)
+ else:
+ setattr(self, key, getattr(self, key, None))
+
+ def resize(
+ self,
+ image: "torch.Tensor",
+ size: SizeDict,
+ interpolation: "F.InterpolationMode" = None,
+ antialias: bool = True,
+ **kwargs,
+ ) -> "torch.Tensor":
+ """
+ Resize an image to `(size["height"], size["width"])`.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to resize.
+ size (`SizeDict`):
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
+ resample (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
+ `InterpolationMode` filter to use when resizing the image e.g. `InterpolationMode.BICUBIC`.
+
+ Returns:
+ `torch.Tensor`: The resized image.
+ """
+ interpolation = interpolation if interpolation is not None else F.InterpolationMode.BILINEAR
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio(
+ image.size()[-2:],
+ size.shortest_edge,
+ size.longest_edge,
+ )
+ elif size.shortest_edge:
+ new_size = get_resize_output_image_size(
+ image,
+ size=size.shortest_edge,
+ default_to_square=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.size()[-2:], size.max_height, size.max_width)
+ elif size.height and size.width:
+ new_size = (size.height, size.width)
+ else:
+ raise ValueError(
+ "Size must contain 'height' and 'width' keys, or 'max_height' and 'max_width', or 'shortest_edge' key. Got"
+ f" {size}."
+ )
+ return F.resize(image, new_size, interpolation=interpolation, antialias=antialias)
+
+ def rescale(
+ self,
+ image: "torch.Tensor",
+ scale: float,
+ **kwargs,
+ ) -> "torch.Tensor":
+ """
+ Rescale an image by a scale factor. image = image * scale.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to rescale.
+ scale (`float`):
+ The scaling factor to rescale pixel values by.
+
+ Returns:
+ `torch.Tensor`: The rescaled image.
+ """
+ return image * scale
+
+ def normalize(
+ self,
+ image: "torch.Tensor",
+ mean: Union[float, Iterable[float]],
+ std: Union[float, Iterable[float]],
+ **kwargs,
+ ) -> "torch.Tensor":
+ """
+ Normalize an image. image = (image - image_mean) / image_std.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to normalize.
+ mean (`torch.Tensor`, `float` or `Iterable[float]`):
+ Image mean to use for normalization.
+ std (`torch.Tensor`, `float` or `Iterable[float]`):
+ Image standard deviation to use for normalization.
+
+ Returns:
+ `torch.Tensor`: The normalized image.
+ """
+ return F.normalize(image, mean, std)
+
+ def rescale_and_normalize(
+ self,
+ images: "torch.Tensor",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: Union[float, List[float]],
+ image_std: Union[float, List[float]],
+ ) -> "torch.Tensor":
+ """
+ Rescale and normalize images.
+ """
+ if do_rescale and do_normalize:
+ images = self.normalize(images.to(dtype=torch.float32), image_mean, image_std)
+ elif do_rescale:
+ images = images * rescale_factor
+ elif do_normalize:
+ images = self.normalize(images, image_mean, image_std)
+
+ return images
+
+ def center_crop(
+ self,
+ image: "torch.Tensor",
+ size: Dict[str, int],
+ **kwargs,
+ ) -> "torch.Tensor":
+ """
+ Center crop an image to `(size["height"], size["width"])`. If the input size is smaller than `crop_size` along
+ any edge, the image is padded with 0's and then center cropped.
+
+ Args:
+ image (`"torch.Tensor"`):
+ Image to center crop.
+ size (`Dict[str, int]`):
+ Size of the output image.
+
+ Returns:
+ `torch.Tensor`: The center cropped image.
+ """
+ if size.height is None or size.width is None:
+ raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}")
+ return F.center_crop(image, (size["height"], size["width"]))
+
+ def convert_to_rgb(
+ self,
+ image: ImageInput,
+ ) -> ImageInput:
+ """
+ Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image
+ as is.
+ Args:
+ image (ImageInput):
+ The image to convert.
+
+ Returns:
+ ImageInput: The converted image.
+ """
+ return convert_to_rgb(image)
+
+ def _prepare_images_structure(
+ self,
+ images: ImageInput,
+ ) -> ImageInput:
+ """
+ Prepare the images structure for processing.
+
+ Args:
+ images (`ImageInput`):
+ The input images to process.
+
+ Returns:
+ `ImageInput`: The images with a valid nesting.
+ """
+ return make_flat_list_of_images(images)
+
+ def _process_image(
+ self,
+ image: ImageInput,
+ do_convert_rgb: Optional[bool] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ device: Optional["torch.device"] = None,
+ ) -> "torch.Tensor":
+ image_type = get_image_type(image)
+ if image_type not in [ImageType.PIL, ImageType.TORCH, ImageType.NUMPY]:
+ raise ValueError(f"Unsupported input image type {image_type}")
+
+ if do_convert_rgb:
+ image = self.convert_to_rgb(image)
+
+ if image_type == ImageType.PIL:
+ image = F.pil_to_tensor(image)
+ elif image_type == ImageType.NUMPY:
+ # not using F.to_tensor as it doesn't handle (C, H, W) numpy arrays
+ image = torch.from_numpy(image).contiguous()
+
+ # Infer the channel dimension format if not provided
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+
+ if input_data_format == ChannelDimension.LAST:
+ # We force the channel dimension to be first for torch tensors as this is what torchvision expects.
+ image = image.permute(2, 0, 1).contiguous()
+
+ # Now that we have torch tensors, we can move them to the right device
+ if device is not None:
+ image = image.to(device)
+
+ return image
+
+ def _prepare_input_images(
+ self,
+ images: ImageInput,
+ do_convert_rgb: bool = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ device: Optional["torch.device"] = None,
+ ) -> List["torch.Tensor"]:
+ """
+ Prepare the input images for processing.
+ """
+ images = self._prepare_images_structure(images)
+ process_image_fn = partial(
+ self._process_image,
+ do_convert_rgb=do_convert_rgb,
+ input_data_format=input_data_format,
+ device=device,
+ )
+ # todo: yoni - check if we can parallelize this efficiently
+ processed_images = []
+ for image in images:
+ processed_images.append(process_image_fn(image))
+
+ return processed_images
+
+ @lru_cache(maxsize=10)
+ def _prepare_process_arguments(
+ self,
+ do_resize: bool = None,
+ size: Dict[str, int] = None,
+ resample: Optional[Union["PILImageResampling", "F.InterpolationMode"]] = None,
+ do_center_crop: bool = None,
+ crop_size: int = None,
+ do_rescale: bool = None,
+ rescale_factor: float = None,
+ do_normalize: bool = None,
+ image_mean: Optional[Union[float, List[float]]] = None,
+ image_std: Optional[Union[float, List[float]]] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
+ device: Optional["torch.device"] = None,
+ ) -> tuple:
+ """
+ Prepare the arguments for the process method.
+ """
+ validate_fast_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_resize=do_resize,
+ size=size,
+ do_center_crop=do_center_crop,
+ crop_size=crop_size,
+ resample=resample,
+ return_tensors=return_tensors,
+ data_format=data_format,
+ )
+
+ if do_rescale and do_normalize:
+ # Fused rescale and normalize
+ image_mean = torch.tensor(image_mean, device=device) * (1.0 / rescale_factor)
+ image_std = torch.tensor(image_std, device=device) * (1.0 / rescale_factor)
+
+ interpolation = (
+ pil_torch_interpolation_mapping[resample] if isinstance(resample, (PILImageResampling, int)) else resample
+ )
+
+ return image_mean, image_std, interpolation
+
+ @add_start_docstrings(BASE_IMAGE_PROCESSOR_FAST_DOCSTRING_PREPROCESS)
+ def preprocess(
+ self,
+ images: ImageInput,
+ **kwargs: Unpack[DefaultFastImageProcessorPreprocessKwargs],
+ ) -> BatchFeature:
+ validate_kwargs(
+ captured_kwargs=kwargs.keys(), valid_processor_keys=self.valid_preprocess_kwargs.__annotations__.keys()
+ )
+ # Set default kwargs from self. This ensures that if a kwarg is not provided
+ # by the user, it gets its default value from the instance, or is set to None.
+ for kwarg_name in self.valid_preprocess_kwargs.__annotations__:
+ kwargs.setdefault(kwarg_name, getattr(self, kwarg_name, None))
+
+ # Extract parameters that are only used for preparing the input images
+ do_convert_rgb = kwargs.pop("do_convert_rgb")
+ input_data_format = kwargs.pop("input_data_format")
+ device = kwargs.pop("device")
+
+ images = self._prepare_input_images(
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
+ )
+
+ # Pop kwargs that need further processing or won't be used in _preprocess
+ default_to_square = kwargs.pop("default_to_square")
+ size = kwargs.pop("size")
+ crop_size = kwargs.pop("crop_size")
+ image_mean = kwargs.pop("image_mean")
+ image_std = kwargs.pop("image_std")
+ data_format = kwargs.pop("data_format")
+ resample = kwargs.pop("resample")
+
+ # Make hashable for cache
+ size = SizeDict(**get_size_dict(size=size, default_to_square=default_to_square)) if size is not None else None
+ crop_size = SizeDict(**get_size_dict(crop_size, param_name="crop_size")) if crop_size is not None else None
+ image_mean = tuple(image_mean) if isinstance(image_mean, list) else image_mean
+ image_std = tuple(image_std) if isinstance(image_std, list) else image_std
+
+ image_mean, image_std, interpolation = self._prepare_process_arguments(
+ size=size,
+ crop_size=crop_size,
+ resample=resample,
+ image_mean=image_mean,
+ image_std=image_std,
+ data_format=data_format if data_format is not None else ChannelDimension.FIRST,
+ device=images[0].device,
+ do_resize=kwargs.get("do_resize"),
+ do_center_crop=kwargs.get("do_center_crop"),
+ do_rescale=kwargs.get("do_rescale"),
+ rescale_factor=kwargs.get("rescale_factor"),
+ do_normalize=kwargs.get("do_normalize"),
+ return_tensors=kwargs.get("return_tensors"),
+ )
+
+ return self._preprocess(
+ images=images,
+ size=size,
+ crop_size=crop_size,
+ interpolation=interpolation,
+ image_mean=image_mean,
+ image_std=image_std,
+ **kwargs,
+ )
+
+ def _preprocess(
+ self,
+ images: List["torch.Tensor"],
+ do_resize: bool,
+ size: SizeDict,
+ interpolation: Optional["F.InterpolationMode"],
+ do_center_crop: bool,
+ crop_size: SizeDict,
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: Optional[Union[float, List[float]]],
+ image_std: Optional[Union[float, List[float]]],
+ return_tensors: Optional[Union[str, TensorType]],
+ ) -> BatchFeature:
+ # Group images by size for batched resizing
+ grouped_images, grouped_images_index = group_images_by_shape(images)
+ resized_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ if do_resize:
+ stacked_images = self.resize(image=stacked_images, size=size, interpolation=interpolation)
+ resized_images_grouped[shape] = stacked_images
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
+
+ # Group images by size for further processing
+ # Needed in case do_resize is False, or resize returns images with different sizes
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images)
+ processed_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ if do_center_crop:
+ stacked_images = self.center_crop(stacked_images, crop_size)
+ # Fused rescale and normalize
+ stacked_images = self.rescale_and_normalize(
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ processed_images_grouped[shape] = stacked_images
+
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
+ processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images
+
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
+
+ def to_dict(self):
+ encoder_dict = super().to_dict()
+ encoder_dict.pop("_valid_processor_keys", None)
+ return encoder_dict
+
+
+class SemanticSegmentationMixin:
+ def post_process_semantic_segmentation(self, outputs, target_sizes: List[Tuple] = None):
+ """
+ Converts the output of [`MobileNetV2ForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch.
+
+ Args:
+ outputs ([`MobileNetV2ForSemanticSegmentation`]):
+ Raw outputs of the model.
+ target_sizes (`List[Tuple]` of length `batch_size`, *optional*):
+ List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
+ predictions will not be resized.
+
+ Returns:
+ semantic_segmentation: `List[torch.Tensor]` of length `batch_size`, where each item is a semantic
+ segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
+ specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
+ """
+ logits = outputs.logits
+
+ # Resize logits and compute semantic segmentation maps
+ if target_sizes is not None:
+ if len(logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ # if is_torch_tensor(target_sizes):
+ # target_sizes = target_sizes.numpy()
+
+ semantic_segmentation = []
+
+ for idx in range(len(logits)):
+ resized_logits = torch.nn.functional.interpolate(
+ logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = logits.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+
+ return semantic_segmentation
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_transforms.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaadcb44586a15002a42159ecf8839c2a18fd0e3
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_transforms.py
@@ -0,0 +1,898 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import warnings
+from collections.abc import Collection
+from math import ceil
+from typing import Dict, Iterable, List, Optional, Tuple, Union
+
+import numpy as np
+
+from .image_utils import (
+ ChannelDimension,
+ ImageInput,
+ get_channel_dimension_axis,
+ get_image_size,
+ infer_channel_dimension_format,
+)
+from .utils import ExplicitEnum, TensorType, is_jax_tensor, is_tf_tensor, is_torch_tensor
+from .utils.import_utils import (
+ is_flax_available,
+ is_tf_available,
+ is_torch_available,
+ is_vision_available,
+ requires_backends,
+)
+
+
+if is_vision_available():
+ import PIL
+
+ from .image_utils import PILImageResampling
+
+if is_torch_available():
+ import torch
+
+if is_tf_available():
+ import tensorflow as tf
+
+if is_flax_available():
+ import jax.numpy as jnp
+
+
+def to_channel_dimension_format(
+ image: np.ndarray,
+ channel_dim: Union[ChannelDimension, str],
+ input_channel_dim: Optional[Union[ChannelDimension, str]] = None,
+) -> 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 (`ChannelDimension`):
+ The channel dimension format to use.
+ input_channel_dim (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
+
+ Returns:
+ `np.ndarray`: The image with the channel dimension set to `channel_dim`.
+ """
+ if not isinstance(image, np.ndarray):
+ raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}")
+
+ if input_channel_dim is None:
+ input_channel_dim = infer_channel_dimension_format(image)
+
+ target_channel_dim = ChannelDimension(channel_dim)
+ if input_channel_dim == target_channel_dim:
+ return image
+
+ if target_channel_dim == ChannelDimension.FIRST:
+ image = image.transpose((2, 0, 1))
+ elif target_channel_dim == ChannelDimension.LAST:
+ image = image.transpose((1, 2, 0))
+ else:
+ raise ValueError("Unsupported channel dimension format: {}".format(channel_dim))
+
+ return image
+
+
+def rescale(
+ image: np.ndarray,
+ scale: float,
+ data_format: Optional[ChannelDimension] = None,
+ dtype: np.dtype = np.float32,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> np.ndarray:
+ """
+ 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 will be the same as the input image.
+ dtype (`np.dtype`, *optional*, defaults to `np.float32`):
+ The dtype of the output image. Defaults to `np.float32`. Used for backwards compatibility with feature
+ extractors.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
+
+ Returns:
+ `np.ndarray`: The rescaled image.
+ """
+ if not isinstance(image, np.ndarray):
+ raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}")
+
+ rescaled_image = image.astype(np.float64) * scale # Numpy type promotion has changed, so always upcast first
+ if data_format is not None:
+ rescaled_image = to_channel_dimension_format(rescaled_image, data_format, input_data_format)
+
+ rescaled_image = rescaled_image.astype(dtype) # Finally downcast to the desired dtype at the end
+
+ return rescaled_image
+
+
+def _rescale_for_pil_conversion(image):
+ """
+ Detects whether or not the image needs to be rescaled before being converted to a PIL image.
+
+ The assumption is that if the image is of type `np.float` and all values are between 0 and 1, it needs to be
+ rescaled.
+ """
+ if image.dtype == np.uint8:
+ do_rescale = False
+ elif np.allclose(image, image.astype(int)):
+ if np.all(0 <= image) and np.all(image <= 255):
+ do_rescale = False
+ else:
+ raise ValueError(
+ "The image to be converted to a PIL image contains values outside the range [0, 255], "
+ f"got [{image.min()}, {image.max()}] which cannot be converted to uint8."
+ )
+ elif np.all(0 <= image) and np.all(image <= 1):
+ do_rescale = True
+ else:
+ raise ValueError(
+ "The image to be converted to a PIL image contains values outside the range [0, 1], "
+ f"got [{image.min()}, {image.max()}] which cannot be converted to uint8."
+ )
+ return do_rescale
+
+
+def to_pil_image(
+ image: Union[np.ndarray, "PIL.Image.Image", "torch.Tensor", "tf.Tensor", "jnp.ndarray"],
+ do_rescale: Optional[bool] = None,
+ image_mode: Optional[str] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = 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:
+ 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`, *optional*):
+ Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will default
+ to `True` if the image type is a floating type and casting to `int` would result in a loss of precision,
+ and `False` otherwise.
+ image_mode (`str`, *optional*):
+ The mode to use for the PIL image. If unset, will use the default mode for the input image type.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
+
+ Returns:
+ `PIL.Image.Image`: The converted image.
+ """
+ requires_backends(to_pil_image, ["vision"])
+
+ if isinstance(image, PIL.Image.Image):
+ return image
+
+ # Convert all tensors to numpy arrays before converting to PIL image
+ if is_torch_tensor(image) or is_tf_tensor(image):
+ image = image.numpy()
+ elif is_jax_tensor(image):
+ image = np.array(image)
+ elif not isinstance(image, np.ndarray):
+ raise ValueError("Input image type not supported: {}".format(type(image)))
+
+ # If the channel has been moved to first dim, we put it back at the end.
+ image = to_channel_dimension_format(image, ChannelDimension.LAST, input_data_format)
+
+ # If there is a single channel, we squeeze it, as otherwise PIL can't handle it.
+ image = np.squeeze(image, axis=-1) if image.shape[-1] == 1 else image
+
+ # PIL.Image can only store uint8 values so we rescale the image to be between 0 and 255 if needed.
+ do_rescale = _rescale_for_pil_conversion(image) if do_rescale is None else do_rescale
+
+ if do_rescale:
+ image = rescale(image, 255)
+
+ image = image.astype(np.uint8)
+ return PIL.Image.fromarray(image, mode=image_mode)
+
+
+def get_size_with_aspect_ratio(image_size, size, max_size=None) -> Tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size.
+
+ Args:
+ image_size (`Tuple[int, int]`):
+ The input image size.
+ size (`int`):
+ The desired output size.
+ max_size (`int`, *optional*):
+ The maximum allowed output size.
+ """
+ height, width = image_size
+ raw_size = None
+ if max_size is not None:
+ min_original_size = float(min((height, width)))
+ max_original_size = float(max((height, width)))
+ if max_original_size / min_original_size * size > max_size:
+ raw_size = max_size * min_original_size / max_original_size
+ size = int(round(raw_size))
+
+ if (height <= width and height == size) or (width <= height and width == size):
+ oh, ow = height, width
+ elif width < height:
+ ow = size
+ if max_size is not None and raw_size is not None:
+ oh = int(raw_size * height / width)
+ else:
+ oh = int(size * height / width)
+ else:
+ oh = size
+ if max_size is not None and raw_size is not None:
+ ow = int(raw_size * width / height)
+ else:
+ ow = int(size * width / height)
+
+ return (oh, ow)
+
+
+# Logic adapted from torchvision resizing logic: https://github.com/pytorch/vision/blob/511924c1ced4ce0461197e5caa64ce5b9e558aab/torchvision/transforms/functional.py#L366
+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,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> tuple:
+ """
+ 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 the image. If `size` is a sequence like (h, w), output size will be matched to
+ this.
+
+ If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If
+ `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this
+ number. i.e, if height > width, then image will be rescaled to (size * height / width, size).
+ default_to_square (`bool`, *optional*, defaults to `True`):
+ How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square
+ (`size`,`size`). If set to `False`, will replicate
+ [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)
+ with support for resizing only the smallest edge and providing an optional `max_size`.
+ max_size (`int`, *optional*):
+ The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater
+ than `max_size` after being resized according to `size`, then the image is resized again so that the longer
+ edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter
+ than `size`. Only used if `default_to_square` is `False`.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
+
+ Returns:
+ `tuple`: The target (height, width) dimension of the output image after resizing.
+ """
+ if isinstance(size, (tuple, list)):
+ if len(size) == 2:
+ return tuple(size)
+ elif len(size) == 1:
+ # Perform same logic as if size was an int
+ size = size[0]
+ else:
+ raise ValueError("size must have 1 or 2 elements if it is a list or tuple")
+
+ if default_to_square:
+ return (size, size)
+
+ height, width = get_image_size(input_image, input_data_format)
+ short, long = (width, height) if width <= height else (height, width)
+ requested_new_short = size
+
+ new_short, new_long = requested_new_short, int(requested_new_short * long / short)
+
+ if max_size is not None:
+ if max_size <= requested_new_short:
+ raise ValueError(
+ f"max_size = {max_size} must be strictly greater than the requested "
+ f"size for the smaller edge size = {size}"
+ )
+ if new_long > max_size:
+ new_short, new_long = int(max_size * new_short / new_long), max_size
+
+ return (new_long, new_short) if width <= height else (new_short, new_long)
+
+
+def resize(
+ image: np.ndarray,
+ size: Tuple[int, int],
+ resample: "PILImageResampling" = None,
+ reducing_gap: Optional[int] = None,
+ data_format: Optional[ChannelDimension] = None,
+ return_numpy: bool = True,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> np.ndarray:
+ """
+ Resizes `image` to `(height, width)` specified by `size` using the PIL library.
+
+ Args:
+ image (`np.ndarray`):
+ The image to resize.
+ size (`Tuple[int, int]`):
+ The size to use for resizing the image.
+ resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ The filter to user for resampling.
+ reducing_gap (`int`, *optional*):
+ Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to
+ the fair resampling. See corresponding Pillow documentation for more details.
+ data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the output image. If unset, will use the inferred format from the input.
+ return_numpy (`bool`, *optional*, defaults to `True`):
+ Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is
+ returned.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
+
+ Returns:
+ `np.ndarray`: The resized image.
+ """
+ requires_backends(resize, ["vision"])
+
+ resample = resample if resample is not None else PILImageResampling.BILINEAR
+
+ if not len(size) == 2:
+ raise ValueError("size must have 2 elements")
+
+ # For all transformations, we want to keep the same data format as the input image unless otherwise specified.
+ # The resized image from PIL will always have channels last, so find the input format first.
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+ data_format = input_data_format if data_format is None else data_format
+
+ # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use
+ # the pillow library to resize the image and then convert back to numpy
+ do_rescale = False
+ if not isinstance(image, PIL.Image.Image):
+ do_rescale = _rescale_for_pil_conversion(image)
+ image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)
+ height, width = size
+ # PIL images are in the format (width, height)
+ resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)
+
+ if return_numpy:
+ resized_image = np.array(resized_image)
+ # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image
+ # so we need to add it back if necessary.
+ resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image
+ # The image is always in channels last format after converting from a PIL image
+ resized_image = to_channel_dimension_format(
+ resized_image, data_format, input_channel_dim=ChannelDimension.LAST
+ )
+ # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to
+ # rescale it back to the original range.
+ resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image
+ return resized_image
+
+
+def normalize(
+ image: np.ndarray,
+ mean: Union[float, Collection[float]],
+ std: Union[float, Collection[float]],
+ data_format: Optional[ChannelDimension] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> np.ndarray:
+ """
+ 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 `Collection[float]`):
+ The mean to use for normalization.
+ std (`float` or `Collection[float]`):
+ The standard deviation to use for normalization.
+ data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the output image. If unset, will use the inferred format from the input.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
+ """
+ if not isinstance(image, np.ndarray):
+ raise ValueError("image must be a numpy array")
+
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+
+ channel_axis = get_channel_dimension_axis(image, input_data_format=input_data_format)
+ num_channels = image.shape[channel_axis]
+
+ # We cast to float32 to avoid errors that can occur when subtracting uint8 values.
+ # We preserve the original dtype if it is a float type to prevent upcasting float16.
+ if not np.issubdtype(image.dtype, np.floating):
+ image = image.astype(np.float32)
+
+ if isinstance(mean, Collection):
+ if len(mean) != num_channels:
+ raise ValueError(f"mean must have {num_channels} elements if it is an iterable, got {len(mean)}")
+ else:
+ mean = [mean] * num_channels
+ mean = np.array(mean, dtype=image.dtype)
+
+ if isinstance(std, Collection):
+ if len(std) != num_channels:
+ raise ValueError(f"std must have {num_channels} elements if it is an iterable, got {len(std)}")
+ else:
+ std = [std] * num_channels
+ std = np.array(std, dtype=image.dtype)
+
+ if input_data_format == ChannelDimension.LAST:
+ image = (image - mean) / std
+ else:
+ image = ((image.T - mean) / std).T
+
+ image = to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image
+ return image
+
+
+def center_crop(
+ image: np.ndarray,
+ size: Tuple[int, int],
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_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
+ 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]`):
+ The target size for the cropped image.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use the inferred format of the input image.
+ input_data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use the inferred format of the input image.
+ return_numpy (`bool`, *optional*):
+ Whether or not to return the cropped image as a numpy array. Used for backwards compatibility with the
+ previous ImageFeatureExtractionMixin method.
+ - Unset: will return the same type as the input image.
+ - `True`: will return a numpy array.
+ - `False`: will return a `PIL.Image.Image` object.
+ Returns:
+ `np.ndarray`: The cropped image.
+ """
+ requires_backends(center_crop, ["vision"])
+
+ if return_numpy is not None:
+ warnings.warn("return_numpy is deprecated and will be removed in v.4.33", FutureWarning)
+
+ return_numpy = True if return_numpy is None else return_numpy
+
+ if not isinstance(image, np.ndarray):
+ raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}")
+
+ if not isinstance(size, Iterable) or len(size) != 2:
+ raise ValueError("size must have 2 elements representing the height and width of the output image")
+
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+ output_data_format = data_format if data_format is not None else input_data_format
+
+ # We perform the crop in (C, H, W) format and then convert to the output format
+ image = to_channel_dimension_format(image, ChannelDimension.FIRST, input_data_format)
+
+ orig_height, orig_width = get_image_size(image, ChannelDimension.FIRST)
+ crop_height, crop_width = size
+ crop_height, crop_width = int(crop_height), int(crop_width)
+
+ # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result.
+ top = (orig_height - crop_height) // 2
+ bottom = top + crop_height
+ # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result.
+ left = (orig_width - crop_width) // 2
+ right = left + crop_width
+
+ # Check if cropped area is within image boundaries
+ if top >= 0 and bottom <= orig_height and left >= 0 and right <= orig_width:
+ image = image[..., top:bottom, left:right]
+ image = to_channel_dimension_format(image, output_data_format, ChannelDimension.FIRST)
+ return image
+
+ # Otherwise, we may need to pad if the image is too small. Oh joy...
+ new_height = max(crop_height, orig_height)
+ new_width = max(crop_width, orig_width)
+ new_shape = image.shape[:-2] + (new_height, new_width)
+ new_image = np.zeros_like(image, shape=new_shape)
+
+ # If the image is too small, pad it with zeros
+ top_pad = ceil((new_height - orig_height) / 2)
+ bottom_pad = top_pad + orig_height
+ left_pad = ceil((new_width - orig_width) / 2)
+ right_pad = left_pad + orig_width
+ new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image
+
+ top += top_pad
+ bottom += top_pad
+ left += left_pad
+ right += left_pad
+
+ new_image = new_image[..., max(0, top) : min(new_height, bottom), max(0, left) : min(new_width, right)]
+ new_image = to_channel_dimension_format(new_image, output_data_format, ChannelDimension.FIRST)
+
+ if not return_numpy:
+ new_image = to_pil_image(new_image)
+
+ return new_image
+
+
+def _center_to_corners_format_torch(bboxes_center: "torch.Tensor") -> "torch.Tensor":
+ center_x, center_y, width, height = bboxes_center.unbind(-1)
+ bbox_corners = torch.stack(
+ # top left x, top left y, bottom right x, bottom right y
+ [(center_x - 0.5 * width), (center_y - 0.5 * height), (center_x + 0.5 * width), (center_y + 0.5 * height)],
+ dim=-1,
+ )
+ return bbox_corners
+
+
+def _center_to_corners_format_numpy(bboxes_center: np.ndarray) -> np.ndarray:
+ center_x, center_y, width, height = bboxes_center.T
+ bboxes_corners = np.stack(
+ # top left x, top left y, bottom right x, bottom right y
+ [center_x - 0.5 * width, center_y - 0.5 * height, center_x + 0.5 * width, center_y + 0.5 * height],
+ axis=-1,
+ )
+ return bboxes_corners
+
+
+def _center_to_corners_format_tf(bboxes_center: "tf.Tensor") -> "tf.Tensor":
+ center_x, center_y, width, height = tf.unstack(bboxes_center, axis=-1)
+ bboxes_corners = tf.stack(
+ # top left x, top left y, bottom right x, bottom right y
+ [center_x - 0.5 * width, center_y - 0.5 * height, center_x + 0.5 * width, center_y + 0.5 * height],
+ axis=-1,
+ )
+ return bboxes_corners
+
+
+# 2 functions below inspired by https://github.com/facebookresearch/detr/blob/master/util/box_ops.py
+def center_to_corners_format(bboxes_center: TensorType) -> TensorType:
+ """
+ Converts bounding boxes from center format to corners format.
+
+ center format: contains the coordinate for the center of the box and its width, height dimensions
+ (center_x, center_y, width, height)
+ corners format: contains the coodinates for the top-left and bottom-right corners of the box
+ (top_left_x, top_left_y, bottom_right_x, bottom_right_y)
+ """
+ # Function is used during model forward pass, so we use the input framework if possible, without
+ # converting to numpy
+ if is_torch_tensor(bboxes_center):
+ return _center_to_corners_format_torch(bboxes_center)
+ elif isinstance(bboxes_center, np.ndarray):
+ return _center_to_corners_format_numpy(bboxes_center)
+ elif is_tf_tensor(bboxes_center):
+ return _center_to_corners_format_tf(bboxes_center)
+
+ raise ValueError(f"Unsupported input type {type(bboxes_center)}")
+
+
+def _corners_to_center_format_torch(bboxes_corners: "torch.Tensor") -> "torch.Tensor":
+ top_left_x, top_left_y, bottom_right_x, bottom_right_y = bboxes_corners.unbind(-1)
+ b = [
+ (top_left_x + bottom_right_x) / 2, # center x
+ (top_left_y + bottom_right_y) / 2, # center y
+ (bottom_right_x - top_left_x), # width
+ (bottom_right_y - top_left_y), # height
+ ]
+ return torch.stack(b, dim=-1)
+
+
+def _corners_to_center_format_numpy(bboxes_corners: np.ndarray) -> np.ndarray:
+ top_left_x, top_left_y, bottom_right_x, bottom_right_y = bboxes_corners.T
+ bboxes_center = np.stack(
+ [
+ (top_left_x + bottom_right_x) / 2, # center x
+ (top_left_y + bottom_right_y) / 2, # center y
+ (bottom_right_x - top_left_x), # width
+ (bottom_right_y - top_left_y), # height
+ ],
+ axis=-1,
+ )
+ return bboxes_center
+
+
+def _corners_to_center_format_tf(bboxes_corners: "tf.Tensor") -> "tf.Tensor":
+ top_left_x, top_left_y, bottom_right_x, bottom_right_y = tf.unstack(bboxes_corners, axis=-1)
+ bboxes_center = tf.stack(
+ [
+ (top_left_x + bottom_right_x) / 2, # center x
+ (top_left_y + bottom_right_y) / 2, # center y
+ (bottom_right_x - top_left_x), # width
+ (bottom_right_y - top_left_y), # height
+ ],
+ axis=-1,
+ )
+ return bboxes_center
+
+
+def corners_to_center_format(bboxes_corners: TensorType) -> TensorType:
+ """
+ Converts bounding boxes from corners format to center format.
+
+ corners format: contains the coordinates for the top-left and bottom-right corners of the box
+ (top_left_x, top_left_y, bottom_right_x, bottom_right_y)
+ center format: contains the coordinate for the center of the box and its the width, height dimensions
+ (center_x, center_y, width, height)
+ """
+ # Inverse function accepts different input types so implemented here too
+ if is_torch_tensor(bboxes_corners):
+ return _corners_to_center_format_torch(bboxes_corners)
+ elif isinstance(bboxes_corners, np.ndarray):
+ return _corners_to_center_format_numpy(bboxes_corners)
+ elif is_tf_tensor(bboxes_corners):
+ return _corners_to_center_format_tf(bboxes_corners)
+
+ raise ValueError(f"Unsupported input type {type(bboxes_corners)}")
+
+
+# 2 functions below copied from https://github.com/cocodataset/panopticapi/blob/master/panopticapi/utils.py
+# Copyright (c) 2018, Alexander Kirillov
+# All rights reserved.
+def rgb_to_id(color):
+ """
+ Converts RGB color to unique ID.
+ """
+ if isinstance(color, np.ndarray) and len(color.shape) == 3:
+ if color.dtype == np.uint8:
+ color = color.astype(np.int32)
+ return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
+ return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
+
+
+def id_to_rgb(id_map):
+ """
+ Converts unique ID to RGB color.
+ """
+ if isinstance(id_map, np.ndarray):
+ id_map_copy = id_map.copy()
+ rgb_shape = tuple(list(id_map.shape) + [3])
+ rgb_map = np.zeros(rgb_shape, dtype=np.uint8)
+ for i in range(3):
+ rgb_map[..., i] = id_map_copy % 256
+ id_map_copy //= 256
+ return rgb_map
+ color = []
+ for _ in range(3):
+ color.append(id_map % 256)
+ id_map //= 256
+ return color
+
+
+class PaddingMode(ExplicitEnum):
+ """
+ Enum class for the different padding modes to use when padding images.
+ """
+
+ CONSTANT = "constant"
+ REFLECT = "reflect"
+ REPLICATE = "replicate"
+ SYMMETRIC = "symmetric"
+
+
+def pad(
+ image: np.ndarray,
+ padding: Union[int, Tuple[int, int], Iterable[Tuple[int, int]]],
+ mode: PaddingMode = PaddingMode.CONSTANT,
+ constant_values: Union[float, Iterable[float]] = 0.0,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> np.ndarray:
+ """
+ Pads the `image` with the specified (height, width) `padding` and `mode`.
+
+ Args:
+ image (`np.ndarray`):
+ The image to pad.
+ padding (`int` or `Tuple[int, int]` or `Iterable[Tuple[int, int]]`):
+ Padding to apply to the edges of the height, width axes. Can be one of three formats:
+ - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis.
+ - `((before, after),)` yields same before and after pad for height and width.
+ - `(pad,)` or int is a shortcut for before = after = pad width for all axes.
+ mode (`PaddingMode`):
+ The padding mode to use. Can be one of:
+ - `"constant"`: pads with a constant value.
+ - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the
+ vector along each axis.
+ - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis.
+ - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array.
+ constant_values (`float` or `Iterable[float]`, *optional*):
+ The value to use for the padding if `mode` is `"constant"`.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use same as the input image.
+ input_data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use the inferred format of the input image.
+
+ Returns:
+ `np.ndarray`: The padded image.
+
+ """
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+
+ def _expand_for_data_format(values):
+ """
+ Convert values to be in the format expected by np.pad based on the data format.
+ """
+ if isinstance(values, (int, float)):
+ values = ((values, values), (values, values))
+ elif isinstance(values, tuple) and len(values) == 1:
+ values = ((values[0], values[0]), (values[0], values[0]))
+ elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], int):
+ values = (values, values)
+ elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], tuple):
+ values = values
+ else:
+ raise ValueError(f"Unsupported format: {values}")
+
+ # add 0 for channel dimension
+ values = ((0, 0), *values) if input_data_format == ChannelDimension.FIRST else (*values, (0, 0))
+
+ # Add additional padding if there's a batch dimension
+ values = (0, *values) if image.ndim == 4 else values
+ return values
+
+ padding = _expand_for_data_format(padding)
+
+ if mode == PaddingMode.CONSTANT:
+ constant_values = _expand_for_data_format(constant_values)
+ image = np.pad(image, padding, mode="constant", constant_values=constant_values)
+ elif mode == PaddingMode.REFLECT:
+ image = np.pad(image, padding, mode="reflect")
+ elif mode == PaddingMode.REPLICATE:
+ image = np.pad(image, padding, mode="edge")
+ elif mode == PaddingMode.SYMMETRIC:
+ image = np.pad(image, padding, mode="symmetric")
+ else:
+ raise ValueError(f"Invalid padding mode: {mode}")
+
+ image = to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image
+ return image
+
+
+# TODO (Amy): Accept 1/3/4 channel numpy array as input and return np.array as default
+def convert_to_rgb(image: ImageInput) -> ImageInput:
+ """
+ Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image
+ as is.
+ Args:
+ image (Image):
+ The image to convert.
+ """
+ requires_backends(convert_to_rgb, ["vision"])
+
+ if not isinstance(image, PIL.Image.Image):
+ return image
+
+ if image.mode == "RGB":
+ return image
+
+ image = image.convert("RGB")
+ return image
+
+
+def flip_channel_order(
+ image: np.ndarray,
+ data_format: Optional[ChannelDimension] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> np.ndarray:
+ """
+ Flips the channel order of the image.
+
+ If the image is in RGB format, it will be converted to BGR and vice versa.
+
+ Args:
+ image (`np.ndarray`):
+ The image to flip.
+ data_format (`ChannelDimension`, *optional*):
+ The channel dimension format for the output image. Can be one of:
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use same as the input image.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format for the input image. Can be one of:
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use the inferred format of the input image.
+ """
+ input_data_format = infer_channel_dimension_format(image) if input_data_format is None else input_data_format
+
+ if input_data_format == ChannelDimension.LAST:
+ image = image[..., ::-1]
+ elif input_data_format == ChannelDimension.FIRST:
+ image = image[::-1, ...]
+ else:
+ raise ValueError(f"Unsupported channel dimension: {input_data_format}")
+
+ if data_format is not None:
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
+ return image
+
+
+def _cast_tensor_to_float(x):
+ if x.is_floating_point():
+ return x
+ return x.float()
+
+
+def group_images_by_shape(
+ images: List["torch.Tensor"],
+) -> Tuple[Dict[Tuple[int, int], List["torch.Tensor"]], Dict[int, Tuple[Tuple[int, int], int]]]:
+ """
+ Groups images by shape.
+ Returns a dictionary with the shape as key and a list of images with that shape as value,
+ and a dictionary with the index of the image in the original list as key and the shape and index in the grouped list as value.
+ """
+ grouped_images = {}
+ grouped_images_index = {}
+ for i, image in enumerate(images):
+ shape = image.shape[1:]
+ if shape not in grouped_images:
+ grouped_images[shape] = []
+ grouped_images[shape].append(image)
+ grouped_images_index[i] = (shape, len(grouped_images[shape]) - 1)
+ # stack images with the same shape
+ grouped_images = {shape: torch.stack(images, dim=0) for shape, images in grouped_images.items()}
+ return grouped_images, grouped_images_index
+
+
+def reorder_images(
+ processed_images: Dict[Tuple[int, int], "torch.Tensor"], grouped_images_index: Dict[int, Tuple[int, int]]
+) -> List["torch.Tensor"]:
+ """
+ Reconstructs a list of images in the original order.
+ """
+ return [
+ processed_images[grouped_images_index[i][0]][grouped_images_index[i][1]]
+ for i in range(len(grouped_images_index))
+ ]
+
+
+class NumpyToTensor:
+ """
+ Convert a numpy array to a PyTorch tensor.
+ """
+
+ def __call__(self, image: np.ndarray):
+ # Same as in PyTorch, we assume incoming numpy images are in HWC format
+ # c.f. https://github.com/pytorch/vision/blob/61d97f41bc209e1407dcfbd685d2ee2da9c1cdad/torchvision/transforms/functional.py#L154
+ return torch.from_numpy(image.transpose(2, 0, 1)).contiguous()
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_utils.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d47f40c1ef3473bde9d207a0ce5da8782ec553f
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/image_utils.py
@@ -0,0 +1,1388 @@
+# coding=utf-8
+# Copyright 2021 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import base64
+import os
+from contextlib import redirect_stdout
+from dataclasses import dataclass
+from io import BytesIO
+from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Tuple, Union
+
+import numpy as np
+import requests
+from packaging import version
+
+from .utils import (
+ ExplicitEnum,
+ TensorType,
+ is_av_available,
+ is_cv2_available,
+ is_decord_available,
+ is_jax_tensor,
+ is_numpy_array,
+ is_tf_tensor,
+ is_torch_available,
+ is_torch_tensor,
+ is_torchvision_available,
+ is_vision_available,
+ is_yt_dlp_available,
+ logging,
+ requires_backends,
+ to_numpy,
+)
+from .utils.constants import ( # noqa: F401
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ IMAGENET_STANDARD_MEAN,
+ IMAGENET_STANDARD_STD,
+ OPENAI_CLIP_MEAN,
+ OPENAI_CLIP_STD,
+)
+
+
+if is_vision_available():
+ import PIL.Image
+ import PIL.ImageOps
+
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
+ PILImageResampling = PIL.Image.Resampling
+ else:
+ PILImageResampling = PIL.Image
+
+ if is_torchvision_available():
+ from torchvision import io as torchvision_io
+ from torchvision.transforms import InterpolationMode
+
+ pil_torch_interpolation_mapping = {
+ PILImageResampling.NEAREST: InterpolationMode.NEAREST,
+ PILImageResampling.BOX: InterpolationMode.BOX,
+ PILImageResampling.BILINEAR: InterpolationMode.BILINEAR,
+ PILImageResampling.HAMMING: InterpolationMode.HAMMING,
+ PILImageResampling.BICUBIC: InterpolationMode.BICUBIC,
+ PILImageResampling.LANCZOS: InterpolationMode.LANCZOS,
+ }
+
+
+if TYPE_CHECKING:
+ if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+
+
+ImageInput = Union[
+ "PIL.Image.Image", np.ndarray, "torch.Tensor", List["PIL.Image.Image"], List[np.ndarray], List["torch.Tensor"]
+] # noqa
+
+
+VideoInput = Union[
+ List["PIL.Image.Image"],
+ "np.ndarray",
+ "torch.Tensor",
+ List["np.ndarray"],
+ List["torch.Tensor"],
+ List[List["PIL.Image.Image"]],
+ List[List["np.ndarrray"]],
+ List[List["torch.Tensor"]],
+] # noqa
+
+
+class ChannelDimension(ExplicitEnum):
+ FIRST = "channels_first"
+ LAST = "channels_last"
+
+
+class AnnotationFormat(ExplicitEnum):
+ COCO_DETECTION = "coco_detection"
+ COCO_PANOPTIC = "coco_panoptic"
+
+
+class AnnotionFormat(ExplicitEnum):
+ COCO_DETECTION = AnnotationFormat.COCO_DETECTION.value
+ COCO_PANOPTIC = AnnotationFormat.COCO_PANOPTIC.value
+
+
+@dataclass
+class VideoMetadata:
+ total_num_frames: int
+ fps: float
+ duration: float
+ video_backend: str
+
+
+AnnotationType = Dict[str, Union[int, str, List[Dict]]]
+
+
+def is_pil_image(img):
+ return is_vision_available() and isinstance(img, PIL.Image.Image)
+
+
+class ImageType(ExplicitEnum):
+ PIL = "pillow"
+ TORCH = "torch"
+ NUMPY = "numpy"
+ TENSORFLOW = "tensorflow"
+ JAX = "jax"
+
+
+def get_image_type(image):
+ if is_pil_image(image):
+ return ImageType.PIL
+ if is_torch_tensor(image):
+ return ImageType.TORCH
+ if is_numpy_array(image):
+ return ImageType.NUMPY
+ if is_tf_tensor(image):
+ return ImageType.TENSORFLOW
+ if is_jax_tensor(image):
+ return ImageType.JAX
+ raise ValueError(f"Unrecognised image type {type(image)}")
+
+
+def is_valid_image(img):
+ return is_pil_image(img) or is_numpy_array(img) or is_torch_tensor(img) or is_tf_tensor(img) or is_jax_tensor(img)
+
+
+def is_valid_list_of_images(images: List):
+ return images and all(is_valid_image(image) for image in images)
+
+
+def valid_images(imgs):
+ # If we have an list of images, make sure every image is valid
+ if isinstance(imgs, (list, tuple)):
+ for img in imgs:
+ if not valid_images(img):
+ return False
+ # If not a list of tuple, we have been given a single image or batched tensor of images
+ elif not is_valid_image(imgs):
+ return False
+ return True
+
+
+def is_batched(img):
+ if isinstance(img, (list, tuple)):
+ return is_valid_image(img[0])
+ return False
+
+
+def is_scaled_image(image: np.ndarray) -> bool:
+ """
+ Checks to see whether the pixel values have already been rescaled to [0, 1].
+ """
+ if image.dtype == np.uint8:
+ return False
+
+ # It's possible the image has pixel values in [0, 255] but is of floating type
+ return np.min(image) >= 0 and np.max(image) <= 1
+
+
+def make_list_of_images(images, expected_ndims: int = 3) -> List[ImageInput]:
+ """
+ Ensure that the output is a list of images. If the input is a single image, it is converted to a list of length 1.
+ If the input is a batch of images, it is converted to a list of images.
+
+ Args:
+ images (`ImageInput`):
+ Image of images to turn into a list of images.
+ expected_ndims (`int`, *optional*, defaults to 3):
+ Expected number of dimensions for a single input image. If the input image has a different number of
+ dimensions, an error is raised.
+ """
+ if is_batched(images):
+ return images
+
+ # Either the input is a single image, in which case we create a list of length 1
+ if is_pil_image(images):
+ # PIL images are never batched
+ return [images]
+
+ if is_valid_image(images):
+ if images.ndim == expected_ndims + 1:
+ # Batch of images
+ images = list(images)
+ elif images.ndim == expected_ndims:
+ # Single image
+ images = [images]
+ else:
+ raise ValueError(
+ f"Invalid image shape. Expected either {expected_ndims + 1} or {expected_ndims} dimensions, but got"
+ f" {images.ndim} dimensions."
+ )
+ return images
+ raise ValueError(
+ "Invalid image type. Expected either PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or "
+ f"jax.ndarray, but got {type(images)}."
+ )
+
+
+def make_flat_list_of_images(
+ images: Union[List[ImageInput], ImageInput],
+) -> ImageInput:
+ """
+ Ensure that the output is a flat list of images. If the input is a single image, it is converted to a list of length 1.
+ If the input is a nested list of images, it is converted to a flat list of images.
+ Args:
+ images (`Union[List[ImageInput], ImageInput]`):
+ The input image.
+ Returns:
+ list: A list of images or a 4d array of images.
+ """
+ # If the input is a nested list of images, we flatten it
+ if (
+ isinstance(images, (list, tuple))
+ and all(isinstance(images_i, (list, tuple)) for images_i in images)
+ and all(is_valid_list_of_images(images_i) for images_i in images)
+ ):
+ return [img for img_list in images for img in img_list]
+
+ if isinstance(images, (list, tuple)) and is_valid_list_of_images(images):
+ if is_pil_image(images[0]) or images[0].ndim == 3:
+ return images
+ if images[0].ndim == 4:
+ return [img for img_list in images for img in img_list]
+
+ if is_valid_image(images):
+ if is_pil_image(images) or images.ndim == 3:
+ return [images]
+ if images.ndim == 4:
+ return list(images)
+
+ raise ValueError(f"Could not make a flat list of images from {images}")
+
+
+def make_nested_list_of_images(
+ images: Union[List[ImageInput], ImageInput],
+) -> ImageInput:
+ """
+ Ensure that the output is a nested list of images.
+ Args:
+ images (`Union[List[ImageInput], ImageInput]`):
+ The input image.
+ Returns:
+ list: A list of list of images or a list of 4d array of images.
+ """
+ # If it's a list of batches, it's already in the right format
+ if (
+ isinstance(images, (list, tuple))
+ and all(isinstance(images_i, (list, tuple)) for images_i in images)
+ and all(is_valid_list_of_images(images_i) for images_i in images)
+ ):
+ return images
+
+ # If it's a list of images, it's a single batch, so convert it to a list of lists
+ if isinstance(images, (list, tuple)) and is_valid_list_of_images(images):
+ if is_pil_image(images[0]) or images[0].ndim == 3:
+ return [images]
+ if images[0].ndim == 4:
+ return [list(image) for image in images]
+
+ # If it's a single image, convert it to a list of lists
+ if is_valid_image(images):
+ if is_pil_image(images) or images.ndim == 3:
+ return [[images]]
+ if images.ndim == 4:
+ return [list(images)]
+
+ raise ValueError("Invalid input type. Must be a single image, a list of images, or a list of batches of images.")
+
+
+def make_batched_videos(videos) -> VideoInput:
+ """
+ Ensure that the input is a list of videos.
+ Args:
+ videos (`VideoInput`):
+ Video or videos to turn into a list of videos.
+ Returns:
+ list: A list of videos.
+ """
+ if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
+ # case 1: nested batch of videos so we flatten it
+ if not is_pil_image(videos[0][0]) and videos[0][0].ndim == 4:
+ videos = [[video for batch_list in batched_videos for video in batch_list] for batched_videos in videos]
+ # case 2: list of videos represented as list of video frames
+ return videos
+
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
+ if is_pil_image(videos[0]) or videos[0].ndim == 3:
+ return [videos]
+ elif videos[0].ndim == 4:
+ return [list(video) for video in videos]
+
+ elif is_valid_image(videos):
+ if is_pil_image(videos) or videos.ndim == 3:
+ return [[videos]]
+ elif videos.ndim == 4:
+ return [list(videos)]
+
+ raise ValueError(f"Could not make batched video from {videos}")
+
+
+def to_numpy_array(img) -> np.ndarray:
+ if not is_valid_image(img):
+ raise ValueError(f"Invalid image type: {type(img)}")
+
+ if is_vision_available() and isinstance(img, PIL.Image.Image):
+ return np.array(img)
+ return to_numpy(img)
+
+
+def infer_channel_dimension_format(
+ image: np.ndarray, num_channels: Optional[Union[int, Tuple[int, ...]]] = None
+) -> ChannelDimension:
+ """
+ Infers the channel dimension format of `image`.
+
+ Args:
+ image (`np.ndarray`):
+ The image to infer the channel dimension of.
+ num_channels (`int` or `Tuple[int, ...]`, *optional*, defaults to `(1, 3)`):
+ The number of channels of the image.
+
+ Returns:
+ The channel dimension of the image.
+ """
+ num_channels = num_channels if num_channels is not None else (1, 3)
+ num_channels = (num_channels,) if isinstance(num_channels, int) else num_channels
+
+ if image.ndim == 3:
+ first_dim, last_dim = 0, 2
+ elif image.ndim == 4:
+ first_dim, last_dim = 1, 3
+ else:
+ raise ValueError(f"Unsupported number of image dimensions: {image.ndim}")
+
+ if image.shape[first_dim] in num_channels and image.shape[last_dim] in num_channels:
+ logger.warning(
+ f"The channel dimension is ambiguous. Got image shape {image.shape}. Assuming channels are the first dimension."
+ )
+ return ChannelDimension.FIRST
+ elif image.shape[first_dim] in num_channels:
+ return ChannelDimension.FIRST
+ elif image.shape[last_dim] in num_channels:
+ return ChannelDimension.LAST
+ raise ValueError("Unable to infer channel dimension format")
+
+
+def get_channel_dimension_axis(
+ image: np.ndarray, input_data_format: Optional[Union[ChannelDimension, str]] = None
+) -> int:
+ """
+ Returns the channel dimension axis of the image.
+
+ Args:
+ image (`np.ndarray`):
+ The image to get the channel dimension axis of.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the image. If `None`, will infer the channel dimension from the image.
+
+ Returns:
+ The channel dimension axis of the image.
+ """
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+ if input_data_format == ChannelDimension.FIRST:
+ return image.ndim - 3
+ elif input_data_format == ChannelDimension.LAST:
+ return image.ndim - 1
+ raise ValueError(f"Unsupported data format: {input_data_format}")
+
+
+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*):
+ Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.
+
+ Returns:
+ A tuple of the image's height and width.
+ """
+ if channel_dim is None:
+ channel_dim = infer_channel_dimension_format(image)
+
+ if channel_dim == ChannelDimension.FIRST:
+ return image.shape[-2], image.shape[-1]
+ elif channel_dim == ChannelDimension.LAST:
+ return image.shape[-3], image.shape[-2]
+ else:
+ raise ValueError(f"Unsupported data format: {channel_dim}")
+
+
+def get_image_size_for_max_height_width(
+ image_size: Tuple[int, int],
+ max_height: int,
+ max_width: int,
+) -> Tuple[int, int]:
+ """
+ Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio.
+ Important, even if image_height < max_height and image_width < max_width, the image will be resized
+ to at least one of the edges be equal to max_height or max_width.
+
+ For example:
+ - input_size: (100, 200), max_height: 50, max_width: 50 -> output_size: (25, 50)
+ - input_size: (100, 200), max_height: 200, max_width: 500 -> output_size: (200, 400)
+
+ Args:
+ image_size (`Tuple[int, int]`):
+ The image to resize.
+ max_height (`int`):
+ The maximum allowed height.
+ max_width (`int`):
+ The maximum allowed width.
+ """
+ height, width = image_size
+ height_scale = max_height / height
+ width_scale = max_width / width
+ min_scale = min(height_scale, width_scale)
+ new_height = int(height * min_scale)
+ new_width = int(width * min_scale)
+ return new_height, new_width
+
+
+def is_valid_annotation_coco_detection(annotation: Dict[str, Union[List, Tuple]]) -> bool:
+ if (
+ isinstance(annotation, dict)
+ and "image_id" in annotation
+ and "annotations" in annotation
+ and isinstance(annotation["annotations"], (list, tuple))
+ and (
+ # an image can have no annotations
+ len(annotation["annotations"]) == 0 or isinstance(annotation["annotations"][0], dict)
+ )
+ ):
+ return True
+ return False
+
+
+def is_valid_annotation_coco_panoptic(annotation: Dict[str, Union[List, Tuple]]) -> bool:
+ if (
+ isinstance(annotation, dict)
+ and "image_id" in annotation
+ and "segments_info" in annotation
+ and "file_name" in annotation
+ and isinstance(annotation["segments_info"], (list, tuple))
+ and (
+ # an image can have no segments
+ len(annotation["segments_info"]) == 0 or isinstance(annotation["segments_info"][0], dict)
+ )
+ ):
+ return True
+ return False
+
+
+def valid_coco_detection_annotations(annotations: Iterable[Dict[str, Union[List, Tuple]]]) -> bool:
+ return all(is_valid_annotation_coco_detection(ann) for ann in annotations)
+
+
+def valid_coco_panoptic_annotations(annotations: Iterable[Dict[str, Union[List, Tuple]]]) -> bool:
+ return all(is_valid_annotation_coco_panoptic(ann) for ann in annotations)
+
+
+def load_image(image: Union[str, "PIL.Image.Image"], timeout: Optional[float] = None) -> "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.
+ timeout (`float`, *optional*):
+ The timeout value in seconds for the URL request.
+
+ Returns:
+ `PIL.Image.Image`: A PIL Image.
+ """
+ requires_backends(load_image, ["vision"])
+ if isinstance(image, str):
+ if image.startswith("http://") or image.startswith("https://"):
+ # We need to actually check for a real protocol, otherwise it's impossible to use a local file
+ # like http_huggingface_co.png
+ image = PIL.Image.open(BytesIO(requests.get(image, timeout=timeout).content))
+ elif os.path.isfile(image):
+ image = PIL.Image.open(image)
+ else:
+ if image.startswith("data:image/"):
+ image = image.split(",")[1]
+
+ # Try to load as base64
+ try:
+ b64 = base64.decodebytes(image.encode())
+ image = PIL.Image.open(BytesIO(b64))
+ except Exception as e:
+ raise ValueError(
+ f"Incorrect image source. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string. Got {image}. Failed with {e}"
+ )
+ elif isinstance(image, PIL.Image.Image):
+ image = image
+ else:
+ raise TypeError(
+ "Incorrect format used for image. Should be an url linking to an image, a base64 string, a local path, or a PIL image."
+ )
+ image = PIL.ImageOps.exif_transpose(image)
+ image = image.convert("RGB")
+ return image
+
+
+def default_sample_indices_fn(metadata: VideoMetadata, num_frames=None, fps=None, **kwargs):
+ """
+ A default sampling function that replicates the logic used in get_uniform_frame_indices,
+ while optionally handling `fps` if `num_frames` is not provided.
+
+ Args:
+ metadata (`VideoMetadata`):
+ `VideoMetadata` object containing metadat about the video, such as "total_num_frames" or "fps".
+ num_frames (`int`, *optional*):
+ Number of frames to sample uniformly.
+ fps (`int`, *optional*):
+ Desired frames per second. Takes priority over num_frames if both are provided.
+
+ Returns:
+ `np.ndarray`: Array of frame indices to sample.
+ """
+ total_num_frames = metadata.total_num_frames
+ video_fps = metadata.fps
+
+ # If num_frames is not given but fps is, calculate num_frames from fps
+ if num_frames is None and fps is not None:
+ num_frames = int(total_num_frames / video_fps * fps)
+ if num_frames > total_num_frames:
+ raise ValueError(
+ f"When loading the video with fps={fps}, we computed num_frames={num_frames} "
+ f"which exceeds total_num_frames={total_num_frames}. Check fps or video metadata."
+ )
+
+ if num_frames is not None:
+ indices = np.arange(0, total_num_frames, total_num_frames / num_frames, dtype=int)
+ else:
+ indices = np.arange(0, total_num_frames, dtype=int)
+ return indices
+
+
+def read_video_opencv(
+ video_path: str,
+ sample_indices_fn: Callable,
+ **kwargs,
+):
+ """
+ Decode a video using the OpenCV backend.
+
+ Args:
+ video_path (`str`):
+ Path to the video file.
+ sample_indices_fn (`Callable`):
+ A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
+ by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
+ If not provided, simple uniform sampling with fps is performed.
+ Example:
+ def sample_indices_fn(metadata, **kwargs):
+ return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)
+
+ Returns:
+ Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
+ - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
+ - `VideoMetadata` object.
+ """
+ # Lazy import cv2
+ requires_backends(read_video_opencv, ["cv2"])
+ import cv2
+
+ video = cv2.VideoCapture(video_path)
+ total_num_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
+ video_fps = video.get(cv2.CAP_PROP_FPS)
+ duration = total_num_frames / video_fps if video_fps else 0
+ metadata = VideoMetadata(
+ total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend="opencv"
+ )
+ indices = sample_indices_fn(metadata=metadata, **kwargs)
+
+ index = 0
+ frames = []
+ while video.isOpened():
+ success, frame = video.read()
+ if not success:
+ break
+ if index in indices:
+ height, width, channel = frame.shape
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+ frames.append(frame[0:height, 0:width, 0:channel])
+ if success:
+ index += 1
+ if index >= total_num_frames:
+ break
+
+ video.release()
+ metadata.frames_indices = indices
+ return np.stack(frames), metadata
+
+
+def read_video_decord(
+ video_path: str,
+ sample_indices_fn: Optional[Callable] = None,
+ **kwargs,
+):
+ """
+ Decode a video using the Decord backend.
+
+ Args:
+ video_path (`str`):
+ Path to the video file.
+ sample_indices_fn (`Callable`, *optional*):
+ A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
+ by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
+ If not provided, simple uniform sampling with fps is performed.
+ Example:
+ def sample_indices_fn(metadata, **kwargs):
+ return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)
+
+ Returns:
+ Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
+ - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
+ - `VideoMetadata` object.
+ """
+ # Lazy import from decord
+ requires_backends(read_video_decord, ["decord"])
+ from decord import VideoReader, cpu
+
+ vr = VideoReader(uri=video_path, ctx=cpu(0)) # decord has problems with gpu
+ video_fps = vr.get_avg_fps()
+ total_num_frames = len(vr)
+ duration = total_num_frames / video_fps if video_fps else 0
+ metadata = VideoMetadata(
+ total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend="decord"
+ )
+
+ indices = sample_indices_fn(metadata=metadata, **kwargs)
+
+ frames = vr.get_batch(indices).asnumpy()
+ metadata.frames_indices = indices
+ return frames, metadata
+
+
+def read_video_pyav(
+ video_path: str,
+ sample_indices_fn: Callable,
+ **kwargs,
+):
+ """
+ Decode the video with PyAV decoder.
+
+ Args:
+ video_path (`str`):
+ Path to the video file.
+ sample_indices_fn (`Callable`, *optional*):
+ A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
+ by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
+ If not provided, simple uniform sampling with fps is performed.
+ Example:
+ def sample_indices_fn(metadata, **kwargs):
+ return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)
+
+ Returns:
+ Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
+ - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
+ - `VideoMetadata` object.
+ """
+ # Lazy import av
+ requires_backends(read_video_pyav, ["av"])
+ import av
+
+ container = av.open(video_path)
+ total_num_frames = container.streams.video[0].frames
+ video_fps = container.streams.video[0].average_rate # should we better use `av_guess_frame_rate`?
+ duration = total_num_frames / video_fps if video_fps else 0
+ metadata = VideoMetadata(
+ total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend="pyav"
+ )
+ indices = sample_indices_fn(metadata=metadata, **kwargs)
+
+ frames = []
+ container.seek(0)
+ end_index = indices[-1]
+ for i, frame in enumerate(container.decode(video=0)):
+ if i > end_index:
+ break
+ if i >= 0 and i in indices:
+ frames.append(frame)
+
+ video = np.stack([x.to_ndarray(format="rgb24") for x in frames])
+ metadata.frames_indices = indices
+ return video, metadata
+
+
+def read_video_torchvision(
+ video_path: str,
+ sample_indices_fn: Callable,
+ **kwargs,
+):
+ """
+ Decode the video with torchvision decoder.
+
+ Args:
+ video_path (`str`):
+ Path to the video file.
+ sample_indices_fn (`Callable`, *optional*):
+ A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
+ by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
+ If not provided, simple uniform sampling with fps is performed.
+ Example:
+ def sample_indices_fn(metadata, **kwargs):
+ return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)
+
+ Returns:
+ Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
+ - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
+ - `VideoMetadata` object.
+ """
+ video, _, info = torchvision_io.read_video(
+ video_path,
+ start_pts=0.0,
+ end_pts=None,
+ pts_unit="sec",
+ output_format="THWC",
+ )
+ video_fps = info["video_fps"]
+ total_num_frames = video.size(0)
+ duration = total_num_frames / video_fps if video_fps else 0
+ metadata = VideoMetadata(
+ total_num_frames=int(total_num_frames),
+ fps=float(video_fps),
+ duration=float(duration),
+ video_backend="torchvision",
+ )
+
+ indices = sample_indices_fn(metadata=metadata, **kwargs)
+
+ video = video[indices].contiguous().numpy()
+ metadata.frames_indices = indices
+ return video, metadata
+
+
+VIDEO_DECODERS = {
+ "decord": read_video_decord,
+ "opencv": read_video_opencv,
+ "pyav": read_video_pyav,
+ "torchvision": read_video_torchvision,
+}
+
+
+def load_video(
+ video: Union[str, "VideoInput"],
+ num_frames: Optional[int] = None,
+ fps: Optional[int] = None,
+ backend: str = "opencv",
+ sample_indices_fn: Optional[Callable] = None,
+ **kwargs,
+) -> np.array:
+ """
+ Loads `video` to a numpy array.
+
+ Args:
+ video (`str` or `VideoInput`):
+ The video to convert to the numpy array format. Can be a link to video or local path.
+ num_frames (`int`, *optional*):
+ Number of frames to sample uniformly. If not passed, the whole video is loaded.
+ fps (`int`, *optional*):
+ Number of frames to sample per second. Should be passed only when `num_frames=None`.
+ If not specified and `num_frames==None`, all frames are sampled.
+ backend (`str`, *optional*, defaults to `"opencv"`):
+ The backend to use when loading the video. Can be any of ["decord", "pyav", "opencv", "torchvision"]. Defaults to "opencv".
+ sample_indices_fn (`Callable`, *optional*):
+ A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
+ by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
+ If not provided, simple uniformt sampling with fps is performed, otherwise `sample_indices_fn` has priority over other args.
+ The function expects at input the all args along with all kwargs passed to `load_video` and should output valid
+ indices at which the video should be sampled. For example:
+
+ Example:
+ def sample_indices_fn(metadata, **kwargs):
+ return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)
+
+ Returns:
+ Tuple[`np.array`, Dict]: A tuple containing:
+ - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
+ - Metadata dictionary.
+ """
+
+ # If `sample_indices_fn` is given, we can accept any args as those might be needed by custom `sample_indices_fn`
+ if fps is not None and num_frames is not None and sample_indices_fn is None:
+ raise ValueError(
+ "`num_frames`, `fps`, and `sample_indices_fn` are mutually exclusive arguments, please use only one!"
+ )
+
+ # If user didn't pass a sampling function, create one on the fly with default logic
+ if sample_indices_fn is None:
+
+ def sample_indices_fn_func(metadata, **fn_kwargs):
+ return default_sample_indices_fn(metadata, num_frames=num_frames, fps=fps, **fn_kwargs)
+
+ sample_indices_fn = sample_indices_fn_func
+
+ if video.startswith("https://www.youtube.com") or video.startswith("http://www.youtube.com"):
+ if not is_yt_dlp_available():
+ raise ImportError("To load a video from YouTube url you have to install `yt_dlp` first.")
+ # Lazy import from yt_dlp
+ requires_backends(load_video, ["yt_dlp"])
+ from yt_dlp import YoutubeDL
+
+ buffer = BytesIO()
+ with redirect_stdout(buffer), YoutubeDL() as f:
+ f.download([video])
+ bytes_obj = buffer.getvalue()
+ file_obj = BytesIO(bytes_obj)
+ elif video.startswith("http://") or video.startswith("https://"):
+ file_obj = BytesIO(requests.get(video).content)
+ elif os.path.isfile(video):
+ file_obj = video
+ elif is_valid_image(video) or (isinstance(video, (list, tuple)) and is_valid_image(video[0])):
+ file_obj = None
+ else:
+ raise TypeError("Incorrect format used for video. Should be an url linking to an video or a local path.")
+
+ # can also load with decord, but not cv2/torchvision
+ # both will fail in case of url links
+ video_is_url = video.startswith("http://") or video.startswith("https://")
+ if video_is_url and backend in ["opencv", "torchvision"]:
+ raise ValueError(
+ "If you are trying to load a video from URL, you can decode the video only with `pyav` or `decord` as backend"
+ )
+
+ if file_obj is None:
+ return video
+
+ if (
+ (not is_decord_available() and backend == "decord")
+ or (not is_av_available() and backend == "pyav")
+ or (not is_cv2_available() and backend == "opencv")
+ or (not is_torchvision_available() and backend == "torchvision")
+ ):
+ raise ImportError(
+ f"You chose backend={backend} for loading the video but the required library is not found in your environment "
+ f"Make sure to install {backend} before loading the video."
+ )
+
+ video_decoder = VIDEO_DECODERS[backend]
+ video, metadata = video_decoder(file_obj, sample_indices_fn, **kwargs)
+ return video, metadata
+
+
+def load_images(
+ images: Union[List, Tuple, str, "PIL.Image.Image"], timeout: Optional[float] = None
+) -> Union["PIL.Image.Image", List["PIL.Image.Image"], List[List["PIL.Image.Image"]]]:
+ """Loads images, handling different levels of nesting.
+
+ Args:
+ images: A single image, a list of images, or a list of lists of images to load.
+ timeout: Timeout for loading images.
+
+ Returns:
+ A single image, a list of images, a list of lists of images.
+ """
+ if isinstance(images, (list, tuple)):
+ if len(images) and isinstance(images[0], (list, tuple)):
+ return [[load_image(image, timeout=timeout) for image in image_group] for image_group in images]
+ else:
+ return [load_image(image, timeout=timeout) for image in images]
+ else:
+ return load_image(images, timeout=timeout)
+
+
+def validate_preprocess_arguments(
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, List[float]]] = None,
+ image_std: Optional[Union[float, List[float]]] = None,
+ do_pad: Optional[bool] = None,
+ size_divisibility: Optional[int] = None,
+ do_center_crop: Optional[bool] = None,
+ crop_size: Optional[Dict[str, int]] = None,
+ do_resize: Optional[bool] = None,
+ size: Optional[Dict[str, int]] = None,
+ resample: Optional["PILImageResampling"] = None,
+):
+ """
+ Checks validity of typically used arguments in an `ImageProcessor` `preprocess` method.
+ Raises `ValueError` if arguments incompatibility is caught.
+ Many incompatibilities are model-specific. `do_pad` sometimes needs `size_divisor`,
+ sometimes `size_divisibility`, and sometimes `size`. New models and processors added should follow
+ existing arguments when possible.
+
+ """
+ if do_rescale and rescale_factor is None:
+ raise ValueError("`rescale_factor` must be specified if `do_rescale` is `True`.")
+
+ if do_pad and size_divisibility is None:
+ # Here, size_divisor might be passed as the value of size
+ raise ValueError(
+ "Depending on the model, `size_divisibility`, `size_divisor`, `pad_size` or `size` must be specified if `do_pad` is `True`."
+ )
+
+ if do_normalize and (image_mean is None or image_std is None):
+ raise ValueError("`image_mean` and `image_std` must both be specified if `do_normalize` is `True`.")
+
+ if do_center_crop and crop_size is None:
+ raise ValueError("`crop_size` must be specified if `do_center_crop` is `True`.")
+
+ if do_resize and (size is None or resample is None):
+ raise ValueError("`size` and `resample` must be specified if `do_resize` is `True`.")
+
+
+def validate_fast_preprocess_arguments(
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, List[float]]] = None,
+ image_std: Optional[Union[float, List[float]]] = None,
+ do_pad: Optional[bool] = None,
+ size_divisibility: Optional[int] = None,
+ do_center_crop: Optional[bool] = None,
+ crop_size: Optional[Dict[str, int]] = None,
+ do_resize: Optional[bool] = None,
+ size: Optional[Dict[str, int]] = None,
+ resample: Optional["PILImageResampling"] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
+):
+ """
+ Checks validity of typically used arguments in an `ImageProcessorFast` `preprocess` method.
+ Raises `ValueError` if arguments incompatibility is caught.
+ """
+ validate_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_pad=do_pad,
+ size_divisibility=size_divisibility,
+ do_center_crop=do_center_crop,
+ crop_size=crop_size,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ )
+ # Extra checks for ImageProcessorFast
+ if return_tensors is not None and return_tensors != "pt":
+ raise ValueError("Only returning PyTorch tensors is currently supported.")
+
+ if data_format != ChannelDimension.FIRST:
+ raise ValueError("Only channel first data format is currently supported.")
+
+
+# In the future we can add a TF implementation here when we have TF models.
+class ImageFeatureExtractionMixin:
+ """
+ Mixin that contain utilities for preparing image features.
+ """
+
+ def _ensure_format_supported(self, image):
+ if not isinstance(image, (PIL.Image.Image, np.ndarray)) and not is_torch_tensor(image):
+ raise ValueError(
+ f"Got type {type(image)} which is not supported, only `PIL.Image.Image`, `np.array` and "
+ "`torch.Tensor` are."
+ )
+
+ 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 to the PIL Image format.
+ rescale (`bool`, *optional*):
+ Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will
+ default to `True` if the image type is a floating type, `False` otherwise.
+ """
+ self._ensure_format_supported(image)
+
+ if is_torch_tensor(image):
+ image = image.numpy()
+
+ if isinstance(image, np.ndarray):
+ if rescale is None:
+ # rescale default to the array being of floating type.
+ rescale = isinstance(image.flat[0], np.floating)
+ # If the channel as been moved to first dim, we put it back at the end.
+ if image.ndim == 3 and image.shape[0] in [1, 3]:
+ image = image.transpose(1, 2, 0)
+ if rescale:
+ image = image * 255
+ image = image.astype(np.uint8)
+ return PIL.Image.fromarray(image)
+ return image
+
+ 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
+
+ return image.convert("RGB")
+
+ 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
+
+ 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 image to convert to a NumPy array.
+ rescale (`bool`, *optional*):
+ Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Will
+ default to `True` if the image is a PIL Image or an array/tensor of integers, `False` otherwise.
+ channel_first (`bool`, *optional*, defaults to `True`):
+ Whether or not to permute the dimensions of the image to put the channel dimension first.
+ """
+ self._ensure_format_supported(image)
+
+ if isinstance(image, PIL.Image.Image):
+ image = np.array(image)
+
+ if is_torch_tensor(image):
+ image = image.numpy()
+
+ rescale = isinstance(image.flat[0], np.integer) if rescale is None else rescale
+
+ if rescale:
+ image = self.rescale(image.astype(np.float32), 1 / 255.0)
+
+ if channel_first and image.ndim == 3:
+ image = image.transpose(2, 0, 1)
+
+ return image
+
+ 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
+ if isinstance(image, PIL.Image.Image):
+ return image
+
+ if is_torch_tensor(image):
+ image = image.unsqueeze(0)
+ else:
+ image = np.expand_dims(image, axis=0)
+ return image
+
+ 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`):
+ The image to normalize.
+ mean (`List[float]` or `np.ndarray` or `torch.Tensor`):
+ The mean (per channel) to use for normalization.
+ std (`List[float]` or `np.ndarray` or `torch.Tensor`):
+ The standard deviation (per channel) to use for normalization.
+ rescale (`bool`, *optional*, defaults to `False`):
+ Whether or not to rescale the image to be between 0 and 1. If a PIL image is provided, scaling will
+ happen automatically.
+ """
+ self._ensure_format_supported(image)
+
+ if isinstance(image, PIL.Image.Image):
+ image = self.to_numpy_array(image, rescale=True)
+ # If the input image is a PIL image, it automatically gets rescaled. If it's another
+ # type it may need rescaling.
+ elif rescale:
+ if isinstance(image, np.ndarray):
+ image = self.rescale(image.astype(np.float32), 1 / 255.0)
+ elif is_torch_tensor(image):
+ image = self.rescale(image.float(), 1 / 255.0)
+
+ if isinstance(image, np.ndarray):
+ if not isinstance(mean, np.ndarray):
+ mean = np.array(mean).astype(image.dtype)
+ if not isinstance(std, np.ndarray):
+ std = np.array(std).astype(image.dtype)
+ elif is_torch_tensor(image):
+ import torch
+
+ if not isinstance(mean, torch.Tensor):
+ if isinstance(mean, np.ndarray):
+ mean = torch.from_numpy(mean)
+ else:
+ mean = torch.tensor(mean)
+ if not isinstance(std, torch.Tensor):
+ if isinstance(std, np.ndarray):
+ std = torch.from_numpy(std)
+ else:
+ std = torch.tensor(std)
+
+ if image.ndim == 3 and image.shape[0] in [1, 3]:
+ return (image - mean[:, None, None]) / std[:, None, None]
+ else:
+ return (image - mean) / std
+
+ 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 `Tuple[int, int]`):
+ The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be
+ matched to this.
+
+ If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If
+ `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to
+ this number. i.e, if height > width, then image will be rescaled to (size * height / width, size).
+ resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ The filter to user for resampling.
+ default_to_square (`bool`, *optional*, defaults to `True`):
+ How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a
+ square (`size`,`size`). If set to `False`, will replicate
+ [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)
+ with support for resizing only the smallest edge and providing an optional `max_size`.
+ max_size (`int`, *optional*, defaults to `None`):
+ The maximum allowed for the longer edge of the resized image: if the longer edge of the image is
+ greater than `max_size` after being resized according to `size`, then the image is resized again so
+ that the longer edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller
+ edge may be shorter than `size`. Only used if `default_to_square` is `False`.
+
+ Returns:
+ image: A resized `PIL.Image.Image`.
+ """
+ resample = resample if resample is not None else PILImageResampling.BILINEAR
+
+ self._ensure_format_supported(image)
+
+ if not isinstance(image, PIL.Image.Image):
+ image = self.to_pil_image(image)
+
+ if isinstance(size, list):
+ size = tuple(size)
+
+ if isinstance(size, int) or len(size) == 1:
+ if default_to_square:
+ size = (size, size) if isinstance(size, int) else (size[0], size[0])
+ else:
+ width, height = image.size
+ # specified size only for the smallest edge
+ short, long = (width, height) if width <= height else (height, width)
+ requested_new_short = size if isinstance(size, int) else size[0]
+
+ if short == requested_new_short:
+ return image
+
+ new_short, new_long = requested_new_short, int(requested_new_short * long / short)
+
+ if max_size is not None:
+ if max_size <= requested_new_short:
+ raise ValueError(
+ f"max_size = {max_size} must be strictly greater than the requested "
+ f"size for the smaller edge size = {size}"
+ )
+ if new_long > max_size:
+ new_short, new_long = int(max_size * new_short / new_long), max_size
+
+ size = (new_short, new_long) if width <= height else (new_long, new_short)
+
+ return image.resize(size, resample=resample)
+
+ 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 `torch.Tensor` of shape (n_channels, height, width) or (height, width, n_channels)):
+ The image to resize.
+ size (`int` or `Tuple[int, int]`):
+ The size to which crop the image.
+
+ Returns:
+ new_image: A center cropped `PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape: (n_channels,
+ height, width).
+ """
+ self._ensure_format_supported(image)
+
+ if not isinstance(size, tuple):
+ size = (size, size)
+
+ # PIL Image.size is (width, height) but NumPy array and torch Tensors have (height, width)
+ if is_torch_tensor(image) or isinstance(image, np.ndarray):
+ if image.ndim == 2:
+ image = self.expand_dims(image)
+ image_shape = image.shape[1:] if image.shape[0] in [1, 3] else image.shape[:2]
+ else:
+ image_shape = (image.size[1], image.size[0])
+
+ top = (image_shape[0] - size[0]) // 2
+ bottom = top + size[0] # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result.
+ left = (image_shape[1] - size[1]) // 2
+ right = left + size[1] # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result.
+
+ # For PIL Images we have a method to crop directly.
+ if isinstance(image, PIL.Image.Image):
+ return image.crop((left, top, right, bottom))
+
+ # Check if image is in (n_channels, height, width) or (height, width, n_channels) format
+ channel_first = True if image.shape[0] in [1, 3] else False
+
+ # Transpose (height, width, n_channels) format images
+ if not channel_first:
+ if isinstance(image, np.ndarray):
+ image = image.transpose(2, 0, 1)
+ if is_torch_tensor(image):
+ image = image.permute(2, 0, 1)
+
+ # Check if cropped area is within image boundaries
+ if top >= 0 and bottom <= image_shape[0] and left >= 0 and right <= image_shape[1]:
+ return image[..., top:bottom, left:right]
+
+ # Otherwise, we may need to pad if the image is too small. Oh joy...
+ new_shape = image.shape[:-2] + (max(size[0], image_shape[0]), max(size[1], image_shape[1]))
+ if isinstance(image, np.ndarray):
+ new_image = np.zeros_like(image, shape=new_shape)
+ elif is_torch_tensor(image):
+ new_image = image.new_zeros(new_shape)
+
+ top_pad = (new_shape[-2] - image_shape[0]) // 2
+ bottom_pad = top_pad + image_shape[0]
+ left_pad = (new_shape[-1] - image_shape[1]) // 2
+ right_pad = left_pad + image_shape[1]
+ new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image
+
+ top += top_pad
+ bottom += top_pad
+ left += left_pad
+ right += left_pad
+
+ new_image = new_image[
+ ..., max(0, top) : min(new_image.shape[-2], bottom), max(0, left) : min(new_image.shape[-1], right)
+ ]
+
+ return new_image
+
+ 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`):
+ The image whose color channels to flip. If `np.ndarray` or `torch.Tensor`, the channel dimension should
+ be first.
+ """
+ self._ensure_format_supported(image)
+
+ if isinstance(image, PIL.Image.Image):
+ image = self.to_numpy_array(image)
+
+ return image[::-1, :, :]
+
+ 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.Image.Image` or `np.ndarray` or `torch.Tensor`):
+ The image to rotate. If `np.ndarray` or `torch.Tensor`, will be converted to `PIL.Image.Image` before
+ rotating.
+
+ Returns:
+ image: A rotated `PIL.Image.Image`.
+ """
+ resample = resample if resample is not None else PIL.Image.NEAREST
+
+ self._ensure_format_supported(image)
+
+ if not isinstance(image, PIL.Image.Image):
+ image = self.to_pil_image(image)
+
+ return image.rotate(
+ angle, resample=resample, expand=expand, center=center, translate=translate, fillcolor=fillcolor
+ )
+
+
+def validate_annotations(
+ annotation_format: AnnotationFormat,
+ supported_annotation_formats: Tuple[AnnotationFormat, ...],
+ annotations: List[Dict],
+) -> None:
+ if annotation_format not in supported_annotation_formats:
+ raise ValueError(f"Unsupported annotation format: {format} must be one of {supported_annotation_formats}")
+
+ if annotation_format is AnnotationFormat.COCO_DETECTION:
+ if not valid_coco_detection_annotations(annotations):
+ raise ValueError(
+ "Invalid COCO detection annotations. Annotations must a dict (single image) or list of dicts "
+ "(batch of images) with the following keys: `image_id` and `annotations`, with the latter "
+ "being a list of annotations in the COCO format."
+ )
+
+ if annotation_format is AnnotationFormat.COCO_PANOPTIC:
+ if not valid_coco_panoptic_annotations(annotations):
+ raise ValueError(
+ "Invalid COCO panoptic annotations. Annotations must a dict (single image) or list of dicts "
+ "(batch of images) with the following keys: `image_id`, `file_name` and `segments_info`, with "
+ "the latter being a list of annotations in the COCO format."
+ )
+
+
+def validate_kwargs(valid_processor_keys: List[str], captured_kwargs: List[str]):
+ unused_keys = set(captured_kwargs).difference(set(valid_processor_keys))
+ if unused_keys:
+ unused_key_str = ", ".join(unused_keys)
+ # TODO raise a warning here instead of simply logging?
+ logger.warning(f"Unused or unrecognized kwargs: {unused_key_str}.")
+
+
+@dataclass(frozen=True)
+class SizeDict:
+ """
+ Hashable dictionary to store image size information.
+ """
+
+ height: int = None
+ width: int = None
+ longest_edge: int = None
+ shortest_edge: int = None
+ max_height: int = None
+ max_width: int = None
+
+ def __getitem__(self, key):
+ if hasattr(self, key):
+ return getattr(self, key)
+ raise KeyError(f"Key {key} not found in SizeDict.")
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/__init__.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b545c5da50a52e90a2fe765bcdb972c2258a2d95
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/__init__.py
@@ -0,0 +1,228 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
+
+
+_import_structure = {
+ "aqlm": ["replace_with_aqlm_linear"],
+ "awq": [
+ "fuse_awq_modules",
+ "post_init_awq_exllama_modules",
+ "post_init_awq_ipex_modules",
+ "replace_quantization_scales",
+ "replace_with_awq_linear",
+ ],
+ "bitnet": [
+ "BitLinear",
+ "pack_weights",
+ "replace_with_bitnet_linear",
+ "unpack_weights",
+ ],
+ "bitsandbytes": [
+ "dequantize_and_replace",
+ "get_keys_to_not_convert",
+ "replace_8bit_linear",
+ "replace_with_bnb_linear",
+ "set_module_8bit_tensor_to_device",
+ "set_module_quantized_tensor_to_device",
+ "validate_bnb_backend_availability",
+ ],
+ "deepspeed": [
+ "HfDeepSpeedConfig",
+ "HfTrainerDeepSpeedConfig",
+ "deepspeed_config",
+ "deepspeed_init",
+ "deepspeed_load_checkpoint",
+ "deepspeed_optim_sched",
+ "is_deepspeed_available",
+ "is_deepspeed_zero3_enabled",
+ "set_hf_deepspeed_config",
+ "unset_hf_deepspeed_config",
+ ],
+ "eetq": ["replace_with_eetq_linear"],
+ "fbgemm_fp8": ["FbgemmFp8Linear", "replace_with_fbgemm_fp8_linear"],
+ "finegrained_fp8": ["FP8Linear", "replace_with_fp8_linear"],
+ "fsdp": ["is_fsdp_managed_module"],
+ "ggml": [
+ "GGUF_CONFIG_MAPPING",
+ "GGUF_TOKENIZER_MAPPING",
+ "_gguf_parse_value",
+ "load_dequant_gguf_tensor",
+ "load_gguf",
+ ],
+ "higgs": ["HiggsLinear", "dequantize_higgs", "quantize_with_higgs", "replace_with_higgs_linear"],
+ "hqq": ["prepare_for_hqq_linear"],
+ "integration_utils": [
+ "INTEGRATION_TO_CALLBACK",
+ "AzureMLCallback",
+ "ClearMLCallback",
+ "CodeCarbonCallback",
+ "CometCallback",
+ "DagsHubCallback",
+ "DVCLiveCallback",
+ "FlyteCallback",
+ "MLflowCallback",
+ "NeptuneCallback",
+ "NeptuneMissingConfiguration",
+ "TensorBoardCallback",
+ "WandbCallback",
+ "get_available_reporting_integrations",
+ "get_reporting_integration_callbacks",
+ "hp_params",
+ "is_azureml_available",
+ "is_clearml_available",
+ "is_codecarbon_available",
+ "is_comet_available",
+ "is_dagshub_available",
+ "is_dvclive_available",
+ "is_flyte_deck_standard_available",
+ "is_flytekit_available",
+ "is_mlflow_available",
+ "is_neptune_available",
+ "is_optuna_available",
+ "is_ray_available",
+ "is_ray_tune_available",
+ "is_sigopt_available",
+ "is_tensorboard_available",
+ "is_wandb_available",
+ "rewrite_logs",
+ "run_hp_search_optuna",
+ "run_hp_search_ray",
+ "run_hp_search_sigopt",
+ "run_hp_search_wandb",
+ ],
+ "peft": ["PeftAdapterMixin"],
+ "quanto": ["replace_with_quanto_layers"],
+ "spqr": ["replace_with_spqr_linear"],
+ "vptq": ["replace_with_vptq_linear"],
+}
+
+try:
+ if not is_torch_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ pass
+else:
+ _import_structure["executorch"] = [
+ "TorchExportableModuleWithStaticCache",
+ "convert_and_export_with_cache",
+ ]
+
+if TYPE_CHECKING:
+ from .aqlm import replace_with_aqlm_linear
+ from .awq import (
+ fuse_awq_modules,
+ post_init_awq_exllama_modules,
+ post_init_awq_ipex_modules,
+ replace_quantization_scales,
+ replace_with_awq_linear,
+ )
+ from .bitnet import (
+ BitLinear,
+ pack_weights,
+ replace_with_bitnet_linear,
+ unpack_weights,
+ )
+ from .bitsandbytes import (
+ dequantize_and_replace,
+ get_keys_to_not_convert,
+ replace_8bit_linear,
+ replace_with_bnb_linear,
+ set_module_8bit_tensor_to_device,
+ set_module_quantized_tensor_to_device,
+ validate_bnb_backend_availability,
+ )
+ from .deepspeed import (
+ HfDeepSpeedConfig,
+ HfTrainerDeepSpeedConfig,
+ deepspeed_config,
+ deepspeed_init,
+ deepspeed_load_checkpoint,
+ deepspeed_optim_sched,
+ is_deepspeed_available,
+ is_deepspeed_zero3_enabled,
+ set_hf_deepspeed_config,
+ unset_hf_deepspeed_config,
+ )
+ from .eetq import replace_with_eetq_linear
+ from .fbgemm_fp8 import FbgemmFp8Linear, replace_with_fbgemm_fp8_linear
+ from .finegrained_fp8 import FP8Linear, replace_with_fp8_linear
+ from .fsdp import is_fsdp_managed_module
+ from .ggml import (
+ GGUF_CONFIG_MAPPING,
+ GGUF_TOKENIZER_MAPPING,
+ _gguf_parse_value,
+ load_dequant_gguf_tensor,
+ load_gguf,
+ )
+ from .higgs import HiggsLinear, dequantize_higgs, quantize_with_higgs, replace_with_higgs_linear
+ from .hqq import prepare_for_hqq_linear
+ from .integration_utils import (
+ INTEGRATION_TO_CALLBACK,
+ AzureMLCallback,
+ ClearMLCallback,
+ CodeCarbonCallback,
+ CometCallback,
+ DagsHubCallback,
+ DVCLiveCallback,
+ FlyteCallback,
+ MLflowCallback,
+ NeptuneCallback,
+ NeptuneMissingConfiguration,
+ TensorBoardCallback,
+ WandbCallback,
+ get_available_reporting_integrations,
+ get_reporting_integration_callbacks,
+ hp_params,
+ is_azureml_available,
+ is_clearml_available,
+ is_codecarbon_available,
+ is_comet_available,
+ is_dagshub_available,
+ is_dvclive_available,
+ is_flyte_deck_standard_available,
+ is_flytekit_available,
+ is_mlflow_available,
+ is_neptune_available,
+ is_optuna_available,
+ is_ray_available,
+ is_ray_tune_available,
+ is_sigopt_available,
+ is_tensorboard_available,
+ is_wandb_available,
+ rewrite_logs,
+ run_hp_search_optuna,
+ run_hp_search_ray,
+ run_hp_search_sigopt,
+ run_hp_search_wandb,
+ )
+ from .peft import PeftAdapterMixin
+ from .quanto import replace_with_quanto_layers
+ from .spqr import replace_with_spqr_linear
+ from .vptq import replace_with_vptq_linear
+
+ try:
+ if not is_torch_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ pass
+ else:
+ from .executorch import TorchExportableModuleWithStaticCache, convert_and_export_with_cache
+
+else:
+ import sys
+
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/aqlm.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/aqlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..0626da7aced5bc259295ac51c58931858aac8dc8
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/aqlm.py
@@ -0,0 +1,100 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"AQLM (Additive Quantization of Language Model) integration file"
+
+from ..utils import ACCELERATE_MIN_VERSION, is_accelerate_available, is_aqlm_available, is_torch_available
+
+
+if is_torch_available():
+ import torch.nn as nn
+
+
+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 use this method. Returns the converted model and a boolean that indicates if the
+ conversion has been successfull or not.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`AqlmConfig`):
+ The quantization config object that contains the quantization parameters.
+ linear_weights_not_to_quantize (`list[str]`, *optional*):
+ A list of nn.Linear weights to not convert. If a parameter path is in the list (e.g. `lm_head.weight`), the corresponding module will not be
+ converted.
+ current_key_name (`list`, *optional*):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+ if not is_aqlm_available():
+ raise ValueError("AQLM is not available. Please install it with `pip install aqlm[cpu,gpu]`")
+
+ if not is_accelerate_available():
+ raise ValueError(
+ f"AQLM requires Accelerate to be installed: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`"
+ )
+
+ if linear_weights_not_to_quantize is None:
+ linear_weights_not_to_quantize = []
+
+ from accelerate import init_empty_weights
+ from aqlm import QuantizedLinear
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, nn.Linear):
+ # Check if the current key is not in the `linear_weights_not_to_quantize`
+ if ".".join(current_key_name) + ".weight" not in linear_weights_not_to_quantize:
+ with init_empty_weights():
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = QuantizedLinear(
+ in_features,
+ out_features,
+ bias=module.bias is not None,
+ in_group_size=quantization_config.in_group_size,
+ out_group_size=quantization_config.out_group_size,
+ num_codebooks=quantization_config.num_codebooks,
+ nbits_per_codebook=quantization_config.nbits_per_codebook,
+ )
+ has_been_replaced = True
+
+ # Store the module class in case we need to transpose the weight later
+ model._modules[name].source_cls = type(module)
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_aqlm_linear(
+ module,
+ quantization_config=quantization_config,
+ linear_weights_not_to_quantize=linear_weights_not_to_quantize,
+ current_key_name=current_key_name,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/awq.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/awq.py
new file mode 100644
index 0000000000000000000000000000000000000000..c860ea1f53744bba6a4d63bc73ee51a187fc92f8
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/awq.py
@@ -0,0 +1,498 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"AWQ (Activation aware Weight Quantization) integration file"
+
+import importlib
+
+from packaging import version
+
+from ..activations import ACT2FN
+from ..modeling_utils import PreTrainedModel
+from ..utils import is_auto_awq_available, is_ipex_available, is_torch_available, logging
+from ..utils.quantization_config import (
+ AwqBackendPackingMethod,
+ AwqConfig,
+ AWQLinearVersion,
+ ExllamaVersion,
+)
+
+
+if is_torch_available():
+ import torch
+ import torch.nn as nn
+
+logger = logging.get_logger(__name__)
+
+AWQ_FUSED_MAPPINGS = {
+ "mistral": {
+ "attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
+ "mlp": ["gate_proj", "up_proj", "down_proj"],
+ "layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
+ "use_alibi": False,
+ },
+ "mixtral": {
+ "attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
+ "mlp": ["w1", "w3", "w2"],
+ "layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
+ "use_alibi": False,
+ "rope_theta": 1000000.0,
+ },
+ "llama": {
+ "attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
+ "mlp": ["gate_proj", "up_proj", "down_proj"],
+ "layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
+ "use_alibi": False,
+ },
+ "llava": {
+ "attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
+ "mlp": ["gate_proj", "up_proj", "down_proj"],
+ "layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
+ "use_alibi": False,
+ },
+}
+
+AWQ_SCALES_MAPPINGS = {
+ "starcoder2": {"act": "act", "layer_before_act": "c_fc"},
+ "RefinedWebModel": {"act": "act", "layer_before_act": "dense_h_to_4h"},
+ "falcon": {"act": "act", "layer_before_act": "dense_h_to_4h"},
+ "mpt": {"act": "act", "layer_before_act": "up_proj"},
+ "gptj": {"act": "act", "layer_before_act": "fc_in"},
+ "gpt_neox": {"act": "act", "layer_before_act": "dense_h_to_4h"},
+ "gpt_bigcode": {"act": "act", "layer_before_act": "c_fc"},
+ "bloom": {"act": "gelu_impl", "layer_before_act": "dense_h_to_4h"},
+}
+
+
+def replace_quantization_scales(model, model_type):
+ from awq.modules.act import ScaledActivation
+
+ if model_type not in AWQ_SCALES_MAPPINGS:
+ return model
+ for name, module in model.named_children():
+ act_name = AWQ_SCALES_MAPPINGS[model_type]["act"]
+ layer_before_act_name = AWQ_SCALES_MAPPINGS[model_type]["layer_before_act"]
+ if name == act_name and hasattr(model, layer_before_act_name):
+ layer_before_act = getattr(model, AWQ_SCALES_MAPPINGS[model_type]["layer_before_act"])
+ size = layer_before_act.out_features
+ scale_like = torch.ones(size)
+ model._modules[name] = ScaledActivation(module, scale_like)
+ _ = replace_quantization_scales(module, model_type)
+ return model
+
+
+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 this method. Returns the converted model and a boolean that indicates if the
+ conversion has been successfull or not.
+
+ During the module replacement, we also infer the backend to use through the `quantization_config` object.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`AwqConfig`):
+ The quantization config object that contains the quantization parameters.
+ modules_to_not_convert (`list`, *optional*):
+ A list of modules to not convert. If a module name is in the list (e.g. `lm_head`), it will not be
+ converted.
+ current_key_name (`list`, *optional*):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+ if modules_to_not_convert is None:
+ modules_to_not_convert = []
+
+ backend = quantization_config.backend
+
+ if not is_auto_awq_available():
+ raise ValueError(
+ "AWQ (either `autoawq` or `llmawq`) is not available. Please install it with `pip install autoawq` or check out the installation guide in https://github.com/mit-han-lab/llm-awq"
+ )
+
+ if backend == AwqBackendPackingMethod.AUTOAWQ:
+ if quantization_config.version == AWQLinearVersion.GEMM:
+ from awq.modules.linear.gemm import WQLinear_GEMM
+
+ target_cls = WQLinear_GEMM
+ elif quantization_config.version == AWQLinearVersion.GEMV:
+ from awq.modules.linear.gemv import WQLinear_GEMV
+
+ target_cls = WQLinear_GEMV
+ elif quantization_config.version == AWQLinearVersion.EXLLAMA:
+ if quantization_config.exllama_config["version"] == ExllamaVersion.ONE:
+ from awq.modules.linear.exllama import WQLinear_Exllama
+
+ target_cls = WQLinear_Exllama
+ elif quantization_config.exllama_config["version"] == ExllamaVersion.TWO:
+ from awq.modules.linear.exllamav2 import WQLinear_ExllamaV2
+
+ target_cls = WQLinear_ExllamaV2
+ else:
+ raise ValueError(f"Unrecognized Exllama version: {quantization_config.exllama_config['version']}")
+ elif quantization_config.version == AWQLinearVersion.IPEX:
+ from awq.modules.linear.gemm_ipex import WQLinear_IPEX
+
+ target_cls = WQLinear_IPEX
+ else:
+ raise ValueError(f"Unrecognized AWQ version: {quantization_config.version}")
+ else:
+ from awq.quantize.qmodule import WQLinear
+
+ target_cls = WQLinear
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, nn.Linear) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ if not any(key in ".".join(current_key_name) for key in modules_to_not_convert):
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = target_cls(
+ w_bit=quantization_config.bits,
+ group_size=quantization_config.group_size,
+ in_features=in_features,
+ out_features=out_features,
+ bias=module.bias is not None,
+ dev=module.weight.device,
+ )
+ has_been_replaced = True
+
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_awq_linear(
+ module,
+ modules_to_not_convert=modules_to_not_convert,
+ current_key_name=current_key_name,
+ quantization_config=quantization_config,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+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 (`~transformers.quantization_config.AWQConfig`):
+ The quantization configuration to use.
+ """
+ if not isinstance(model, PreTrainedModel):
+ raise TypeError(f"The model should be an instance of `PreTrainedModel`, got {model.__class__.__name__}")
+
+ # Always default to `quantization_config.modules_to_fuse`
+ if quantization_config.modules_to_fuse is not None:
+ current_fused_mapping = quantization_config.modules_to_fuse
+ current_fused_mapping["max_seq_len"] = quantization_config.fuse_max_seq_len
+ elif model.config.model_type in AWQ_FUSED_MAPPINGS:
+ current_fused_mapping = AWQ_FUSED_MAPPINGS[model.config.model_type]
+
+ # Properly deal with the case where we have a multi-modal model as well (e.g. Llava)
+ config = model.config.get_text_config(decoder=True)
+
+ # Handle hidden_size, num_attention_heads, num_key_value_heads on our own.
+ hidden_size = config.hidden_size
+ num_attention_heads = config.num_attention_heads
+ num_key_value_heads = getattr(config, "num_key_value_heads", num_attention_heads)
+
+ # Fill `current_fused_mapping` with the expected values
+ current_fused_mapping["hidden_size"] = hidden_size
+ current_fused_mapping["num_attention_heads"] = num_attention_heads
+ current_fused_mapping["num_key_value_heads"] = num_key_value_heads
+ current_fused_mapping["max_seq_len"] = quantization_config.fuse_max_seq_len
+ else:
+ raise ValueError(
+ "Fusing mapping not found either on the quantization config or the supported `AWQ_FUSED_MAPPINGS`. Please pass a `fused_mapping` argument"
+ " in the `quantization_config` or raise an issue on transformers https://github.com/huggingface/transformers to add its support."
+ )
+ return current_fused_mapping
+
+
+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[AwqConfig, dict]`):
+ The quantization configuration to use.
+ """
+ # We need to convert it from dict in order to get an AwqConfig object
+ # otherwise the fields `backend` etc. will not be available
+ # https://github.com/huggingface/transformers/pull/27411#discussion_r1414044495
+ if isinstance(quantization_config, dict):
+ quantization_config = AwqConfig.from_dict(quantization_config)
+ backend = quantization_config.backend
+
+ modules_to_fuse = get_modules_to_fuse(model, quantization_config)
+ modules_to_not_convert = getattr(quantization_config, "modules_to_not_convert", None)
+
+ if backend == AwqBackendPackingMethod.AUTOAWQ:
+ from awq.modules.fused.attn import QuantAttentionFused
+ from awq.modules.fused.mlp import QuantFusedMLP
+ from awq.modules.fused.norm import FasterTransformerRMSNorm
+ else:
+ raise ValueError("Fusing is only supported for the AutoAWQ backend")
+
+ fused_attention_modules = []
+
+ for name, module in model.named_modules():
+ if modules_to_not_convert is not None:
+ if any(module_name_to_not_convert in name for module_name_to_not_convert in modules_to_not_convert):
+ continue
+
+ # Replace layer norms
+ _fuse_awq_layernorm(modules_to_fuse["layernorm"], module, FasterTransformerRMSNorm)
+
+ # Replace MLP layers if awq version is not ipex.
+ if quantization_config.version != "ipex":
+ _fuse_awq_mlp(model, name, modules_to_fuse["mlp"], module, QuantFusedMLP)
+ else:
+ logger.info("The IPEX version AWQ does not support fuse mlp for now.")
+
+ # Replace attention layers
+ attention_has_been_fused = _fuse_awq_attention_layers(
+ model, module, modules_to_fuse, name, QuantAttentionFused
+ )
+
+ if attention_has_been_fused:
+ fused_attention_modules.append(name.split(".")[0])
+
+ # For AWQ fused + Llama we need to set `config._attn_implementation` = "custom" to avoid unexpected behavior and pass
+ # `None` attention mask to the fused attention modules as now the attention mask is dropped by our models and dealt
+ # by the `AttentionMaskConverter` module.
+ if len(fused_attention_modules) > 0:
+ for module_name, module in model.named_modules():
+ if any(
+ module_name in fused_attention_modules for fused_attention_parent_module in fused_attention_modules
+ ):
+ if hasattr(module, "config") and hasattr(module.config, "_attn_implementation"):
+ module.config._attn_implementation = "custom"
+ return model
+
+
+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 modules to fuse
+ target_cls (`~autoawq.FasterTransformerRMSNorm`):
+ The `FasterTransformerRMSNorm` class as it only supports that class
+ for now.
+ """
+ for module_name in fuse_module_names:
+ if hasattr(module, module_name):
+ old_module = getattr(module, module_name)
+ module._modules[module_name] = target_cls(
+ old_module.weight,
+ old_module.variance_epsilon,
+ ).to(old_module.weight.device)
+ del old_module
+
+
+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_module_names (`List[str]`):
+ The list of module names to fuse. For the MLP layers it has to be an array
+ of length 3 that consists of the 3 MLP layers in the order (gate (dense layer post-attention) / up / down layers)
+ module (`nn.Module`):
+ The pytorch parent module that has layernorm modules to fuse
+ target_cls (`~autoawq.QuantFusedMLP`):
+ The `QuantFusedMLP` class as it only supports that class
+ for now.
+ """
+ if len(fuse_module_names) == 0:
+ return
+
+ if hasattr(module, fuse_module_names[0]):
+ gate_proj = getattr(module, fuse_module_names[0])
+ up_proj = getattr(module, fuse_module_names[1])
+ down_proj = getattr(module, fuse_module_names[2])
+
+ previous_device = gate_proj.qweight.device
+
+ # Deal also with the case model has `text_config` attribute
+ config = model.config.get_text_config(decoder=True)
+ hidden_act = config.hidden_act
+ activation_fn = ACT2FN[hidden_act]
+ new_module = target_cls(gate_proj, down_proj, up_proj, activation_fn)
+
+ parent_name, child_name = current_module_name.rsplit(".", 1)
+ parent = model.get_submodule(parent_name)
+ setattr(parent, child_name, new_module.to(previous_device))
+
+ del gate_proj, up_proj, down_proj
+
+
+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 module that has layernorm modules to fuse
+ modules_to_fuse (`List[str]`):
+ The module fusing mapping. The dictionary has to contain a field `attention` with attention module names
+ in the correct order: q, k, v, o layer
+ current_module_name (`str`):
+ The current submodule name
+ target_cls (`~autoawq.QuantAttentionFused`):
+ The `QuantAttentionFused` class as it only supports that class
+ for now.
+ """
+ from awq.modules.linear import WQLinear_GEMM, WQLinear_GEMV
+
+ module_has_been_fused = False
+
+ if len(modules_to_fuse["attention"]) == 0:
+ return module_has_been_fused
+
+ if hasattr(module, modules_to_fuse["attention"][0]):
+ # First, we pack the QKV layers together
+ q_proj = getattr(module, modules_to_fuse["attention"][0])
+
+ if isinstance(q_proj, WQLinear_GEMV):
+ linear_target_cls = WQLinear_GEMV
+ cat_dim = 0
+ elif isinstance(q_proj, WQLinear_GEMM):
+ linear_target_cls = WQLinear_GEMM
+ cat_dim = 1
+ elif is_ipex_available() and version.parse(importlib.metadata.version("autoawq")) > version.parse("0.2.6"):
+ from awq.modules.linear import WQLinear_IPEX
+
+ if isinstance(q_proj, WQLinear_IPEX):
+ linear_target_cls = WQLinear_IPEX
+ cat_dim = 1
+ else:
+ raise ValueError("Unsupported q_proj type: {type(q_proj)}")
+
+ previous_device = q_proj.qweight.device
+
+ k_proj = getattr(module, modules_to_fuse["attention"][1])
+ v_proj = getattr(module, modules_to_fuse["attention"][2])
+ o_proj = getattr(module, modules_to_fuse["attention"][3])
+
+ bias = torch.cat([q_proj.bias, k_proj.bias, v_proj.bias], dim=0) if q_proj.bias is not None else None
+
+ qkv_layer = linear_target_cls(
+ q_proj.w_bit,
+ q_proj.group_size,
+ q_proj.in_features,
+ q_proj.out_features + k_proj.out_features + v_proj.out_features,
+ q_proj.bias is not None,
+ next(iter(module.state_dict().values())).device,
+ )
+
+ qkv_layer.qweight = torch.cat([q_proj.qweight, k_proj.qweight, v_proj.qweight], dim=cat_dim)
+ qkv_layer.qzeros = torch.cat([q_proj.qzeros, k_proj.qzeros, v_proj.qzeros], dim=cat_dim)
+ qkv_layer.scales = torch.cat([q_proj.scales, k_proj.scales, v_proj.scales], dim=cat_dim)
+
+ if isinstance(qkv_layer, WQLinear_GEMV):
+ qkv_layer.split_k_iters = q_proj.split_k_iters
+
+ qkv_layer.bias = bias
+
+ fused_attention_layer = target_cls(
+ modules_to_fuse["hidden_size"],
+ modules_to_fuse["num_attention_heads"],
+ modules_to_fuse["num_key_value_heads"],
+ qkv_layer,
+ o_proj,
+ previous_device,
+ modules_to_fuse["max_seq_len"],
+ use_alibi=modules_to_fuse["use_alibi"],
+ # The default value in autoawq is set to 10000.0
+ rope_theta=modules_to_fuse.get("rope_theta", 10000.0),
+ )
+
+ fused_attention_layer.is_hf_transformers = True
+
+ parent_name, child_name = current_module_name.rsplit(".", 1)
+ parent = model.get_submodule(parent_name)
+ setattr(parent, child_name, fused_attention_layer.to(previous_device))
+
+ del q_proj, k_proj, v_proj, o_proj
+ module_has_been_fused = True
+
+ return module_has_been_fused
+
+
+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.exllama import exllama_post_init
+
+ model = exllama_post_init(model)
+ elif exllama_config["version"] == ExllamaVersion.TWO:
+ from awq.modules.linear.exllamav2 import exllamav2_post_init
+
+ model = exllamav2_post_init(
+ model,
+ max_input_len=exllama_config["max_input_len"],
+ max_batch_size=exllama_config["max_batch_size"],
+ )
+ else:
+ raise ValueError(f"Unrecognized Exllama version: {exllama_config['version']}")
+
+ return model
+
+
+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
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/bitnet.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/bitnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b50f9738afb69e680371b5f868bc4508f2a60e7
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/bitnet.py
@@ -0,0 +1,288 @@
+from ..utils import is_accelerate_available, is_torch_available, logging
+
+
+if is_accelerate_available():
+ from accelerate import init_empty_weights
+
+if is_torch_available():
+ import torch
+ import torch.nn as nn
+ import torch.nn.functional as F
+
+logger = logging.get_logger(__name__)
+
+
+# the weights are ternary so can be represented with 2 bits, and they are packed in uint8 tensors, hence the number of values per item is 4
+VALUES_PER_ITEM = 4
+
+
+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 values are adjusted to
+ {0, 1, 2} before being packed.
+
+ Returns:
+ --------
+ torch.Tensor
+ A packed tensor where each element stores 4 quantized values (each using 2 bits) in an 8-bit format.
+ """
+
+ original_shape = quantized_weights.shape
+
+ row_dim = (original_shape[0] + VALUES_PER_ITEM - 1) // VALUES_PER_ITEM
+
+ if len(original_shape) == 1:
+ packed_tensor_shape = (row_dim,)
+ else:
+ packed_tensor_shape = (row_dim, *original_shape[1:])
+
+ quantized_weights += 1
+ packed = torch.zeros(packed_tensor_shape, device=quantized_weights.device, dtype=torch.uint8)
+ unpacked = quantized_weights.to(torch.uint8)
+
+ it = min(VALUES_PER_ITEM, (original_shape[0] // row_dim) + 1)
+ for i in range(it):
+ start = i * row_dim
+ end = min(start + row_dim, original_shape[0])
+ packed[: (end - start)] |= unpacked[start:end] << 2 * i
+
+ return packed
+
+
+@torch.compile
+def unpack_weights(packed: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
+ """
+ Unpacks a tensor of quantized weights that were stored in a packed format using 2 bits per value.
+
+ Parameters:
+ -----------
+ packed : torch.Tensor
+ A tensor containing packed weights where each element represents 4 quantized values (using 2 bits per value).
+ dtype : torch.dtype
+ The dtype of the returned Tensor
+ Returns:
+ --------
+ torch.Tensor
+ A tensor of unpacked weights, where each value is converted from its packed 2-bit representation.
+
+ Example:
+ --------
+ packed = torch.tensor([[0b10100001, 0b00011000],
+ [0b10010000, 0b00001010]], dtype=torch.uint8)
+
+ # Unpack the values
+ unpacked = unpack_weights(packed)
+
+ # Resulting unpacked tensor
+ print(unpacked)
+ # Output: tensor([[ 0, -1],
+ [-1, 1],
+ [-1, 1],
+ [-1, 1],
+ [ 1, 0],
+ [ 0, -1],
+ [ 1, -1],
+ [ 1, -1]])
+
+ Explanation of the example:
+ ---------------------------
+ Let's take the first value for example 0b10100001, we we will only focus on the first column,
+ because every element is unpacked across the first dimension
+ - First 2 bits: `01` → 0 at [0][0]
+ - Second 2 bits: `00` → -1 at [0][2]
+ - Third 2 bits: `10` → 1 at [0][4]
+ - Fourth 2 bits: `10` → 1 at [0][6]
+ the second value of the same row (0b10010000) will give the values for [0][1], [0][3], [0][5], [0][7]
+
+ We subtract 1 because during the packing process, it's easier to work with values like 0, 1, and 2. To make this possible,
+ we add 1 to the original ternary weights (which are typically -1, 0, and 1) when packing them. When unpacking, we reverse
+ this by subtracting 1 to restore the original ternary values.
+ """
+ packed_shape = packed.shape
+
+ if len(packed_shape) == 1:
+ original_row_dim = packed_shape[0] * VALUES_PER_ITEM
+ unpacked_shape = (original_row_dim,)
+ else:
+ original_row_dim = packed_shape[0] * VALUES_PER_ITEM
+ unpacked_shape = (original_row_dim, *packed_shape[1:])
+
+ unpacked = torch.zeros(unpacked_shape, device=packed.device, dtype=torch.uint8)
+
+ for i in range(VALUES_PER_ITEM):
+ start = i * packed_shape[0]
+ end = start + packed_shape[0]
+ mask = 3 << (2 * i)
+ unpacked[start:end] = (packed & mask) >> (2 * i)
+
+ return unpacked.to(dtype) - 1
+
+
+class BitLinear(nn.Module):
+ def __init__(self, in_features: int, out_features: int, bias: bool, device=None, dtype=None):
+ super().__init__()
+ self.dtype = dtype
+ self.in_features = in_features
+ self.out_features = out_features
+ self.register_buffer(
+ "weight",
+ torch.zeros(
+ (out_features // VALUES_PER_ITEM, in_features),
+ dtype=torch.uint8,
+ device=device,
+ ),
+ )
+ self.register_buffer(
+ "weight_scale",
+ torch.ones(
+ (1),
+ dtype=dtype,
+ device=device,
+ ),
+ )
+ if bias:
+ self.register_buffer("bias", torch.zeros((out_features), dtype=dtype, device=device))
+ else:
+ self.bias = None
+
+ @torch.compile
+ 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)
+ Number of bits to use for quantization, determining the quantization range.
+
+ Returns:
+ --------
+ result : torch.Tensor
+ Quantized activation tensor, with values mapped to an `int8` range.
+ scale : torch.Tensor
+ The per-channel scaling factors used to quantize the tensor.
+ """
+ Qn = -(2 ** (num_bits - 1))
+ Qp = 2 ** (num_bits - 1) - 1
+ scale = Qp / input.abs().max(dim=-1, keepdim=True).values.clamp(min=1e-5)
+ result = (input * scale).round().clamp(Qn, Qp)
+ return result.to(torch.int8), scale
+
+ @torch.compile
+ def post_quant_process(self, input, input_scale, weight_scale):
+ out = input / (input_scale * weight_scale)
+ return out
+
+ def forward(self, input):
+ w = self.weight
+ w_quant = unpack_weights(w, dtype=self.dtype)
+ input_quant, input_scale = self.activation_quant(input)
+ y = F.linear(input_quant.to(self.dtype), w_quant)
+ y = self.post_quant_process(y, self.weight_scale, input_scale)
+ if self.bias is not None:
+ y += self.bias.view(1, -1).expand_as(y)
+ return y
+
+
+def _replace_with_bitnet_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+ pre_quantized=False,
+):
+ """
+ Private method that wraps the recursion for module replacement.
+
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+ """
+
+ if current_key_name is None:
+ current_key_name = []
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ # Check if the current key is not in the `modules_to_not_convert`
+ if not any(key in ".".join(current_key_name) for key in modules_to_not_convert):
+ with init_empty_weights():
+ if isinstance(module, nn.Linear) and name not in modules_to_not_convert:
+ in_features = module.in_features
+ out_features = module.out_features
+ model._modules[name] = BitLinear(
+ in_features=in_features,
+ out_features=out_features,
+ bias=module.bias is not None,
+ device=module.weight.device,
+ dtype=module.weight.dtype,
+ )
+ has_been_replaced = True
+ model._modules[name].requires_grad_(False)
+
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _replace_with_bitnet_linear(
+ module,
+ modules_to_not_convert=modules_to_not_convert,
+ current_key_name=current_key_name,
+ quantization_config=quantization_config,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+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 `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 manager so no
+ CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model or `torch.nn.Module` as the function is run recursively.
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
+ Names of the modules to not convert in `EetqLinear`. In practice we keep the `lm_head` in full precision
+ for numerical stability reasons.
+ current_key_name (`List[`str`]`, *optional*):
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
+ it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
+ `disk`).
+ """
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
+ if quantization_config and quantization_config.modules_to_not_convert is not None:
+ modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
+ modules_to_not_convert = list(set(modules_to_not_convert))
+ model, has_been_replaced = _replace_with_bitnet_linear(
+ model,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ pre_quantized=pre_quantized,
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model using bitnet but no linear modules were found in your model."
+ " Please double check your model architecture, or submit an issue on github if you think this is"
+ " a bug."
+ )
+
+ return model
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/bitsandbytes.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/bitsandbytes.py
new file mode 100644
index 0000000000000000000000000000000000000000..61e9f8d8db5d6e6eb6b32c2584fd91ddae52036b
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/bitsandbytes.py
@@ -0,0 +1,559 @@
+import importlib.metadata
+import inspect
+import warnings
+from copy import deepcopy
+from inspect import signature
+
+from packaging import version
+
+from ..utils import (
+ get_available_devices,
+ is_accelerate_available,
+ is_bitsandbytes_available,
+ is_bitsandbytes_multi_backend_available,
+ is_ipex_available,
+ is_torch_available,
+ logging,
+)
+
+
+if is_bitsandbytes_available():
+ import bitsandbytes as bnb
+ import torch
+ import torch.nn as nn
+
+ from ..pytorch_utils import Conv1D
+
+if is_accelerate_available():
+ import accelerate
+ from accelerate import init_empty_weights
+ from accelerate.hooks import add_hook_to_module, remove_hook_from_module
+ from accelerate.utils import find_tied_parameters
+
+logger = logging.get_logger(__name__)
+
+
+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 need this function). The
+ function is adapted from `set_module_tensor_to_device` function from accelerate that is adapted to support the
+ class `Int8Params` from `bitsandbytes`.
+
+ Args:
+ module (`torch.nn.Module`):
+ The module in which the tensor we want to move lives.
+ tensor_name (`str`):
+ The full name of the parameter/buffer.
+ device (`int`, `str` or `torch.device`):
+ The device on which to set the tensor.
+ value (`torch.Tensor`, *optional*):
+ The value of the tensor (useful when going from the meta device to any other device).
+ quantized_stats (`dict[str, Any]`, *optional*):
+ Dict with items for either 4-bit or 8-bit serialization
+ """
+ # Recurse if needed
+ if "." in tensor_name:
+ splits = tensor_name.split(".")
+ for split in splits[:-1]:
+ new_module = getattr(module, split)
+ if new_module is None:
+ raise ValueError(f"{module} has no attribute {split}.")
+ module = new_module
+ tensor_name = splits[-1]
+
+ if tensor_name not in module._parameters and tensor_name not in module._buffers:
+ raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
+ is_buffer = tensor_name in module._buffers
+ old_value = getattr(module, tensor_name)
+
+ if old_value.device == torch.device("meta") and device not in ["meta", torch.device("meta")] and value is None:
+ raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}.")
+
+ prequantized_loading = quantized_stats is not None
+ if is_buffer or not is_bitsandbytes_available():
+ is_8bit = False
+ is_4bit = False
+ else:
+ is_4bit = hasattr(bnb.nn, "Params4bit") and isinstance(module._parameters[tensor_name], bnb.nn.Params4bit)
+ is_8bit = isinstance(module._parameters[tensor_name], bnb.nn.Int8Params)
+
+ if is_8bit or is_4bit:
+ param = module._parameters[tensor_name]
+ if param.device.type != "cuda":
+ if value is None:
+ new_value = old_value.to(device)
+ elif isinstance(value, torch.Tensor):
+ new_value = value.to("cpu")
+ else:
+ new_value = torch.tensor(value, device="cpu")
+
+ # Support models using `Conv1D` in place of `nn.Linear` (e.g. openai-community/gpt2) by transposing the weight matrix prior to quantization.
+ # Since weights are saved in the correct "orientation", we skip transposing when loading.
+ if issubclass(module.source_cls, Conv1D) and not prequantized_loading:
+ new_value = new_value.T
+
+ kwargs = old_value.__dict__
+
+ if prequantized_loading != (new_value.dtype in (torch.int8, torch.uint8)):
+ raise ValueError(
+ f"Value dtype `{new_value.dtype}` is not compatible with parameter quantization status."
+ )
+
+ if is_8bit:
+ is_8bit_serializable = version.parse(importlib.metadata.version("bitsandbytes")) > version.parse(
+ "0.37.2"
+ )
+ if new_value.dtype in (torch.int8, torch.uint8) and not is_8bit_serializable:
+ raise ValueError(
+ "Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. "
+ "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
+ )
+ new_value = bnb.nn.Int8Params(new_value, requires_grad=False, **kwargs).to(device)
+ if prequantized_loading:
+ setattr(new_value, "SCB", quantized_stats["SCB"].to(device))
+ elif is_4bit:
+ if prequantized_loading:
+ is_4bit_serializable = version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse(
+ "0.41.3"
+ )
+ if new_value.dtype in (torch.int8, torch.uint8) and not is_4bit_serializable:
+ raise ValueError(
+ "Detected 4-bit weights but the version of bitsandbytes is not compatible with 4-bit serialization. "
+ "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
+ )
+ new_value = bnb.nn.Params4bit.from_prequantized(
+ data=new_value,
+ quantized_stats=quantized_stats,
+ requires_grad=False,
+ device=device,
+ **kwargs,
+ )
+ else:
+ new_value = bnb.nn.Params4bit(new_value, requires_grad=False, **kwargs).to(device)
+ module._parameters[tensor_name] = new_value
+
+ else:
+ if value is None:
+ new_value = old_value.to(device)
+ elif isinstance(value, torch.Tensor):
+ new_value = value.to(device)
+ else:
+ new_value = torch.tensor(value, device=device)
+
+ if is_buffer:
+ module._buffers[tensor_name] = new_value
+ else:
+ new_value = nn.Parameter(new_value, requires_grad=old_value.requires_grad)
+ module._parameters[tensor_name] = new_value
+
+
+def _replace_with_bnb_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+):
+ """
+ Private method that wraps the recursion for module replacement.
+
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+ """
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if (isinstance(module, nn.Linear) or isinstance(module, Conv1D)) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+ if not any(
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
+ ):
+ with init_empty_weights():
+ if isinstance(module, Conv1D):
+ in_features, out_features = module.weight.shape
+ else:
+ in_features = module.in_features
+ out_features = module.out_features
+
+ if quantization_config.quantization_method() == "llm_int8":
+ model._modules[name] = bnb.nn.Linear8bitLt(
+ in_features,
+ out_features,
+ module.bias is not None,
+ has_fp16_weights=quantization_config.llm_int8_has_fp16_weight,
+ threshold=quantization_config.llm_int8_threshold,
+ )
+ has_been_replaced = True
+ else:
+ if (
+ quantization_config.llm_int8_skip_modules is not None
+ and name in quantization_config.llm_int8_skip_modules
+ ):
+ pass
+ else:
+ extra_kwargs = (
+ {"quant_storage": quantization_config.bnb_4bit_quant_storage}
+ if "quant_storage" in list(signature(bnb.nn.Linear4bit).parameters)
+ else {}
+ )
+ model._modules[name] = bnb.nn.Linear4bit(
+ in_features,
+ out_features,
+ module.bias is not None,
+ quantization_config.bnb_4bit_compute_dtype,
+ compress_statistics=quantization_config.bnb_4bit_use_double_quant,
+ quant_type=quantization_config.bnb_4bit_quant_type,
+ **extra_kwargs,
+ )
+ has_been_replaced = True
+ # Store the module class in case we need to transpose the weight later
+ model._modules[name].source_cls = type(module)
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _replace_with_bnb_linear(
+ module,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+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 described by the paper `LLM.int8():
+ 8-bit Matrix Multiplication for Transformers at Scale`. Make sure `bitsandbytes` compiled with the correct CUDA
+ version of your hardware is installed before running this function. `pip install -i https://test.pypi.org/simple/
+ bitsandbytes`
+
+ 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 manager so no
+ CPU/GPU memory is required to run this function. Int8 mixed-precision matrix decomposition works by separating a
+ matrix multiplication into two streams: (1) and systematic feature outlier stream matrix multiplied in fp16
+ (0.01%), (2) a regular stream of int8 matrix multiplication (99.9%). With this method, int8 inference with no
+ predictive degradation is possible for very large models (>=176B parameters).
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model or `torch.nn.Module` as the function is run recursively.
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
+ Names of the modules to not convert in `Linear8bitLt`. In practice we keep the `lm_head` in full precision
+ for numerical stability reasons.
+ current_key_name (`List[`str`]`, *optional*):
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
+ it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
+ `disk`).
+ quantization_config ('transformers.utils.quantization_config.BitsAndBytesConfig'):
+ To configure and manage settings related to quantization, a technique used to compress neural network models
+ by reducing the precision of the weights and activations, thus making models more efficient in terms of both
+ storage and computation.
+ """
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
+ model, has_been_replaced = _replace_with_bnb_linear(
+ model, modules_to_not_convert, current_key_name, quantization_config
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model in 8bit or 4bit but no linear modules were found in your model."
+ " Please double check your model architecture, or submit an issue on github if you think this is"
+ " a bug."
+ )
+
+ return model
+
+
+# For backward compatibility
+def replace_8bit_linear(*args, **kwargs):
+ warnings.warn(
+ "`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead",
+ FutureWarning,
+ )
+ return replace_with_bnb_linear(*args, **kwargs)
+
+
+# For backward compatiblity
+def set_module_8bit_tensor_to_device(*args, **kwargs):
+ warnings.warn(
+ "`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead",
+ FutureWarning,
+ )
+ return set_module_quantized_tensor_to_device(*args, **kwargs)
+
+
+def get_keys_to_not_convert(model):
+ r"""
+ An utility function to get the key of the module to keep in full precision if any For example for CausalLM modules
+ we may want to keep the lm_head in full precision for numerical stability reasons. For other architectures, we want
+ to keep the tied weights of the model. The function will return a list of the keys of the modules to not convert in
+ int8.
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model
+ """
+ # Create a copy of the model and tie the weights, then
+ # check if it contains tied weights
+ tied_model = deepcopy(model) # this has 0 cost since it is done inside `init_empty_weights` context manager`
+ tied_model.tie_weights()
+
+ tied_params = find_tied_parameters(tied_model)
+ # For compatibility with Accelerate < 0.18
+ if isinstance(tied_params, dict):
+ tied_keys = sum(list(tied_params.values()), []) + list(tied_params.keys())
+ else:
+ tied_keys = sum(tied_params, [])
+ has_tied_params = len(tied_keys) > 0
+
+ # If there is not tied weights, we want to keep the lm_head(output_embedding) in full precision
+ if not has_tied_params:
+ output_emb = model.get_output_embeddings()
+ if output_emb is not None:
+ list_last_module = [name for name, module in model.named_modules() if id(module) == id(output_emb)]
+ return list_last_module
+
+ # otherwise, no tied weights, no output embedding defined, simply keep the last module in full precision
+ list_modules = list(model.named_parameters())
+ list_last_module = [list_modules[-1][0]]
+ # add last module together with tied weights
+ intersection = set(list_last_module) - set(tied_keys)
+ list_untouched = list(set(tied_keys)) + list(intersection)
+
+ # remove ".weight" from the keys
+ names_to_remove = [".weight", ".bias"]
+ filtered_module_names = []
+ for name in list_untouched:
+ for name_to_remove in names_to_remove:
+ if name_to_remove in name:
+ name = name.replace(name_to_remove, "")
+ filtered_module_names.append(name)
+
+ return filtered_module_names
+
+
+# Copied from PEFT: https://github.com/huggingface/peft/blob/47b3712898539569c02ec5b3ed4a6c36811331a1/src/peft/utils/integrations.py#L41
+def dequantize_bnb_weight(weight: "torch.nn.Parameter", dtype: "torch.dtype", state=None):
+ """
+ Helper function to dequantize 4bit or 8bit bnb weights.
+
+ If the weight is not a bnb quantized weight, it will be returned as is.
+ """
+ if not isinstance(weight, torch.nn.Parameter):
+ raise TypeError(f"Input weight should be of type nn.Parameter, got {type(weight)} instead")
+
+ cls_name = weight.__class__.__name__
+ if cls_name not in ("Params4bit", "Int8Params"):
+ return weight
+
+ if cls_name == "Params4bit":
+ output_tensor = bnb.functional.dequantize_4bit(weight.data, weight.quant_state)
+ logger.warning_once(
+ f"The model is going to be dequantized in {output_tensor.dtype} - if you want to upcast it to another dtype, make sure to pass the desired dtype when quantizing the model through `bnb_4bit_quant_type` argument of `BitsAndBytesConfig`"
+ )
+ return output_tensor.to(dtype)
+
+ if state.SCB is None:
+ state.SCB = weight.SCB
+
+ if hasattr(bnb.functional, "int8_vectorwise_dequant"):
+ # Use bitsandbytes API if available (requires v0.45.0+)
+ dequantized = bnb.functional.int8_vectorwise_dequant(weight.data, state.SCB)
+ else:
+ # Multiply by (scale/127) to dequantize.
+ dequantized = weight.data * state.SCB.view(-1, 1) * 7.874015718698502e-3
+
+ return dequantized.to(dtype)
+
+
+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
+ """
+ old_hook_cls = getattr(accelerate.hooks, old_hook.__class__.__name__)
+ old_hook_attr = old_hook.__dict__
+ filtered_old_hook_attr = {}
+ old_hook_init_signature = inspect.signature(old_hook_cls.__init__)
+ for k in old_hook_attr.keys():
+ if k in old_hook_init_signature.parameters:
+ filtered_old_hook_attr[k] = old_hook_attr[k]
+ new_hook = old_hook_cls(**filtered_old_hook_attr)
+ return new_hook
+
+
+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 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 the conversion has been successfull or not.
+ """
+ quant_method = quantization_config.quantization_method()
+
+ target_cls = bnb.nn.Linear8bitLt if quant_method == "llm_int8" else bnb.nn.Linear4bit
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, target_cls) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+
+ if not any(
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
+ ):
+ bias = getattr(module, "bias", None)
+
+ device = module.weight.device
+ with init_empty_weights():
+ new_module = torch.nn.Linear(module.in_features, module.out_features, bias=bias is not None)
+
+ if quant_method == "llm_int8":
+ state = module.state
+ else:
+ state = None
+
+ new_module.weight = torch.nn.Parameter(dequantize_bnb_weight(module.weight, dtype, state))
+
+ if bias is not None:
+ new_module.bias = bias
+
+ # Create a new hook and attach it in case we use accelerate
+ if hasattr(module, "_hf_hook"):
+ old_hook = module._hf_hook
+ new_hook = _create_accelerate_new_hook(old_hook)
+
+ remove_hook_from_module(module)
+ add_hook_to_module(new_module, new_hook)
+
+ new_module.to(device)
+ model._modules[name] = new_module
+ has_been_replaced = True
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _dequantize_and_replace(
+ module,
+ dtype,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+def dequantize_and_replace(
+ model,
+ modules_to_not_convert=None,
+ quantization_config=None,
+):
+ model, has_been_replaced = _dequantize_and_replace(
+ model,
+ model.dtype,
+ modules_to_not_convert=modules_to_not_convert,
+ quantization_config=quantization_config,
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "For some reason the model has not been properly dequantized. You might see unexpected behavior."
+ )
+
+ return model
+
+
+def _validate_bnb_multi_backend_availability(raise_exception):
+ import bitsandbytes as bnb
+
+ bnb_supported_devices = getattr(bnb, "supported_torch_devices", set())
+ available_devices = set(get_available_devices())
+
+ if available_devices == {"cpu"} and not is_ipex_available():
+ from importlib.util import find_spec
+
+ if find_spec("intel_extension_for_pytorch"):
+ logger.warning(
+ "You have Intel IPEX installed but if you're intending to use it for CPU, it might not have the right version. Be sure to double check that your PyTorch and IPEX installs are compatible."
+ )
+
+ available_devices.discard("cpu") # Only Intel CPU is supported by BNB at the moment
+
+ if not available_devices.intersection(bnb_supported_devices):
+ if raise_exception:
+ bnb_supported_devices_with_info = set( # noqa: C401
+ '"cpu" (needs an Intel CPU and intel_extension_for_pytorch installed and compatible with the PyTorch version)'
+ if device == "cpu"
+ else device
+ for device in bnb_supported_devices
+ )
+ err_msg = (
+ f"None of the available devices `available_devices = {available_devices or None}` are supported by the bitsandbytes version you have installed: `bnb_supported_devices = {bnb_supported_devices_with_info}`. "
+ "Please check the docs to see if the backend you intend to use is available and how to install it: https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend"
+ )
+
+ logger.error(err_msg)
+ raise RuntimeError(err_msg)
+
+ logger.warning("No supported devices found for bitsandbytes multi-backend.")
+ return False
+
+ logger.debug("Multi-backend validation successful.")
+ return True
+
+
+def _validate_bnb_cuda_backend_availability(raise_exception):
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if not torch.cuda.is_available():
+ log_msg = (
+ "CUDA is required but not available for bitsandbytes. Please consider installing the multi-platform enabled version of bitsandbytes, which is currently a work in progress. "
+ "Please check currently supported platforms and installation instructions at https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend"
+ )
+ if raise_exception:
+ logger.error(log_msg)
+ raise RuntimeError(log_msg)
+
+ logger.warning(log_msg)
+ return False
+
+ logger.debug("CUDA backend validation successful.")
+ return True
+
+
+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.metadata.version("bitsandbytes")
+ ) < version.parse("0.43.1"):
+ return _validate_bnb_cuda_backend_availability(raise_exception)
+ return False
+
+ if is_bitsandbytes_multi_backend_available():
+ return _validate_bnb_multi_backend_availability(raise_exception)
+ return _validate_bnb_cuda_backend_availability(raise_exception)
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/deepspeed.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/deepspeed.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b51a531645d9fd172083f8a13f3fad1890b7409
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/deepspeed.py
@@ -0,0 +1,499 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Integration with Deepspeed
+"""
+
+import copy
+import importlib.metadata as importlib_metadata
+import importlib.util
+import weakref
+from functools import partialmethod
+
+from ..dependency_versions_check import dep_version_check
+from ..utils import is_accelerate_available, is_torch_available, is_torch_mlu_available, logging
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+
+logger = logging.get_logger(__name__)
+
+
+def is_deepspeed_available():
+ package_exists = importlib.util.find_spec("deepspeed") is not None
+
+ # Check we're not importing a "deepspeed" directory somewhere but the actual library by trying to grab the version
+ # AND checking it has an author field in the metadata that is HuggingFace.
+ if package_exists:
+ try:
+ if is_torch_mlu_available():
+ _ = importlib_metadata.metadata("deepspeed-mlu")
+ return True
+ _ = importlib_metadata.metadata("deepspeed")
+ return True
+ except importlib_metadata.PackageNotFoundError:
+ return False
+
+
+if is_accelerate_available() and is_deepspeed_available():
+ from accelerate.utils.deepspeed import HfDeepSpeedConfig as DeepSpeedConfig
+else:
+ # Inherits from a dummy `object` if accelerate is not available, so that python succeeds to import this file.
+ # Deepspeed glue code will never inherit this dummy object as it checks if accelerate is available.
+ from builtins import object as DeepSpeedConfig
+
+
+class HfDeepSpeedConfig(DeepSpeedConfig):
+ """
+ This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage.
+
+ A `weakref` of this object is stored in the module's globals to be able to access the config from areas where
+ things like the Trainer object is not available (e.g. `from_pretrained` and `_get_resized_embeddings`). Therefore
+ it's important that this object remains alive while the program is still running.
+
+ [`Trainer`] uses the `HfTrainerDeepSpeedConfig` subclass instead. That subclass has logic to sync the configuration
+ with values of [`TrainingArguments`] by replacing special placeholder values: `"auto"`. Without this special logic
+ the DeepSpeed configuration is not modified in any way.
+
+ Args:
+ config_file_or_dict (`Union[str, Dict]`): path to DeepSpeed config file or dict.
+
+ """
+
+ def __init__(self, config_file_or_dict):
+ # set global weakref object
+ set_hf_deepspeed_config(self)
+ dep_version_check("accelerate")
+ dep_version_check("deepspeed")
+ super().__init__(config_file_or_dict)
+
+
+class HfTrainerDeepSpeedConfig(HfDeepSpeedConfig):
+ """
+ The `HfTrainerDeepSpeedConfig` object is meant to be created during `TrainingArguments` object creation and has the
+ same lifespan as the latter.
+ """
+
+ def __init__(self, config_file_or_dict):
+ super().__init__(config_file_or_dict)
+ self._dtype = None
+ self.mismatches = []
+
+ def dtype(self):
+ if self._dtype is None:
+ raise ValueError("trainer_config_process() wasn't called yet to tell dtype")
+ return self._dtype
+
+ def is_auto(self, ds_key_long):
+ val = self.get_value(ds_key_long)
+ if val is None:
+ return False
+ else:
+ return val == "auto"
+
+ def fill_match(self, ds_key_long, hf_val, hf_key=None, must_match=True):
+ """
+ A utility method that massages the config file and can optionally verify that the values match.
+
+ 1. Replace "auto" values with `TrainingArguments` value.
+
+ 2. If it wasn't "auto" and `must_match` is true, then check that DS config matches Trainer
+ config values and if mismatched add the entry to `self.mismatched` - will assert during
+ `trainer_config_finalize` for one or more mismatches.
+
+ """
+ config, ds_key = self.find_config_node(ds_key_long)
+ if config is None:
+ return
+
+ if config.get(ds_key) == "auto":
+ config[ds_key] = hf_val
+ return
+
+ if not must_match:
+ return
+
+ ds_val = config.get(ds_key)
+ if ds_val is not None and ds_val != hf_val:
+ self.mismatches.append(f"- ds {ds_key_long}={ds_val} vs hf {hf_key}={hf_val}")
+
+ fill_only = partialmethod(fill_match, must_match=False)
+
+ def trainer_config_process(self, args, auto_find_batch_size=False):
+ """
+ Adjust the config with `TrainingArguments` values. This stage is run during `TrainingArguments` object
+ creation.
+ """
+ # DeepSpeed does:
+ # train_batch_size = world_size * train_micro_batch_size_per_gpu * gradient_accumulation_steps
+ train_batch_size = args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps
+ self.fill_match(
+ "train_micro_batch_size_per_gpu",
+ args.per_device_train_batch_size,
+ "per_device_train_batch_size",
+ not auto_find_batch_size,
+ )
+ self.fill_match(
+ "gradient_accumulation_steps",
+ args.gradient_accumulation_steps,
+ "gradient_accumulation_steps",
+ )
+ self.fill_match(
+ "train_batch_size",
+ train_batch_size,
+ "train_batch_size (calculated)",
+ not auto_find_batch_size,
+ )
+ self.fill_match("gradient_clipping", args.max_grad_norm, "max_grad_norm")
+
+ self.fill_match("optimizer.params.lr", args.learning_rate, "learning_rate")
+ self.fill_match(
+ "optimizer.params.betas",
+ [args.adam_beta1, args.adam_beta2],
+ "adam_beta1+adam_beta2",
+ )
+ self.fill_match("optimizer.params.eps", args.adam_epsilon, "adam_epsilon")
+ self.fill_match("optimizer.params.weight_decay", args.weight_decay, "weight_decay")
+
+ self.fill_only("scheduler.params.warmup_min_lr", 0) # not a trainer arg
+ self.fill_match("scheduler.params.warmup_max_lr", args.learning_rate, "learning_rate")
+ # total_num_steps - will get set in trainer_config_finalize
+
+ # fp16
+ if args.fp16 or args.fp16_full_eval:
+ fp16_backend = "apex" if args.fp16_backend == "apex" else "amp"
+ else:
+ fp16_backend = None
+
+ if args.save_on_each_node:
+ # deepspeed uses shared storage by default. Let's override this setting if save_on_each_node == True
+ self.config["checkpoint"] = self.config.get("checkpoint", {})
+ self.config["checkpoint"]["use_node_local_storage"] = args.save_on_each_node
+
+ # amp: similar to the pytorch native amp - it has a bunch of optional params but we won't set
+ # any here unless the user did the work
+ self.fill_match(
+ "fp16.enabled",
+ ((args.fp16 or args.fp16_full_eval) and fp16_backend == "amp"),
+ "fp16|fp16_full_eval+fp16_backend(amp)",
+ )
+
+ # apex: delegates amp work to apex (which needs to be available), but it cannot be used with any
+ # ZeRO features
+ self.fill_match("amp.enabled", fp16_backend == "apex", "fp16+fp16_backend(apex)")
+ self.fill_match("amp.opt_level", args.fp16_opt_level, "fp16_opt_level")
+
+ self.fill_match("bf16.enabled", (args.bf16 or args.bf16_full_eval), "bf16|bf16_full_eval")
+
+ # deepspeed's default mode is fp16 unless there is a config that says differently
+ if self.is_true("bf16.enabled"):
+ self._dtype = torch.bfloat16
+ elif self.is_false("fp16.enabled"):
+ self._dtype = torch.float32
+ else:
+ self._dtype = torch.float16
+
+ def trainer_config_finalize(self, args, model, num_training_steps):
+ """
+ This stage is run after we have the model and know num_training_steps.
+
+ Now we can complete the configuration process.
+ """
+ # zero
+
+ # deal with config keys that use `auto` value and rely on model's hidden_size
+ hidden_size_based_keys = [
+ "zero_optimization.reduce_bucket_size",
+ "zero_optimization.stage3_prefetch_bucket_size",
+ "zero_optimization.stage3_param_persistence_threshold",
+ ]
+ hidden_size_auto_keys = [x for x in hidden_size_based_keys if self.is_auto(x)]
+
+ if len(hidden_size_auto_keys) > 0:
+ if hasattr(model.config, "hidden_size"):
+ hidden_size = model.config.hidden_size
+ elif hasattr(model.config, "hidden_sizes"):
+ # if there are many hidden sizes pick the largest one
+ hidden_size = max(model.config.hidden_sizes)
+ elif hasattr(model.config, "text_config") and hasattr(model.config.text_config, "hidden_size"):
+ hidden_size = model.config.text_config.hidden_size
+ elif hasattr(model.config, "text_config") and hasattr(model.config.text_config, "hidden_sizes"):
+ # if there are many hidden sizes pick the largest one
+ hidden_size = max(model.config.text_config.hidden_sizes)
+ else:
+ raise ValueError(
+ "The model's config file has neither `hidden_size` nor `hidden_sizes` entry, "
+ "therefore it's not possible to automatically fill out the following `auto` entries "
+ f"in the DeepSpeed config file: {hidden_size_auto_keys}. You can fix that by replacing "
+ "`auto` values for these keys with an integer value of your choice."
+ )
+
+ self.fill_only("zero_optimization.reduce_bucket_size", hidden_size * hidden_size)
+ if self.is_zero3():
+ # automatically assign the optimal config values based on model config
+ self.fill_only(
+ "zero_optimization.stage3_prefetch_bucket_size",
+ int(0.9 * hidden_size * hidden_size),
+ )
+ self.fill_only(
+ "zero_optimization.stage3_param_persistence_threshold",
+ 10 * hidden_size,
+ )
+
+ # scheduler
+ self.fill_match(
+ "scheduler.params.total_num_steps",
+ num_training_steps,
+ "num_training_steps (calculated)",
+ )
+ self.fill_match(
+ "scheduler.params.warmup_num_steps",
+ args.get_warmup_steps(num_training_steps),
+ "warmup_steps",
+ )
+
+ if len(self.mismatches) > 0:
+ mismatches = "\n".join(self.mismatches)
+ raise ValueError(
+ "Please correct the following DeepSpeed config values that mismatch TrainingArguments"
+ f" values:\n{mismatches}\nThe easiest method is to set these DeepSpeed config values to 'auto'."
+ )
+
+
+# keep the config object global to be able to access it anywhere during TrainingArguments life-cycle
+_hf_deepspeed_config_weak_ref = None
+
+
+def set_hf_deepspeed_config(hf_deepspeed_config_obj):
+ # this is a special weakref global object to allow us to get to Deepspeed config from APIs
+ # that don't have an easy way to get to the Deepspeed config outside of the Trainer domain.
+ global _hf_deepspeed_config_weak_ref
+ # will go away automatically when HfDeepSpeedConfig is destroyed (when TrainingArguments is destroyed)
+ _hf_deepspeed_config_weak_ref = weakref.ref(hf_deepspeed_config_obj)
+
+
+def unset_hf_deepspeed_config():
+ # useful for unit tests to ensure the global state doesn't leak - call from `tearDown` method
+ global _hf_deepspeed_config_weak_ref
+ _hf_deepspeed_config_weak_ref = None
+
+
+def is_deepspeed_zero3_enabled():
+ if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
+ return _hf_deepspeed_config_weak_ref().is_zero3()
+ else:
+ return False
+
+
+def deepspeed_config():
+ if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
+ return _hf_deepspeed_config_weak_ref().config
+ else:
+ return None
+
+
+def _load_state_dict_into_zero3_model(model_to_load, state_dict, start_prefix, assign_to_params_buffers=False):
+ """
+ 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_state_dict_into_zero3_model` can modify it
+ metadata = getattr(state_dict, "_metadata", None)
+ state_dict = state_dict.copy()
+ if metadata is not None:
+ state_dict._metadata = metadata
+
+ error_msgs = []
+
+ # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants
+ # so we need to apply the function recursively.
+ def load(module: nn.Module, state_dict, prefix="", assign_to_params_buffers=False):
+ local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
+ local_metadata["assign_to_params_buffers"] = assign_to_params_buffers
+
+ args = (state_dict, prefix, local_metadata, True, [], [], error_msgs)
+ # Parameters of module and children will start with prefix. We can exit early if there are none in this
+ # state_dict
+ if is_deepspeed_zero3_enabled() and len([key for key in state_dict if key.startswith(prefix)]) > 0:
+ import deepspeed
+
+ # In sharded models, each shard has only part of the full state_dict, so only gather
+ # parameters that are in the current state_dict.
+ named_parameters = dict(module.named_parameters(prefix=prefix[:-1], recurse=False))
+ params_to_gather = [named_parameters[k] for k in state_dict.keys() if k in named_parameters]
+ if len(params_to_gather) > 0:
+ # because zero3 puts placeholders in model params, this context
+ # manager gathers (unpartitions) the params of the current layer, then loads from
+ # the state dict and then re-partitions them again
+ with deepspeed.zero.GatheredParameters(params_to_gather, modifier_rank=0):
+ if torch.distributed.get_rank() == 0:
+ module._load_from_state_dict(*args)
+
+ for name, child in module._modules.items():
+ if child is not None:
+ load(child, state_dict, prefix + name + ".", assign_to_params_buffers)
+
+ load(model_to_load, state_dict, prefix=start_prefix, assign_to_params_buffers=assign_to_params_buffers)
+ # Delete `state_dict` so it could be collected by GC earlier. Note that `state_dict` is a copy of the argument, so
+ # it's safe to delete it.
+ del state_dict
+
+ return error_msgs
+
+
+def deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps, model_parameters):
+ """
+ A convenience wrapper that deals with optimizer and lr scheduler configuration.
+ """
+ from accelerate.utils import DummyOptim, DummyScheduler
+
+ config = hf_deepspeed_config.config
+
+ # Mixing and matching DS schedulers and optimizers is supported unless Offload is enabled in which case it's:
+ # 1. DS scheduler + DS optimizer: Yes
+ # 2. HF scheduler + HF optimizer: Mostly*
+ # 3. DS scheduler + HF optimizer: Mostly*
+ # 4. HF scheduler + DS optimizer: Yes
+ #
+ # Mostly*: All non-native DeepSpeed optimizers that have both CPU and GPU implementation should work (except LAMB)
+
+ optimizer = None
+ if "optimizer" in config:
+ if args.adafactor:
+ raise ValueError(
+ "--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. "
+ "Only one optimizer can be configured."
+ )
+ optimizer = DummyOptim(params=model_parameters)
+ else:
+ if hf_deepspeed_config.is_offload():
+ logger.info(
+ "Detected ZeRO Offload and non-DeepSpeed optimizers: This combination should work as long as the"
+ " custom optimizer has both CPU and GPU implementation (except LAMB)"
+ )
+
+ # ds supports Adam, OneBitAdam, and Lamb optimizers and can import other optimizers from torch.
+ # But trainer uses AdamW by default.
+ optimizer = trainer.create_optimizer()
+ # To use other optimizers requires voiding warranty with: `zero_allow_untested_optimizer`
+ config["zero_allow_untested_optimizer"] = True
+
+ lr_scheduler = None
+ if "scheduler" in config:
+ lr_scheduler = DummyScheduler(optimizer)
+ else:
+ if isinstance(optimizer, DummyOptim):
+
+ def _lr_scheduler_callable(optimizer):
+ # create a shallow copy first, so later modifications do not affect original trainer
+ trainer_copy = copy.copy(trainer)
+ # at the time _lr_scheduler_callable is called, trainer.lr_scheduler has been set
+ # update it to None so that we can re-create a new scheduler
+ trainer_copy.lr_scheduler = None
+ lr_scheduler = trainer_copy.create_scheduler(
+ num_training_steps=num_training_steps, optimizer=optimizer
+ )
+ return lr_scheduler
+
+ lr_scheduler = DummyScheduler(optimizer, lr_scheduler_callable=_lr_scheduler_callable)
+ else:
+ lr_scheduler = trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer)
+
+ return optimizer, lr_scheduler
+
+
+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: Trainer object
+ num_training_steps: per single gpu
+ resume_from_checkpoint: path to a checkpoint if to resume from after normal DeepSpeedEngine load
+ inference: launch in inference mode (no optimizer and no lr scheduler)
+ auto_find_batch_size: whether to ignore the `train_micro_batch_size_per_gpu` argument as it's being
+ set automatically by the auto batch size finder
+
+ Returns: optimizer, lr_scheduler
+
+ We may use `deepspeed_init` more than once during the life of Trainer, when we do - it's a temp hack based on:
+ https://github.com/deepspeedai/DeepSpeed/issues/1394#issuecomment-937405374 until Deepspeed fixes a bug where it
+ can't resume from a checkpoint after it did some stepping https://github.com/deepspeedai/DeepSpeed/issues/1612
+
+ """
+ from deepspeed.utils import logger as ds_logger
+
+ model = trainer.model
+ args = trainer.args
+
+ hf_deepspeed_config = trainer.accelerator.state.deepspeed_plugin.hf_ds_config
+
+ # resume config update - some bits like `model` and `num_training_steps` only become available during train
+ hf_deepspeed_config.trainer_config_finalize(args, model, num_training_steps)
+
+ # set the Deepspeed log level consistent with the Trainer
+ ds_logger.setLevel(args.get_process_log_level())
+
+ if inference:
+ # only Z3 makes sense for the inference
+ if not hf_deepspeed_config.is_zero3():
+ raise ValueError("ZeRO inference only makes sense with ZeRO Stage 3 - please adjust your config")
+
+ # in case the training config is re-used for inference
+ hf_deepspeed_config.del_config_sub_tree("optimizer")
+ hf_deepspeed_config.del_config_sub_tree("lr_scheduler")
+ optimizer, lr_scheduler = None, None
+ model_parameters = None
+ else:
+ trainer.optimizer = None # important for when deepspeed_init is used as re-init
+ model_parameters = list(filter(lambda p: p.requires_grad, model.parameters()))
+ optimizer, lr_scheduler = deepspeed_optim_sched(
+ trainer, hf_deepspeed_config, args, num_training_steps, model_parameters
+ )
+
+ # keep for quick debug:
+ # from pprint import pprint; pprint(config)
+
+ return optimizer, lr_scheduler
+
+
+def deepspeed_load_checkpoint(deepspeed_engine, checkpoint_path, load_module_strict=True):
+ # it's possible that the user is trying to resume from model_path, which doesn't necessarily
+ # contain a deepspeed checkpoint. e.g. examples just check if the dir exists and assume it's
+ # a resume from a checkpoint and not just a local pretrained weight. So we check here if the
+ # path contains what looks like a deepspeed checkpoint
+ import glob
+
+ deepspeed_checkpoint_dirs = sorted(glob.glob(f"{checkpoint_path}/global_step*"))
+
+ if len(deepspeed_checkpoint_dirs) > 0:
+ logger.info(f"Attempting to resume from {checkpoint_path}")
+ # this magically updates self.optimizer and self.lr_scheduler
+ load_path, _ = deepspeed_engine.load_checkpoint(
+ checkpoint_path,
+ load_module_strict=load_module_strict,
+ load_optimizer_states=True,
+ load_lr_scheduler_states=True,
+ )
+ if load_path is None:
+ raise ValueError(f"[deepspeed] failed to resume from checkpoint {checkpoint_path}")
+ else:
+ raise ValueError(f"Can't find a valid checkpoint at {checkpoint_path}")
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/eetq.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/eetq.py
new file mode 100644
index 0000000000000000000000000000000000000000..97698cf1aa37c6279d4f6932ef496ed708e324a7
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/eetq.py
@@ -0,0 +1,121 @@
+# coding=utf-8
+# Copyright 2024 NetEase, Inc. and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from ..utils import is_accelerate_available, is_eetq_available, logging
+
+
+if is_eetq_available():
+ import eetq
+ import torch.nn as nn
+
+if is_accelerate_available():
+ from accelerate import init_empty_weights
+
+logger = logging.get_logger(__name__)
+
+
+def _replace_with_eetq_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+ pre_quantized=False,
+):
+ """
+ Private method that wraps the recursion for module replacement.
+
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+ """
+ if current_key_name is None:
+ current_key_name = []
+
+ for name, module in model.named_children():
+ current_key_name.append(name)
+
+ if (isinstance(module, nn.Linear)) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+ if not any(
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
+ ):
+ with init_empty_weights():
+ in_features = module.in_features
+ out_features = module.out_features
+ model._modules[name] = eetq.EetqLinear(
+ in_features, out_features, module.bias is not None, module.weight.device
+ )
+ if pre_quantized:
+ model._modules[name].register_scale(module.weight.device)
+ has_been_replaced = True
+
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _replace_with_eetq_linear(
+ module,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ has_been_replaced=has_been_replaced,
+ pre_quantized=pre_quantized,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+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 performance int8 weight-only gemm kerner from
+ FasterTransformer and TensorRT-LLM. Make sure `eetq` compiled with the correct CUDA
+ version of your hardware is installed before running this function. EETQ shall be installed via the source
+ 'https://github.com/NetEase-FuXi/EETQ'
+
+ 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 manager so no
+ CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model or `torch.nn.Module` as the function is run recursively.
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
+ Names of the modules to not convert in `EetqLinear`. In practice we keep the `lm_head` in full precision
+ for numerical stability reasons.
+ current_key_name (`List[`str`]`, *optional*):
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
+ it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
+ `disk`).
+ """
+
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
+
+ if quantization_config.modules_to_not_convert is not None:
+ modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
+ modules_to_not_convert = list(set(modules_to_not_convert))
+ model, has_been_replaced = _replace_with_eetq_linear(
+ model, modules_to_not_convert, current_key_name, quantization_config, pre_quantized=pre_quantized
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model using eetq but no linear modules were found in your model."
+ " Please double check your model architecture, or submit an issue on github if you think this is"
+ " a bug."
+ )
+
+ return model
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/executorch.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/executorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ee525ddf8e182b3b1a80020fee09f5862208269
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/executorch.py
@@ -0,0 +1,218 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations under the License.
+
+import torch
+
+from ..utils.import_utils import is_torch_available
+
+
+if is_torch_available():
+ from transformers import PreTrainedModel, StaticCache
+ from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_3
+
+
+class TorchExportableModuleWithStaticCache(torch.nn.Module):
+ """
+ A wrapper module designed to make a `PreTrainedModel` exportable with `torch.export`,
+ specifically for use with static caching. This module ensures that the exported model
+ is compatible with further lowering and execution in `ExecuTorch`.
+
+ Note:
+ This class is specifically designed to support export process using `torch.export`
+ in a way that ensures the model can be further lowered and run efficiently in `ExecuTorch`.
+ """
+
+ 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:
+ AssertionError: If the pretrained model does not have caching enabled or if it does
+ not use a 'static' caching implementation in `model.generation_config`.
+ """
+ super().__init__()
+
+ # Sanity checks
+ if model.generation_config is None:
+ raise AssertionError(
+ "The model must have a generation config to be exported with static caching. "
+ "Please set `generation_config`."
+ )
+
+ if not model.generation_config.use_cache:
+ raise AssertionError(
+ "The model must have caching enabled to be exported with static caching. "
+ "Please set `generation_config.use_cache=True`."
+ )
+
+ if model.generation_config.cache_implementation != "static":
+ raise AssertionError(
+ "The model must use a 'static' caching implementation to be exported with static caching. "
+ "Please set `generation_config.cache_implementation='static'`."
+ )
+
+ self.model = model
+ self.static_cache = StaticCache(
+ config=self.model.config,
+ batch_size=self.model.generation_config.cache_config.batch_size,
+ max_cache_len=self.model.generation_config.cache_config.max_cache_len,
+ device=self.model.generation_config.cache_config.device,
+ dtype=self.model.dtype,
+ )
+ for i in range(len(self.static_cache.key_cache)):
+ self.register_buffer(f"key_cache_{i}", self.static_cache.key_cache[i], persistent=False)
+ self.register_buffer(f"value_cache_{i}", self.static_cache.value_cache[i], persistent=False)
+
+ self.is_causal = any("CausalLM" in arch for arch in self.model.config.architectures)
+ if self.is_causal:
+ causal_mask = torch.tril(
+ torch.ones(
+ self.static_cache.max_cache_len,
+ self.static_cache.max_cache_len,
+ dtype=torch.bool,
+ )
+ )
+ self.register_buffer("mask", causal_mask, persistent=False)
+
+ 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.Tensor`): Tensor representing current input position in the cache.
+
+ Returns:
+ torch.Tensor: Logits output from the model.
+
+ This forward adapter serves two primary purposes:
+
+ 1. **Making the Model `torch.export`-Compatible**:
+ The adapter hides unsupported objects, such as the `Cache`, from the graph inputs and outputs,
+ enabling the model to be exportable using `torch.export` without encountering issues.
+
+ 2. **Ensuring Compatibility with `ExecuTorch` runtime**:
+ The adapter matches the model's forward signature with that in `executorch/extension/llm/runner`,
+ ensuring that the exported model can be executed in `ExecuTorch` out-of-the-box.
+ """
+ _, seqlen = input_ids.shape
+ attn_mask = self.mask[cache_position, :seqlen] if self.is_causal else None
+ position_ids = cache_position.unsqueeze(0)
+ past_key_values = self.static_cache
+
+ outs = self.model(
+ input_ids=input_ids,
+ attention_mask=attn_mask,
+ position_ids=position_ids,
+ cache_position=cache_position,
+ past_key_values=past_key_values,
+ use_cache=True,
+ )
+ return outs.logits
+
+ @staticmethod
+ def generate(
+ exported_program: torch.export.ExportedProgram, prompt_token_ids: torch.Tensor, max_new_tokens: int
+ ) -> torch.Tensor:
+ """
+ Generate a sequence of tokens using an exported program.
+
+ This util function is designed to test exported models by simulating the generation process.
+ It processes the input prompt tokens sequentially (no parallel prefill).
+ This generate function is not intended to replace the original `generate` method, and the support
+ for leveraging the original `generate` is potentially planed!
+
+ Args:
+ exported_program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
+ prompt_token_ids (`torch.Tensor`): Tensor representing the input prompt token IDs.
+ max_new_tokens (`int`): Maximum number of new tokens to generate. Note that the total generation
+ length is limited by both `max_new_tokens` and the model's cache size.
+
+ Returns:
+ torch.Tensor: A tensor containing the generated sequence of token IDs, including the original prompt tokens.
+ """
+ prompt_token_len = prompt_token_ids.shape[-1]
+ max_generation_length = prompt_token_len + max_new_tokens
+ for buffer_name, buffer in exported_program.named_buffers():
+ if buffer_name.startswith("key_cache"):
+ max_cache_len = buffer.shape[2]
+ max_generation_length = min(max_generation_length, max_cache_len)
+ break
+
+ response_tokens = []
+ for input_pos in range(min(max_generation_length, prompt_token_len)):
+ result = exported_program.module().forward(
+ input_ids=prompt_token_ids[:, input_pos : input_pos + 1],
+ cache_position=torch.tensor([input_pos], dtype=torch.long),
+ )
+ response_tokens.append(prompt_token_ids[0][input_pos].item())
+
+ current_token = torch.argmax(result[:, -1, :], dim=-1).item()
+ response_tokens.append(current_token)
+
+ while len(response_tokens) < max_generation_length:
+ result = exported_program.module().forward(
+ input_ids=torch.tensor([[current_token]], dtype=torch.long),
+ cache_position=torch.tensor([len(response_tokens)], dtype=torch.long),
+ )
+ current_token = torch.argmax(result[:, -1, :], dim=-1).item()
+ response_tokens.append(current_token)
+
+ return torch.tensor([response_tokens], dtype=torch.long)
+
+
+def convert_and_export_with_cache(
+ model: PreTrainedModel,
+ example_input_ids: torch.Tensor = None,
+ example_cache_position: torch.Tensor = None,
+):
+ """
+ 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 (`torch.Tensor`): Example input token id used by `torch.export`.
+ example_cache_position (`torch.Tensor`): Example current cache position used by `torch.export`.
+
+ Returns:
+ Exported program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
+ """
+
+ if not is_torch_greater_or_equal_than_2_3:
+ raise ImportError("torch >= 2.3 is required.")
+
+ import torch.export._trace
+
+ with torch.no_grad():
+ # TODO: The default inputs only work for text models. We need to add support for vision/audio models.
+ example_input_ids = (
+ example_input_ids if example_input_ids is not None else torch.tensor([[1]], dtype=torch.long)
+ )
+ example_cache_position = (
+ example_cache_position if example_cache_position is not None else torch.tensor([0], dtype=torch.long)
+ )
+
+ # Due to issue https://github.com/pytorch/pytorch/issues/128394, we need to switch to use an internal
+ # export API and pre_dispatch=False. Switch to use the public API once the issue is included in 2.5 release.
+ exported_program = torch.export._trace._export(
+ TorchExportableModuleWithStaticCache(model),
+ args=(example_input_ids,),
+ kwargs={"cache_position": example_cache_position},
+ pre_dispatch=False,
+ strict=True,
+ )
+ return exported_program
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/fbgemm_fp8.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/fbgemm_fp8.py
new file mode 100644
index 0000000000000000000000000000000000000000..71c2b570cc0a7381c66a3b7797a4f72f442d0b6a
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/fbgemm_fp8.py
@@ -0,0 +1,164 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from ..utils import is_accelerate_available, is_fbgemm_gpu_available, is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+if is_accelerate_available():
+ from accelerate import init_empty_weights
+
+if is_fbgemm_gpu_available():
+ import fbgemm_gpu.experimental.gen_ai # noqa: F401
+
+logger = logging.get_logger(__name__)
+
+
+class FbgemmFp8Linear(torch.nn.Module):
+ def __init__(self, in_features, out_features, bias, weight_dtype=torch.float32):
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+
+ self.register_buffer("weight", torch.zeros((out_features, in_features), dtype=torch.float8_e4m3fn))
+ self.register_buffer("weight_scale", torch.zeros((out_features, 1), dtype=weight_dtype))
+ self.register_buffer("input_scale_ub", torch.zeros([1], dtype=torch.float), persistent=False)
+
+ if bias:
+ self.register_buffer("bias", torch.zeros((self.out_features), dtype=weight_dtype))
+ else:
+ self.bias = None
+
+ def forward(self, x):
+ num_tokens = None
+ # quantize_fp8_per_row will squash the leading dimensions, so save the desired shape here
+ output_shape = (*x.shape[:-1], -1)
+ # x_quantized and x_scale are not necessarily on the same device as x, this is an issue.
+ # https://github.com/pytorch/FBGEMM/blob/e08af8539c391437f447173863df0f3f6f6f1855/fbgemm_gpu/experimental/gen_ai/src/quantize/quantize.cu#L1237C3-L1237C45
+ x_quantized, x_scale = torch.ops.fbgemm.quantize_fp8_per_row(
+ x.view(-1, x.shape[-1]), num_tokens, self.input_scale_ub
+ )
+ # moving x_quantized, x_scale here creates glibberish output ... However, if we move the output, it works
+ # x_quantized, x_scale = x_quantized.to(x.device), x_scale.to(x.device)
+
+ # The computation still happens on the device where self.weight is even if x_quantized is not on the same device as self.weight
+ output = torch.ops.fbgemm.f8f8bf16_rowwise(
+ x_quantized, self.weight, x_scale, self.weight_scale, use_fast_accum=True
+ )
+ output = output + self.bias if self.bias is not None else output
+ # Hacky for now, we have the output to the device of x
+ output = output.to(x.device)
+ output = output.reshape(output_shape)
+ del x_quantized, x_scale
+ return output
+
+
+def _replace_with_fbgemm_fp8_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+ pre_quantized=False,
+):
+ """
+ Private method that wraps the recursion for module replacement.
+
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+ """
+ if current_key_name is None:
+ current_key_name = []
+
+ for name, module in model.named_children():
+ current_key_name.append(name)
+
+ if (isinstance(module, nn.Linear)) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+ if not any(
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
+ ):
+ with init_empty_weights(include_buffers=True):
+ in_features = module.in_features
+ out_features = module.out_features
+ model._modules[name] = FbgemmFp8Linear(
+ in_features,
+ out_features,
+ module.bias is not None,
+ )
+ has_been_replaced = True
+
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ # set non persistant buffer outside of init_empty_weights
+ model._modules[name].input_scale_ub = torch.tensor(
+ [quantization_config.activation_scale_ub], dtype=torch.float
+ )
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _replace_with_fbgemm_fp8_linear(
+ module,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ has_been_replaced=has_been_replaced,
+ pre_quantized=pre_quantized,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+def replace_with_fbgemm_fp8_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 `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 kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
+ CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model or `torch.nn.Module` as the function is run recursively.
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
+ Names of the modules to not convert in `FP8Linear`. In practice we keep the `lm_head` in full precision
+ for numerical stability reasons.
+ current_key_name (`List[`str`]`, *optional*):
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
+ it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
+ `disk`).
+ """
+
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
+
+ if quantization_config.modules_to_not_convert is not None:
+ modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
+ modules_to_not_convert = list(set(modules_to_not_convert))
+ model, has_been_replaced = _replace_with_fbgemm_fp8_linear(
+ model, modules_to_not_convert, current_key_name, quantization_config, pre_quantized=pre_quantized
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model using FP8 quantization but no linear modules were found in your model."
+ " Please double check your model architecture, or submit an issue on github if you think this is"
+ " a bug."
+ )
+
+ return model
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/finegrained_fp8.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/finegrained_fp8.py
new file mode 100644
index 0000000000000000000000000000000000000000..0815df43445306b6b4aefd2c2d9a4ea35169a044
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/finegrained_fp8.py
@@ -0,0 +1,420 @@
+# coding=utf-8
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import List, Optional, Tuple
+
+from ..utils import is_accelerate_available, is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+ import torch.nn as nn
+ import triton
+ import triton.language as tl
+ from torch.nn import functional as F
+
+if is_accelerate_available():
+ from accelerate import init_empty_weights
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/inference/kernel.py
+@triton.jit
+def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr):
+ pid = tl.program_id(axis=0)
+ offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
+ x = tl.load(x_ptr + offs).to(tl.float32)
+ s = tl.max(tl.abs(x)) / 448.0
+ y = x / s
+ y = y.to(y_ptr.dtype.element_ty)
+ tl.store(y_ptr + offs, y)
+ tl.store(s_ptr + pid, s)
+
+
+def act_quant(x: torch.Tensor, block_size: int = 128) -> Tuple[torch.Tensor, torch.Tensor]:
+ assert x.is_contiguous()
+ assert x.shape[-1] % block_size == 0
+ y = torch.empty_like(x, dtype=torch.float8_e4m3fn)
+ s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
+
+ def grid(meta):
+ return (triton.cdiv(x.numel(), meta["BLOCK_SIZE"]),)
+
+ act_quant_kernel[grid](x, y, s, BLOCK_SIZE=block_size)
+ return y, s
+
+
+# Adapted from https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/quantization/fp8_kernel.py
+@triton.jit
+def _w8a8_block_fp8_matmul(
+ # Pointers to inputs and output
+ A,
+ B,
+ C,
+ As,
+ Bs,
+ # Shape for matmul
+ M,
+ N,
+ K,
+ # Block size for block-wise quantization
+ group_n,
+ group_k,
+ # Stride for inputs and output
+ stride_am,
+ stride_ak,
+ stride_bk,
+ stride_bn,
+ stride_cm,
+ stride_cn,
+ stride_As_m,
+ stride_As_k,
+ stride_Bs_k,
+ stride_Bs_n,
+ # Meta-parameters
+ BLOCK_SIZE_M: tl.constexpr,
+ BLOCK_SIZE_N: tl.constexpr,
+ BLOCK_SIZE_K: tl.constexpr,
+ GROUP_SIZE_M: tl.constexpr,
+):
+ """Triton-accelerated function used to perform linear operations (dot
+ product) on input tensors `A` and `B` with block-wise quantization, and
+ store the result in output tensor `C`.
+ """
+
+ pid = tl.program_id(axis=0)
+ num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
+ num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
+ num_pid_in_group = GROUP_SIZE_M * num_pid_n
+ group_id = pid // num_pid_in_group
+ first_pid_m = group_id * GROUP_SIZE_M
+ group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
+ pid_m = first_pid_m + (pid % group_size_m)
+ pid_n = (pid % num_pid_in_group) // group_size_m
+
+ offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
+ offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
+ offs_k = tl.arange(0, BLOCK_SIZE_K)
+ a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)
+ b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
+
+ As_ptrs = As + offs_am * stride_As_m
+ offs_bsn = offs_bn // group_n
+ Bs_ptrs = Bs + offs_bsn * stride_Bs_n
+
+ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
+ for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
+ a = tl.load(a_ptrs, mask=offs_k[None, :] < K - k * BLOCK_SIZE_K, other=0.0)
+ b = tl.load(b_ptrs, mask=offs_k[:, None] < K - k * BLOCK_SIZE_K, other=0.0)
+
+ k_start = k * BLOCK_SIZE_K
+ offs_ks = k_start // group_k
+ a_s = tl.load(As_ptrs + offs_ks * stride_As_k)
+ b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k)
+
+ accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
+ a_ptrs += BLOCK_SIZE_K * stride_ak
+ b_ptrs += BLOCK_SIZE_K * stride_bk
+
+ if C.dtype.element_ty == tl.bfloat16:
+ c = accumulator.to(tl.bfloat16)
+ elif C.dtype.element_ty == tl.float16:
+ c = accumulator.to(tl.float16)
+ else:
+ c = accumulator.to(tl.float32)
+
+ offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
+ offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
+ c_ptrs = C + stride_cm * offs_cm[:, None] + stride_cn * offs_cn[None, :]
+ c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < N)
+ tl.store(c_ptrs, c, mask=c_mask)
+
+
+def w8a8_block_fp8_matmul_triton(
+ A: torch.Tensor,
+ B: torch.Tensor,
+ As: torch.Tensor,
+ Bs: torch.Tensor,
+ block_size: List[int],
+ output_dtype: torch.dtype = torch.float32,
+) -> torch.Tensor:
+ """This function performs matrix multiplication with block-wise
+ quantization.
+ It takes two input tensors `A` and `B` with scales `As` and `Bs`.
+ The output is returned in the specified `output_dtype`.
+ Args:
+ A: The input tensor, e.g., activation.
+ B: The input tensor, e.g., weight.
+ As: The per-token-group quantization scale for `A`.
+ Bs: The per-block quantization scale for `B`.
+ block_size: The block size for per-block quantization. It should
+ be 2-dim, e.g., [128, 128].
+ output_dytpe: The dtype of the returned tensor.
+ Returns:
+ torch.Tensor: The result of matmul.
+ """
+ assert len(block_size) == 2
+ block_n, block_k = block_size[0], block_size[1]
+
+ assert A.shape[-1] == B.shape[-1]
+ assert A.shape[:-1] == As.shape[:-1] and A.is_contiguous()
+ assert triton.cdiv(A.shape[-1], block_k) == As.shape[-1]
+ M = A.numel() // A.shape[-1]
+
+ assert B.ndim == 2 and B.is_contiguous() and Bs.ndim == 2
+ N, K = B.shape
+ assert triton.cdiv(N, block_n) == Bs.shape[0]
+ assert triton.cdiv(K, block_k) == Bs.shape[1]
+
+ C_shape = A.shape[:-1] + (N,)
+ C = A.new_empty(C_shape, dtype=output_dtype)
+
+ BLOCK_SIZE_M = 128
+ if M < BLOCK_SIZE_M:
+ BLOCK_SIZE_M = triton.next_power_of_2(M)
+ BLOCK_SIZE_M = max(BLOCK_SIZE_M, 16)
+ BLOCK_SIZE_K = block_k
+ assert block_k % BLOCK_SIZE_K == 0
+ BLOCK_SIZE_N = block_n
+
+ def grid(META):
+ return (triton.cdiv(M, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]),)
+
+ _w8a8_block_fp8_matmul[grid](
+ A,
+ B,
+ C,
+ As,
+ Bs,
+ M,
+ N,
+ K,
+ block_n,
+ block_k,
+ A.stride(-2),
+ A.stride(-1),
+ B.stride(1),
+ B.stride(0),
+ C.stride(-2),
+ C.stride(-1),
+ As.stride(-2),
+ As.stride(-1),
+ Bs.stride(1),
+ Bs.stride(0),
+ BLOCK_SIZE_M=BLOCK_SIZE_M,
+ BLOCK_SIZE_N=BLOCK_SIZE_N,
+ BLOCK_SIZE_K=BLOCK_SIZE_K,
+ GROUP_SIZE_M=8,
+ )
+
+ return C
+
+
+# Python version of the above triton function, it's much slower than the triton version, for testing
+@torch.compile
+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: Optional[Tuple[int, int]] = None, # (M=128, N=128) for weights for example
+ output_dtype: torch.dtype = torch.float32,
+) -> torch.Tensor:
+ """
+ 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 for weight blocks
+ block_size: Tuple of (M, N) for weight block dimensions
+ output_dtype: Desired output dtype
+ """
+ batch_size, seq_len, hidden_dim = input_q.shape if input_q.ndim == 3 else (1, input_q.shape[0], input_q.shape[1])
+ out_features = weight_q.shape[0]
+
+ # Reshape input for batched matmul
+ input_reshaped = input_q.view(-1, hidden_dim) # [batch*seq_len, hidden_dim]
+ input_scale_reshaped = input_scale.view(input_scale.shape[0], -1) # [batch*seq_len, 1]
+ # Calculate number of blocks
+ num_weight_blocks_m = out_features // block_size[0]
+ num_weight_blocks_n = hidden_dim // block_size[1]
+
+ output = torch.zeros((batch_size * seq_len, out_features), dtype=torch.float32, device=input_q.device)
+
+ for i in range(num_weight_blocks_m):
+ m_start = i * block_size[0]
+ m_end = m_start + block_size[0]
+
+ for j in range(num_weight_blocks_n):
+ n_start = j * block_size[1]
+ n_end = n_start + block_size[1]
+
+ # Extract current blocks
+ input_block = input_reshaped[:, n_start:n_end]
+ weight_block = weight_q[m_start:m_end, n_start:n_end]
+
+ # Get corresponding scales
+ curr_input_scale = input_scale_reshaped[:, j : j + 1] # [batch*seq_len, 1]
+ curr_weight_scale = weight_scale[i, j] # scalar
+
+ block_result = (
+ torch._scaled_mm(
+ input_block,
+ weight_block.t(),
+ scale_a=torch.tensor(1, dtype=torch.float32, device=input_q.device),
+ scale_b=curr_weight_scale,
+ out_dtype=output_dtype,
+ )
+ * curr_input_scale
+ )
+
+ output[:, m_start:m_end] += block_result
+
+ output = output.view(batch_size, seq_len, out_features)
+
+ return output.to(output_dtype)
+
+
+class FP8Linear(nn.Module):
+ dtype = torch.float8_e4m3fn
+
+ def __init__(
+ self,
+ in_features: int,
+ out_features: int,
+ bias: bool = False,
+ dtype=None,
+ block_size: Optional[Tuple[int, int]] = None,
+ device=None,
+ activation_scheme="dynamic",
+ ):
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+
+ self.register_buffer("weight", torch.empty(out_features, in_features, dtype=FP8Linear.dtype, device=device))
+
+ scale_out_features = (out_features + block_size[0] - 1) // block_size[0]
+ scale_in_features = (in_features + block_size[1] - 1) // block_size[1]
+ self.register_buffer(
+ "weight_scale_inv", torch.empty(scale_out_features, scale_in_features, dtype=torch.float32, device=device)
+ )
+
+ self.block_size = block_size
+
+ self.activation_scheme = activation_scheme
+
+ if bias:
+ self.bias = nn.Parameter(torch.empty(self.out_features))
+ else:
+ self.register_parameter("bias", None)
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ if self.weight.element_size() > 1:
+ return F.linear(input, self.weight, self.bias)
+ else:
+ # Context manager used to switch among the available cuda devices
+ with torch.cuda.device(input.device):
+ qinput, scale = act_quant(input, self.block_size[1])
+ # Blocks the CPU until all CUDA operations on the specified device are complete. It is used to ensure that the results of the
+ # preceding operations are ready before proceeding
+ torch.cuda.synchronize(device=input.device)
+ with torch.cuda.device(input.device):
+ output = w8a8_block_fp8_matmul_triton(
+ qinput,
+ self.weight,
+ scale,
+ self.weight_scale_inv,
+ self.block_size,
+ output_dtype=input.dtype,
+ )
+ torch.cuda.synchronize(device=input.device)
+ if self.bias is not None:
+ output = output + self.bias
+ return output.to(dtype=input.dtype)
+
+
+def _replace_with_fp8_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+):
+ """Replace Linear layers with FP8Linear."""
+ if current_key_name is None:
+ current_key_name = []
+
+ for name, module in model.named_children():
+ current_key_name.append(name)
+
+ if isinstance(module, nn.Linear) and name not in (modules_to_not_convert or []):
+ current_key_name_str = ".".join(current_key_name)
+ if not any(key in current_key_name_str for key in (modules_to_not_convert or [])):
+ with init_empty_weights():
+ model._modules[name] = FP8Linear(
+ in_features=module.in_features,
+ out_features=module.out_features,
+ bias=module.bias is not None,
+ device=module.weight.device,
+ dtype=module.weight.dtype,
+ activation_scheme=quantization_config.activation_scheme,
+ block_size=quantization_config.weight_block_size,
+ )
+ has_been_replaced = True
+
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _replace_with_fp8_linear(
+ module,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ has_been_replaced=has_been_replaced,
+ )
+
+ current_key_name.pop(-1)
+
+ return model, has_been_replaced
+
+
+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_convert is not None:
+ modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
+ modules_to_not_convert = list(set(modules_to_not_convert))
+
+ model, has_been_replaced = _replace_with_fp8_linear(
+ model,
+ modules_to_not_convert=modules_to_not_convert,
+ quantization_config=quantization_config,
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model using fp8 but no linear modules were found in your model."
+ " Please double check your model architecture."
+ )
+
+ return model
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/flash_attention.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/flash_attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3ca4bea484d22176f49dd74d93666ce7c7e2e40
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/flash_attention.py
@@ -0,0 +1,66 @@
+from typing import Optional, Tuple
+
+import torch
+
+from ..modeling_flash_attention_utils import _flash_attention_forward
+from ..utils import is_flash_attn_greater_or_equal_2_10
+
+
+_use_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
+
+
+def flash_attention_forward(
+ module: torch.nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ dropout: float = 0.0,
+ scaling: Optional[float] = None,
+ sliding_window: Optional[int] = None,
+ softcap: Optional[float] = None,
+ **kwargs,
+) -> Tuple[torch.Tensor, None]:
+ # This is before the transpose
+ seq_len = query.shape[2]
+
+ # FA2 uses non-transposed inputs
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
+ # cast them back in the correct dtype just to be sure everything works as expected.
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
+ # in fp32. (usually our RMSNorm modules handle it correctly)
+ target_dtype = None
+ if query.dtype == torch.float32:
+ if torch.is_autocast_enabled():
+ target_dtype = torch.get_autocast_gpu_dtype()
+ # Handle the case where the model is quantized
+ elif hasattr(module.config, "_pre_quantization_dtype"):
+ target_dtype = module.config._pre_quantization_dtype
+ else:
+ target_dtype = next(layer for layer in module.modules() if isinstance(layer, torch.nn.Linear)).weight.dtype
+
+ # FA2 always relies on the value set in the module, so remove it if present in kwargs to avoid passing it twice
+ kwargs.pop("is_causal", None)
+
+ attn_output = _flash_attention_forward(
+ query,
+ key,
+ value,
+ attention_mask,
+ query_length=seq_len,
+ is_causal=module.is_causal,
+ dropout=dropout,
+ softmax_scale=scaling,
+ sliding_window=sliding_window,
+ softcap=softcap,
+ use_top_left_mask=_use_top_left_mask,
+ target_dtype=target_dtype,
+ **kwargs,
+ )
+
+ return attn_output, None
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/flex_attention.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/flex_attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..5181b2c1a0ad256afefda7ac98c8c6be5f1d2c38
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/flex_attention.py
@@ -0,0 +1,51 @@
+from typing import Optional, Tuple
+
+import torch
+
+from ..utils import is_torch_flex_attn_available
+
+
+if is_torch_flex_attn_available():
+ from torch.nn.attention.flex_attention import flex_attention
+
+
+def flex_attention_forward(
+ module: torch.nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ scaling: Optional[float] = None,
+ softcap: Optional[float] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ **kwargs,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ causal_mask = attention_mask
+ if causal_mask is not None:
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
+
+ def causal_mod(score, b, h, q_idx, kv_idx):
+ if softcap is not None:
+ score = softcap * torch.tanh(score / softcap)
+ if causal_mask is not None:
+ score = score + causal_mask[b][0][q_idx][kv_idx]
+ if head_mask is not None:
+ score = score + head_mask[b][h][0][0]
+ return score
+
+ attn_output, attention_weights = flex_attention(
+ query,
+ key,
+ value,
+ score_mod=causal_mod,
+ enable_gqa=True,
+ scale=scaling,
+ # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.
+ # For simplification, we thus always return it as no additional computations are introduced.
+ return_lse=True,
+ )
+ # lse is returned in float32
+ attention_weights = attention_weights.to(value.dtype)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attention_weights
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/fsdp.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/fsdp.py
new file mode 100644
index 0000000000000000000000000000000000000000..332231c04f433f4ebd1364347c5cbce62dd498e6
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/fsdp.py
@@ -0,0 +1,38 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from ..utils import is_torch_available
+
+
+if TYPE_CHECKING:
+ from torch import nn
+
+
+def is_fsdp_managed_module(module: nn.Module) -> bool:
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if not torch.distributed.is_available():
+ return False
+
+ import torch.distributed.fsdp
+
+ return isinstance(module, torch.distributed.fsdp.FullyShardedDataParallel) or getattr(
+ module, "_is_fsdp_managed_module", False
+ )
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/ggml.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/ggml.py
new file mode 100644
index 0000000000000000000000000000000000000000..db7d93cad0427acd2c12683edd177bf28c1ceb07
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/ggml.py
@@ -0,0 +1,692 @@
+# coding=utf-8
+# Copyright 2024 The ggml.ai team and The HuggingFace Inc. team. and pygguf author (github.com/99991)
+# https://github.com/99991/pygguf
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Integration with GGML / The file is copied and adapted from https://github.com/99991/pygguf
+with extra methods beings exposed
+"""
+
+from array import array
+
+import numpy as np
+from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
+from tokenizers.models import BPE, Unigram
+
+from .. import AddedToken
+from ..convert_slow_tokenizer import GemmaConverter, GPT2Converter, LlamaConverter, Qwen2Converter, T5Converter
+from ..utils import logging
+from ..utils.logging import tqdm
+
+
+logger = logging.get_logger(__name__)
+
+
+GGUF_CONFIG_MAPPING = {
+ "general": {
+ "architecture": "model_type",
+ "name": "_model_name_or_path",
+ },
+ "llama": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ # NOTE: rope.dimension_count==head_dim only suitable for llama/mistral
+ "rope.dimension_count": "head_dim",
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "mistral": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ # NOTE: rope.dimension_count==head_dim only suitable for llama/mistral
+ "rope.dimension_count": "head_dim",
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "qwen2": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "qwen2moe": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ "expert_count": "num_experts",
+ "expert_used_count": "num_experts_per_tok",
+ },
+ "falcon": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "tokenizer": {
+ "ggml.bos_token_id": "bos_token_id",
+ "ggml.eos_token_id": "eos_token_id",
+ "ggml.unknown_token_id": "unk_token_id",
+ "ggml.padding_token_id": "pad_token_id",
+ },
+ "phi3": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "bloom": {
+ "block_count": "n_layer",
+ "embedding_length": "hidden_size",
+ "attention.head_count": "n_head",
+ "vocab_size": "vocab_size",
+ "attention.layer_norm_epsilon": "layer_norm_epsilon",
+ },
+ "t5": {
+ "context_length": "n_positions",
+ "block_count": "num_layers",
+ "feed_forward_length": "d_ff",
+ "embedding_length": "d_model",
+ "attention.key_length": "d_kv",
+ "attention.head_count": "num_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_epsilon": "layer_norm_epsilon",
+ "attention.relative_buckets_count": "relative_attention_num_buckets",
+ "decoder_start_token_id": "decoder_start_token_id",
+ "vocab_size": "vocab_size",
+ },
+ "stablelm": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_epsilon": "layer_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "gpt2": {
+ "block_count": "n_layer",
+ "context_length": "n_ctx",
+ "embedding_length": "n_embd",
+ "feed_forward_length": "feed_forward_length",
+ "attention.head_count": "n_head",
+ "attention.layer_norm_epsilon": "layer_norm_epsilon",
+ },
+ "starcoder2": {
+ "block_count": "num_hidden_layers",
+ "context_length": "max_position_embeddings",
+ "embedding_length": "hidden_size",
+ "feed_forward_length": "intermediate_size",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_epsilon": "norm_epsilon",
+ },
+ "mamba": {
+ "vocab_size": "vocab_size",
+ "context_length": "max_position_embeddings",
+ "embedding_length": "hidden_size",
+ "attention.layer_norm_rms_epsilon": "layer_norm_epsilon",
+ "block_count": "num_hidden_layers",
+ "ssm.conv_kernel": "conv_kernel",
+ "ssm.state_size": "state_size",
+ "ssm.time_step_rank": "time_step_rank",
+ "ssm.inner_size": "intermediate_size",
+ },
+ "nemotron": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "gemma2": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ # NOTE: Gemma2 has key_length==value_length==head_dim
+ # See: https://github.com/ggerganov/llama.cpp/blob/2e2f8f093cd4fb6bbb87ba84f6b9684fa082f3fa/convert_hf_to_gguf.py#L3293-L3294
+ "attention.key_length": "head_dim",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+}
+
+GGUF_TOKENIZER_MAPPING = {
+ "tokenizer": {
+ "ggml.model": "tokenizer_type",
+ "ggml.tokens": "tokens",
+ "ggml.scores": "scores",
+ "ggml.token_type": "token_type",
+ "ggml.merges": "merges",
+ "ggml.bos_token_id": "bos_token_id",
+ "ggml.eos_token_id": "eos_token_id",
+ "ggml.unknown_token_id": "unk_token_id",
+ "ggml.padding_token_id": "pad_token_id",
+ "ggml.add_space_prefix": "add_prefix_space",
+ },
+ "tokenizer_config": {
+ "chat_template": "chat_template",
+ "ggml.model": "model_type",
+ "ggml.bos_token_id": "bos_token_id",
+ "ggml.eos_token_id": "eos_token_id",
+ "ggml.unknown_token_id": "unk_token_id",
+ "ggml.padding_token_id": "pad_token_id",
+ },
+}
+
+
+def _gguf_parse_value(_value, data_type):
+ if not isinstance(data_type, list):
+ data_type = [data_type]
+ if len(data_type) == 1:
+ data_type = data_type[0]
+ array_data_type = None
+ else:
+ if data_type[0] != 9:
+ raise ValueError("Received multiple types, therefore expected the first type to indicate an array.")
+ data_type, array_data_type = data_type
+
+ if data_type in [0, 1, 2, 3, 4, 5, 10, 11]:
+ _value = int(_value[0])
+ elif data_type in [6, 12]:
+ _value = float(_value[0])
+ elif data_type in [7]:
+ _value = bool(_value[0])
+ elif data_type in [8]:
+ _value = array("B", list(_value)).tobytes().decode()
+ elif data_type in [9]:
+ _value = _gguf_parse_value(_value, array_data_type)
+ return _value
+
+
+class GGUFTokenizerSkeleton:
+ def __init__(self, dict_):
+ for k, v in dict_.items():
+ setattr(self, k, v)
+
+ if not hasattr(self, "merges"):
+ if not hasattr(self, "tokens") or not hasattr(self, "scores"):
+ raise ValueError(
+ "tokens and scores need to be passed for a LLaMa tokenizer without merges to be instantiated."
+ )
+ tokens = self.tokens
+ scores = self.scores
+ vocab = {t: scores[i] for i, t in enumerate(tokens)}
+
+ logger.warning("Merges were not in checkpoint, building merges on the fly.")
+ merges = []
+ for merge, piece_score in tqdm(vocab.items()):
+ local = []
+ for index in range(1, len(merge)):
+ piece_l, piece_r = merge[:index], merge[index:]
+ if piece_l in tokens and piece_r in tokens:
+ local.append((piece_l, piece_r, piece_score))
+ local = sorted(local, key=lambda x: (vocab[x[0]], vocab[x[1]]), reverse=True)
+ merges.extend(local)
+ merges = sorted(merges, key=lambda val: val[2], reverse=True)
+ merges = [(val[0], val[1]) for val in merges]
+ self.merges = merges
+ else:
+ self.merges = [tuple(merge.split(" ")) for merge in self.merges]
+ if not hasattr(self, "scores"):
+ self.scores = [None for _ in range(len(self.tokens))]
+
+ if not hasattr(self, "added_tokens"):
+ self.added_tokens = []
+
+ if not hasattr(self, "unk_token_id"):
+ self.unk_token_id = None
+
+ # Llama2 uses the field `unknown_token_id`
+ if hasattr(self, "unknown_token_id") and self.unk_token_id is None:
+ self.unk_token_id = self.unknown_token_id
+
+
+class GGUFLlamaConverter(LlamaConverter):
+ def __init__(self, tokenizer_dict):
+ self.proto = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.original_tokenizer = self.proto
+ self.additional_kwargs = {}
+ self.is_llama_3_tokenizer = getattr(self.proto, "tokenizer_type", "llama") != "llama"
+
+ def vocab(self, proto):
+ return list(zip(proto.tokens, proto.scores))
+
+ def merges(self, proto):
+ return proto.merges
+
+ def tokenizer(self, proto):
+ vocab_scores = self.vocab(self.proto)
+ merges = self.merges(self.proto)
+ bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
+
+ unk_token = proto.tokens[proto.unk_token_id] if proto.unk_token_id is not None else None
+ bos_token = proto.tokens[proto.bos_token_id] if getattr(proto, "bos_token_id", None) is not None else None
+ eos_token = proto.tokens[proto.bos_token_id] if getattr(proto, "eos_token_id", None) is not None else None
+
+ tokenizer = Tokenizer(
+ BPE(
+ bpe_vocab,
+ merges,
+ unk_token=unk_token,
+ fuse_unk=True,
+ byte_fallback=True,
+ )
+ )
+
+ special_tokens = []
+
+ if not hasattr(self.proto, "token_type"):
+ if unk_token is not None:
+ special_tokens.append(AddedToken(unk_token, normalized=False, special=True))
+
+ if bos_token is not None:
+ special_tokens.append(AddedToken(bos_token, normalized=False, special=True))
+
+ if eos_token is not None:
+ special_tokens.append(AddedToken(eos_token, normalized=False, special=True))
+ else:
+ # 3 stands for special tokens
+ special_tokens_idx = np.where(np.array(self.proto.token_type) == 3)[0]
+
+ for idx in special_tokens_idx:
+ special_tokens.append(AddedToken(self.proto.tokens[idx], normalized=False, special=True))
+
+ if len(special_tokens) != 0:
+ tokenizer.add_special_tokens(special_tokens)
+
+ if len(self.proto.added_tokens) != 0:
+ tokenizer.add_tokens(
+ [AddedToken(added_token, normalized=False, special=False) for added_token in self.proto.added_tokens]
+ )
+
+ self.additional_kwargs["unk_token"] = unk_token
+ self.additional_kwargs["eos_token"] = bos_token
+ self.additional_kwargs["bos_token"] = eos_token
+
+ if self.is_llama_3_tokenizer:
+ self.additional_kwargs["add_prefix_space"] = None
+ self.additional_kwargs["clean_up_tokenization_spaces"] = True
+
+ self.additional_kwargs["legacy"] = False
+ self.original_tokenizer.legacy = False
+
+ return tokenizer
+
+ def decoder(self, replacement, add_prefix_space):
+ sequence = [
+ decoders.ByteFallback(),
+ decoders.Fuse(),
+ decoders.Replace("▁", " "),
+ ]
+
+ if self.is_llama_3_tokenizer:
+ sequence += [decoders.ByteLevel(add_prefix_space=False, trim_offsets=False, use_regex=True)]
+
+ if add_prefix_space:
+ sequence += [decoders.Strip(content=" ", left=1)]
+ return decoders.Sequence(sequence)
+
+ def converted(self):
+ # Copied partly from converted method in SpmConverter class
+ tokenizer = self.tokenizer(self.proto)
+
+ # Tokenizer assemble
+ normalizer = self.normalizer(self.proto)
+ if normalizer is not None:
+ tokenizer.normalizer = normalizer
+
+ replacement = "▁"
+ add_prefix_space = True
+ if hasattr(self.original_tokenizer, "add_prefix_space"):
+ add_prefix_space = self.original_tokenizer.add_prefix_space
+
+ pre_tokenizer = self.pre_tokenizer(replacement, add_prefix_space)
+ if pre_tokenizer is not None:
+ tokenizer.pre_tokenizer = pre_tokenizer
+
+ tokenizer.decoder = self.decoder(replacement, add_prefix_space)
+ post_processor = self.post_processor()
+ if post_processor:
+ tokenizer.post_processor = post_processor
+
+ # HACK: patch the llama-3 tokenizer to use the correspinding pre-tokenizer
+ # and normalizer
+ if self.is_llama_3_tokenizer:
+ tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(
+ add_prefix_space=False, trim_offsets=False, use_regex=True
+ )
+ # This is tricky as the additional kwargs are passed after legacy is force-set in LlamaTokenizer's
+ # init.
+ tokenizer.normalizer = normalizers.Sequence([])
+
+ return tokenizer
+
+
+class GGUFQwen2Converter(Qwen2Converter):
+ def __init__(self, tokenizer_dict):
+ self.original_tokenizer = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.additional_kwargs = {}
+
+ def converted(self) -> Tokenizer:
+ vocab = {word: i for i, word in enumerate(self.original_tokenizer.tokens)}
+ merges = self.original_tokenizer.merges
+ tokenizer = super().converted(vocab, merges)
+
+ tokenizer.add_special_tokens(
+ [
+ AddedToken("<|endoftext|>", normalized=False, special=True),
+ AddedToken("<|im_start|>", normalized=False, special=True),
+ AddedToken("<|im_end|>", normalized=False, special=True),
+ ]
+ )
+ return tokenizer
+
+
+class GGUFPhi3Converter(LlamaConverter):
+ def __init__(self, tokenizer_dict):
+ self.proto = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.original_tokenizer = self.proto
+ self.additional_kwargs = {}
+
+ def vocab(self, proto):
+ return list(zip(proto.tokens, proto.scores))
+
+ def merges(self, proto):
+ return proto.merges
+
+ def tokenizer(self, proto):
+ vocab_scores = self.vocab(self.proto)
+ merges = self.merges(self.proto)
+ bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
+
+ tokenizer = Tokenizer(BPE(bpe_vocab, merges))
+ # add the special tokens from phi3 tokenizer config
+ tokenizer.add_special_tokens(
+ [
+ AddedToken("", rstrip=True, lstrip=False, normalized=False, special=True),
+ AddedToken("<|endoftext|>", normalized=False, special=True),
+ AddedToken("<|assistant|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder1|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder2|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder3|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder4|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|system|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|end|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder5|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder6|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|user|>", rstrip=True, normalized=False, special=True),
+ ]
+ )
+
+ self.additional_kwargs["unk_token"] = (
+ proto.tokens[proto.unk_token_id] if proto.unk_token_id is not None else None
+ )
+ self.additional_kwargs["eos_token"] = (
+ proto.tokens[proto.eos_token_id] if proto.eos_token_id is not None else None
+ )
+ self.additional_kwargs["bos_token"] = (
+ proto.tokens[proto.bos_token_id] if proto.bos_token_id is not None else None
+ )
+ self.additional_kwargs["pad_token"] = (
+ proto.tokens[proto.pad_token_id] if proto.pad_token_id is not None else None
+ )
+
+ return tokenizer
+
+ def decoder(self, replacement, add_prefix_space):
+ sequence = [
+ decoders.ByteFallback(),
+ decoders.Fuse(),
+ decoders.Replace(replacement, " "),
+ ]
+
+ if add_prefix_space:
+ sequence += [decoders.Strip(content=" ", left=1)]
+ return decoders.Sequence(sequence)
+
+ def converted(self) -> Tokenizer:
+ tokenizer = self.tokenizer(self.proto)
+
+ replacement = "▁"
+ add_prefix_space = True
+ if hasattr(self.original_tokenizer, "add_prefix_space"):
+ add_prefix_space = self.original_tokenizer.add_prefix_space
+
+ tokenizer.decoder = self.decoder(replacement, add_prefix_space)
+
+ return tokenizer
+
+
+class GGUFGPTConverter(GPT2Converter):
+ def __init__(self, tokenizer_dict):
+ self.original_tokenizer = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.additional_kwargs = {}
+
+ def converted(self) -> Tokenizer:
+ vocab = {word: i for i, word in enumerate(self.original_tokenizer.tokens)}
+ merges = self.original_tokenizer.merges
+ tokenizer = super().converted(vocab, merges)
+ return tokenizer
+
+
+class GGUFT5Converter(T5Converter):
+ def __init__(self, tokenizer_dict):
+ # set dummy data to avoid unnecessary merges calculation
+ tokenizer_dict["merges"] = ["dummy text"]
+
+ self.proto = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.token2id = {k: v for v, k in enumerate(self.proto.tokens)}
+ self.original_tokenizer = self.proto
+ self.additional_kwargs = {}
+
+ def vocab(self, proto):
+ return list(zip(proto.tokens, proto.scores))
+
+ def normalizer(self, proto):
+ if getattr(self.original_tokenizer, "legacy", True):
+ sequence = []
+ if getattr(self.original_tokenizer, "add_prefix_space", True):
+ sequence += [normalizers.Prepend(prepend="▁")]
+ sequence += [normalizers.Replace(pattern=" ", content="▁")]
+ return normalizers.Sequence(sequence)
+ return None # non-legacy, no normalizer
+
+ def post_processor(self):
+ return processors.TemplateProcessing(
+ single=["$A", ""],
+ pair=["$A", "", "$B", ""],
+ special_tokens=[
+ ("", self.token2id[""]),
+ ],
+ )
+
+ def converted(self) -> Tokenizer:
+ vocab_scores = self.vocab(self.proto)
+ tokenizer = Tokenizer(
+ Unigram(
+ vocab_scores,
+ unk_id=self.proto.unk_token_id,
+ byte_fallback=False,
+ )
+ )
+
+ # Tokenizer assemble
+ normalizer = self.normalizer(self.proto)
+ if normalizer is not None:
+ tokenizer.normalizer = normalizer
+
+ replacement = "▁"
+ add_prefix_space = True
+ if hasattr(self.original_tokenizer, "add_prefix_space"):
+ add_prefix_space = self.original_tokenizer.add_prefix_space
+
+ pre_tokenizer = self.pre_tokenizer(replacement, add_prefix_space)
+ if pre_tokenizer is not None:
+ tokenizer.pre_tokenizer = pre_tokenizer
+
+ tokenizer.decoder = self.decoder(replacement, add_prefix_space)
+ post_processor = self.post_processor()
+ if post_processor:
+ tokenizer.post_processor = post_processor
+
+ return tokenizer
+
+
+class GGUFGemmaConverter(GemmaConverter):
+ def __init__(self, tokenizer_dict):
+ # set dummy data to avoid unnecessary merges calculation
+ tokenizer_dict["merges"] = ["dummy text"]
+
+ self.proto = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.original_tokenizer = self.proto
+ self.additional_kwargs = {}
+
+ def vocab(self, proto):
+ original_vocab = list(zip(proto.tokens, proto.scores))
+ updated_vocab = []
+
+ for token, score in original_vocab:
+ if token == "<0x09>":
+ updated_vocab.append(("\t", score))
+ elif " " in token and len(token.strip()) == 0:
+ underscores = "▁" * len(token)
+ updated_vocab.append((underscores, score))
+ else:
+ updated_vocab.append((token, score))
+
+ return updated_vocab
+
+ def normalizer(self, proto):
+ return normalizers.Replace(" ", "▁")
+
+ def decoder(self, replacement, add_prefix_space):
+ sequence = [
+ decoders.Replace("▁", " "),
+ decoders.ByteFallback(),
+ decoders.Fuse(),
+ ]
+
+ if add_prefix_space:
+ sequence += [decoders.Strip(content=" ", left=1)]
+ return decoders.Sequence(sequence)
+
+ def converted(self) -> Tokenizer:
+ vocab_scores = self.vocab(self.proto)
+ tokenizer = Tokenizer(
+ Unigram(
+ vocab_scores,
+ unk_id=self.proto.unk_token_id,
+ byte_fallback=self.handle_byte_fallback,
+ )
+ )
+
+ normalizer = self.normalizer(self.proto)
+ if normalizer is not None:
+ tokenizer.normalizer = normalizer
+
+ replacement = "▁"
+ add_prefix_space = True
+ if hasattr(self.original_tokenizer, "add_prefix_space"):
+ add_prefix_space = self.original_tokenizer.add_prefix_space
+
+ tokenizer.decoder = self.decoder(replacement, add_prefix_space)
+ pre_tokenizer = self.pre_tokenizer(replacement, add_prefix_space)
+ if pre_tokenizer is not None:
+ tokenizer.pre_tokenizer = pre_tokenizer
+
+ return tokenizer
+
+
+GGUF_TO_FAST_CONVERTERS = {
+ "llama": GGUFLlamaConverter,
+ "qwen2": GGUFQwen2Converter,
+ "qwen2_moe": GGUFQwen2Converter,
+ "phi3": GGUFPhi3Converter,
+ "bloom": GGUFGPTConverter,
+ "falcon": GGUFGPTConverter,
+ "stablelm": GGUFGPTConverter,
+ "gpt2": GGUFGPTConverter,
+ "starcoder2": GGUFGPTConverter,
+ "t5": GGUFT5Converter,
+ "mamba": GGUFGPTConverter,
+ "nemotron": GGUFGPTConverter,
+ "gemma2": GGUFGemmaConverter,
+}
+
+
+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.PreTrainedTokenizer`]):
+ Instance of a slow tokenizer to convert in the backend tokenizer for
+ [`~tokenization_utils_base.PreTrainedTokenizerFast`].
+
+ Return:
+ A instance of [`~tokenizers.Tokenizer`] to be used as the backend tokenizer of a
+ [`~tokenization_utils_base.PreTrainedTokenizerFast`]
+ """
+ tokenizer_class_name = architecture
+ converter = GGUF_TO_FAST_CONVERTERS[tokenizer_class_name](tokenizer_dict)
+ fast_tokenizer = converter.converted()
+ return fast_tokenizer, converter.additional_kwargs
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/higgs.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/higgs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ba35eb4e4fd052c610beaab16211b2b43d2e01b
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/higgs.py
@@ -0,0 +1,655 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"HIGGS through FLUTE (Flexible Lookup Table Engine for LUT-quantized LLMs) integration file"
+
+from math import sqrt
+
+from ..utils import (
+ is_flute_available,
+ is_hadamard_available,
+ is_torch_available,
+)
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+
+if is_flute_available():
+ from flute.integrations.higgs import prepare_data_transposed
+ from flute.tune import TuneMetaData, qgemm_v2
+
+if is_hadamard_available():
+ from fast_hadamard_transform import hadamard_transform
+
+
+def pad_to_block(tensor, dims, had_block_size, value=0):
+ pad_dims = [0 for _ in range(2 * len(tensor.shape))]
+ for dim in dims:
+ size = tensor.shape[dim]
+ next_multiple_of_1024 = ((size - 1) // had_block_size + 1) * had_block_size
+ delta = next_multiple_of_1024 - size
+ pad_dims[-2 * dim - 1] = delta
+
+ return nn.functional.pad(tensor, pad_dims, "constant", value)
+
+
+def get_higgs_grid(p: int, n: int):
+ if (p, n) == (2, 256):
+ return torch.tensor(
+ [
+ [-2.501467704772949, 0.17954708635807037],
+ [-0.6761789321899414, 1.2728623151779175],
+ [-1.8025816679000854, 0.7613157629966736],
+ [-0.538287878036499, -2.6028504371643066],
+ [0.8415029644966125, -0.8600977659225464],
+ [0.7023013234138489, 3.3138747215270996],
+ [0.5699077844619751, 2.5782253742218018],
+ [3.292393207550049, -0.6016128063201904],
+ [0.5561617016792297, -1.7723814249038696],
+ [-2.1012380123138428, 0.020958125591278076],
+ [0.46085724234580994, 0.8428705334663391],
+ [1.4548040628433228, -0.6156039237976074],
+ [3.210029363632202, 0.3546904921531677],
+ [0.8893890976905823, -0.5967988967895508],
+ [0.8618854284286499, -3.2061192989349365],
+ [1.1360996961593628, -0.23852407932281494],
+ [1.6646337509155273, -0.9265465140342712],
+ [1.4767773151397705, 1.2476022243499756],
+ [-1.0511897802352905, 1.94503915309906],
+ [-1.56318998336792, -0.3264186680316925],
+ [-0.1829211413860321, 0.2922491431236267],
+ [-0.8950616717338562, -1.3887052536010742],
+ [-0.08206957578659058, -1.329533576965332],
+ [-0.487422913312912, 1.4817842245101929],
+ [-1.6769757270812988, -2.8269758224487305],
+ [-1.5057679414749146, 1.8905963897705078],
+ [1.8335362672805786, 1.0515104532241821],
+ [0.3273945450782776, 1.0491033792495728],
+ [-3.295924186706543, -0.7021600008010864],
+ [-1.8428784608840942, -1.2315762042999268],
+ [-0.8575026392936707, -1.7005949020385742],
+ [-1.120667815208435, 0.6467998027801514],
+ [-0.1588846743106842, -1.804071068763733],
+ [-0.8539647459983826, 0.5645008683204651],
+ [-1.4192019701004028, -0.6175029873847961],
+ [1.0799058675765991, 1.7871345281600952],
+ [1.171311855316162, 0.7511613965034485],
+ [2.162078380584717, 0.8044339418411255],
+ [1.3969420194625854, -1.243762493133545],
+ [-0.23818807303905487, 0.053944624960422516],
+ [2.304199457168579, -1.2667627334594727],
+ [1.4225027561187744, 0.568610668182373],
+ [0.376836895942688, -0.7134661674499512],
+ [2.0404467582702637, 0.4087389409542084],
+ [0.7639489769935608, -1.1367933750152588],
+ [0.3622530400753021, -1.4827953577041626],
+ [0.4100743532180786, 0.36108437180519104],
+ [-1.5867475271224976, -1.618212342262268],
+ [-2.2769672870635986, -1.2132309675216675],
+ [0.9184022545814514, -0.34428009390830994],
+ [-0.3902314603328705, 0.21785245835781097],
+ [3.120687484741211, 1.3077973127365112],
+ [1.587440848350525, -1.6506884098052979],
+ [-1.718808889389038, -0.038405973464250565],
+ [-0.6888407468795776, -0.8402308821678162],
+ [-0.7981445789337158, -1.1117373704910278],
+ [-2.4124443531036377, 1.3419722318649292],
+ [-0.6611530184745789, 0.9939885139465332],
+ [-0.33103418350219727, -0.16702833771705627],
+ [-2.4091389179229736, -2.326857566833496],
+ [1.6610108613967896, -2.159703254699707],
+ [0.014884627424180508, 0.3887578248977661],
+ [0.029668325558304787, 1.8786455392837524],
+ [1.180362582206726, 2.699317216873169],
+ [1.821286678314209, -0.5960053205490112],
+ [-0.44835323095321655, 3.327436685562134],
+ [-0.3714401423931122, -2.1466753482818604],
+ [-1.1103475093841553, -2.4536871910095215],
+ [-0.39110705256462097, 0.6670510172843933],
+ [0.474752813577652, -1.1959707736968994],
+ [-0.013110585510730743, -2.52519154548645],
+ [-2.0836575031280518, -1.703289270401001],
+ [-1.1077687740325928, -0.1252644956111908],
+ [-0.4138077199459076, 1.1837692260742188],
+ [-1.977599024772644, 1.688241720199585],
+ [-1.659559965133667, -2.1387736797332764],
+ [0.03242531046271324, 0.6526556015014648],
+ [0.9127950072288513, 0.6099498867988586],
+ [-0.38478314876556396, 0.433487206697464],
+ [0.27454206347465515, -0.27719801664352417],
+ [0.10388526320457458, 2.2812814712524414],
+ [-0.014394169673323631, -3.177137613296509],
+ [-1.2871228456497192, -0.8961855173110962],
+ [0.5720916986465454, -0.921597957611084],
+ [1.1159656047821045, -0.7609877586364746],
+ [2.4383342266082764, -2.2983546257019043],
+ [-0.294057160615921, -0.9770799875259399],
+ [-0.9342701435089111, 1.107579231262207],
+ [-1.549338698387146, 3.090520143508911],
+ [2.6076579093933105, 2.051239013671875],
+ [-0.9259037375450134, 1.407211184501648],
+ [-0.1747353971004486, 0.540488600730896],
+ [-0.8963701725006104, 0.8271111249923706],
+ [0.6480194926261902, 1.0128909349441528],
+ [0.980783998966217, -0.06156221032142639],
+ [-0.16883476078510284, 1.0601658821105957],
+ [0.5839992761611938, 0.004697148688137531],
+ [-0.34228450059890747, -1.2423977851867676],
+ [2.500824451446533, 0.3665279746055603],
+ [-0.17641609907150269, 1.3529551029205322],
+ [0.05378641560673714, 2.817232847213745],
+ [-1.2391047477722168, 2.354328155517578],
+ [0.630434513092041, -0.668536365032196],
+ [1.7576488256454468, 0.6738647818565369],
+ [0.4435231387615204, 0.6000469326972961],
+ [-0.08794835954904556, -0.11511358618736267],
+ [1.6540337800979614, 0.33995017409324646],
+ [-0.04202975332736969, -0.5375117063522339],
+ [-0.4247745871543884, -0.7897617220878601],
+ [0.06695003807544708, 1.2000739574432373],
+ [-3.2508881092071533, 0.28734830021858215],
+ [-1.613816261291504, 0.4944162368774414],
+ [1.3598989248275757, 0.26117825508117676],
+ [2.308382511138916, 1.3462618589401245],
+ [-1.2137469053268433, -1.9254342317581177],
+ [-0.4889402985572815, 1.8136259317398071],
+ [-0.1870335340499878, -0.3480615019798279],
+ [1.0766386985778809, -1.0627082586288452],
+ [0.4651014506816864, 2.131748914718628],
+ [-0.1306295394897461, -0.7811847925186157],
+ [0.06433182954788208, -1.5397958755493164],
+ [-0.2894323468208313, -0.5789554715156555],
+ [-0.6081662178039551, 0.4845278263092041],
+ [2.697964668273926, -0.18515698611736298],
+ [0.1277363896369934, -0.7221432328224182],
+ [0.8700758218765259, 0.35042452812194824],
+ [0.22088994085788727, 0.495242178440094],
+ [-2.5843818187713623, -0.8000828623771667],
+ [0.6732649803161621, -1.4362232685089111],
+ [-1.5286413431167603, 1.0417330265045166],
+ [-1.1222513914108276, -0.6269875764846802],
+ [-0.9752035140991211, -0.8750635385513306],
+ [-2.6369473934173584, 0.6918523907661438],
+ [0.14478731155395508, -0.041986867785453796],
+ [-1.5629483461380005, 1.4369450807571411],
+ [0.38952457904815674, -2.16428804397583],
+ [-0.16885095834732056, 0.7976621985435486],
+ [-3.12416934967041, 1.256506085395813],
+ [0.6843105554580688, -0.4203019142150879],
+ [1.9345275163650513, 1.934950351715088],
+ [0.012184220366179943, -2.1080918312072754],
+ [-0.6350273489952087, 0.7358828186988831],
+ [-0.837304949760437, -0.6214472651481628],
+ [0.08211923390626907, -0.9472538232803345],
+ [2.9332995414733887, -1.4956780672073364],
+ [1.3806978464126587, -0.2916182279586792],
+ [0.06773144006729126, 0.9285762310028076],
+ [-1.1943119764328003, 1.5963770151138306],
+ [1.6395620107650757, -0.32285431027412415],
+ [-1.390851378440857, -0.08273141086101532],
+ [1.816330909729004, -1.2812227010726929],
+ [0.7921574711799622, -2.1135804653167725],
+ [0.5817914605140686, 1.2644577026367188],
+ [1.929347038269043, -0.2386285960674286],
+ [0.8877345323562622, 1.190008521080017],
+ [1.4732073545455933, 0.8935023546218872],
+ [-2.8518524169921875, -1.5478795766830444],
+ [0.2439267635345459, 0.7576767802238464],
+ [0.5246709585189819, -2.606659412384033],
+ [1.150876760482788, 1.4073830842971802],
+ [-0.2643202245235443, 2.0634236335754395],
+ [1.555483341217041, -0.0023102816194295883],
+ [2.0830578804016113, -1.7225427627563477],
+ [-0.5424830317497253, -1.070199728012085],
+ [0.9168899655342102, 0.8955540060997009],
+ [-0.8120972514152527, 2.696739912033081],
+ [-0.29908373951911926, -1.5310651063919067],
+ [1.2320337295532227, -1.556247353553772],
+ [1.8612544536590576, 0.08704725652933121],
+ [0.22133447229862213, -1.8091708421707153],
+ [-0.4403655230998993, -0.38571012020111084],
+ [-1.88539457321167, 1.192205786705017],
+ [2.239687919616699, 0.004709010478109121],
+ [1.139495611190796, 0.45733731985092163],
+ [-1.507995367050171, 0.19716016948223114],
+ [0.46986445784568787, 1.5422041416168213],
+ [-1.2573751211166382, -0.35984551906585693],
+ [-1.7415345907211304, -0.6020717024803162],
+ [1.0751984119415283, 0.19006384909152985],
+ [2.24186635017395, -0.46343153715133667],
+ [0.3610347509384155, -0.07658443599939346],
+ [-1.3111497163772583, 0.432013601064682],
+ [0.6164408326148987, 0.24538464844226837],
+ [-1.9266542196273804, -0.3256155550479889],
+ [-0.5870336890220642, -0.1879584938287735],
+ [-1.0476511716842651, 0.3677721917629242],
+ [-1.229940414428711, 1.2433830499649048],
+ [0.18550436198711395, 0.22753673791885376],
+ [-0.017921989783644676, 0.12625974416732788],
+ [1.1659504175186157, -0.5020995736122131],
+ [-0.5983408093452454, -1.40438973903656],
+ [0.7519024014472961, -0.16282692551612854],
+ [0.9920787811279297, -1.344896912574768],
+ [-0.8103678226470947, 0.3064485788345337],
+ [0.6956969499588013, 1.8208192586898804],
+ [-2.7830491065979004, -0.2299390584230423],
+ [-0.34681546688079834, 2.4890666007995605],
+ [-1.4452646970748901, -1.2216600179672241],
+ [-2.1872897148132324, 0.8926076292991638],
+ [1.706072211265564, -2.8440372943878174],
+ [1.1119003295898438, -2.4923460483551025],
+ [-2.582794666290283, 2.0973289012908936],
+ [0.04987720400094986, -0.2964983284473419],
+ [-2.063807487487793, -0.7847916483879089],
+ [-0.4068813621997833, 0.9135897755622864],
+ [-0.9814359545707703, -0.3874954879283905],
+ [-1.4227229356765747, 0.7337291240692139],
+ [0.3065044581890106, 1.3125417232513428],
+ [1.2160996198654175, -1.9643305540084839],
+ [-1.2163853645324707, 0.14608727395534515],
+ [-2.3030710220336914, -0.37558120489120483],
+ [0.9232977628707886, 2.1843791007995605],
+ [-0.1989777386188507, 1.651851773262024],
+ [-0.714374840259552, -0.39365994930267334],
+ [-0.7805715799331665, -2.099881887435913],
+ [0.9015759229660034, -1.7053706645965576],
+ [0.1033422127366066, 1.5256654024124146],
+ [-1.8773194551467896, 2.324174165725708],
+ [1.9227174520492554, 2.7441604137420654],
+ [-0.5994020104408264, 0.23984014987945557],
+ [1.3496100902557373, -0.9126054644584656],
+ [-0.8765304088592529, -3.1877026557922363],
+ [-1.2040035724639893, -1.5169521570205688],
+ [1.4261796474456787, 2.150200128555298],
+ [1.463774561882019, 1.6656692028045654],
+ [0.20364105701446533, -0.4988172650337219],
+ [0.5195154547691345, -0.24067887663841248],
+ [-1.1116786003112793, -1.1599653959274292],
+ [-0.8490808606147766, -0.1681060940027237],
+ [0.3189965784549713, -0.9641751646995544],
+ [-0.5664751529693604, -0.5951744318008423],
+ [-1.6347930431365967, -0.9137664437294006],
+ [0.44048091769218445, -0.47259435057640076],
+ [-2.147747039794922, 0.47442489862442017],
+ [1.834734320640564, 1.4462147951126099],
+ [1.1777573823928833, 1.0659226179122925],
+ [-0.9568989872932434, 0.09495053440332413],
+ [-1.838529348373413, 0.2950586676597595],
+ [-0.4800611734390259, 0.014894310384988785],
+ [-0.5235516428947449, -1.7687653303146362],
+ [2.0735011100769043, -0.8825281262397766],
+ [2.637502431869507, 0.8455678224563599],
+ [2.606602907180786, -0.7848446369171143],
+ [-1.1886937618255615, 0.9330510497093201],
+ [0.38082656264305115, 0.13328030705451965],
+ [0.6847941875457764, 0.7384101152420044],
+ [1.2638574838638306, -0.007309418171644211],
+ [0.18292222917079926, -1.22371244430542],
+ [0.8143821954727173, 1.4976691007614136],
+ [0.6571850776672363, 0.48368802666664124],
+ [-0.6991601586341858, 2.150190830230713],
+ [0.8101756572723389, 0.10206498205661774],
+ [-0.08768226951360703, -1.084917664527893],
+ [-0.7208092212677002, 0.03657956421375275],
+ [0.3211449086666107, 1.803687334060669],
+ [-0.7835946083068848, 1.6869111061096191],
+ ]
+ )
+ if (p, n) == (2, 64):
+ return torch.tensor(
+ [
+ [-2.7216711044311523, 0.14431366324424744],
+ [-0.766914427280426, 1.7193410396575928],
+ [-2.2575762271881104, 1.2476624250411987],
+ [1.233758807182312, -2.3560616970062256],
+ [0.8701965808868408, -0.2649352252483368],
+ [1.4506438970565796, 2.1776366233825684],
+ [-0.06305818259716034, 1.9049758911132812],
+ [2.536226511001587, 0.563927412033081],
+ [0.4599496126174927, -1.8745561838150024],
+ [-1.900517225265503, -0.30703988671302795],
+ [0.09386251866817474, 0.8755807280540466],
+ [1.946500539779663, -0.6743080615997314],
+ [2.1338934898376465, 1.4581491947174072],
+ [0.9429940581321716, -0.8038390278816223],
+ [2.0697755813598633, -1.614896535873413],
+ [0.772676408290863, 0.22017823159694672],
+ [1.0689979791641235, -1.525044322013855],
+ [0.6813604831695557, 1.1345642805099487],
+ [0.4706456661224365, 2.606626272201538],
+ [-1.294018030166626, -0.4372096061706543],
+ [-0.09134224057197571, 0.4610418677330017],
+ [-0.7907772064208984, -0.48412787914276123],
+ [0.060459110885858536, -0.9172890186309814],
+ [-0.5855047702789307, 2.56172513961792],
+ [0.11484206467866898, -2.659848213195801],
+ [-1.5893300771713257, 2.188580274581909],
+ [1.6750942468643188, 0.7089915871620178],
+ [-0.445697546005249, 0.7452405095100403],
+ [-1.8539940118789673, -1.8377939462661743],
+ [-1.5791912078857422, -1.017285943031311],
+ [-1.030419945716858, -1.5746369361877441],
+ [-1.9511750936508179, 0.43696075677871704],
+ [-0.3446580767631531, -1.8953213691711426],
+ [-1.4219647645950317, 0.7676230669021606],
+ [-0.9191089272499084, 0.5021472573280334],
+ [0.20464491844177246, 1.3684605360031128],
+ [0.5402919054031372, 0.6699410676956177],
+ [1.8903915882110596, 0.03638288006186485],
+ [0.4723062515258789, -0.6216739416122437],
+ [-0.41345009207725525, -0.22752176225185394],
+ [2.7119064331054688, -0.5111885070800781],
+ [1.065286636352539, 0.6950305700302124],
+ [0.40629103779792786, -0.14339995384216309],
+ [1.2815024852752686, 0.17108257114887238],
+ [0.01785222627222538, -0.43778058886528015],
+ [0.054590027779340744, -1.4225547313690186],
+ [0.3076786696910858, 0.30697619915008545],
+ [-0.9498570561408997, -0.9576997756958008],
+ [-2.4640724658966064, -0.9660449028015137],
+ [1.3714425563812256, -0.39760473370552063],
+ [-0.4857747256755829, 0.2386789172887802],
+ [1.2797833681106567, 1.3097363710403442],
+ [0.5508887767791748, -1.1777795553207397],
+ [-1.384316325187683, 0.1465839296579361],
+ [-0.46556955575942993, -1.2442727088928223],
+ [-0.3915477693080902, -0.7319604158401489],
+ [-1.4005504846572876, 1.3890998363494873],
+ [-0.8647305965423584, 1.0617644786834717],
+ [-0.8901953101158142, -0.01650036871433258],
+ [-0.9893633723258972, -2.4662880897521973],
+ [1.445534110069275, -1.049334168434143],
+ [-0.041650623083114624, 0.012734669260680676],
+ [-0.3302375078201294, 1.26217782497406],
+ [0.6934980154037476, 1.7714335918426514],
+ ]
+ )
+ elif (p, n) == (2, 16):
+ return torch.tensor(
+ [
+ [-0.8996632695198059, -1.6360418796539307],
+ [-0.961183488368988, 1.5999565124511719],
+ [-1.882026195526123, 0.678778350353241],
+ [0.36300793290138245, -1.9667866230010986],
+ [-0.6814072728157043, -0.576818585395813],
+ [0.7270012497901917, 0.6186859607696533],
+ [0.3359416127204895, 1.8371193408966064],
+ [1.859930396080017, 0.036668598651885986],
+ [0.17208248376846313, -0.9401724338531494],
+ [-1.7599700689315796, -0.6244229674339294],
+ [-0.8993809223175049, 0.32267823815345764],
+ [0.839488685131073, -0.3017036020755768],
+ [1.5314953327178955, 1.2942044734954834],
+ [-0.0011779458727687597, 0.00022069070837460458],
+ [1.4274526834487915, -1.207889199256897],
+ [-0.16123905777931213, 0.8787511587142944],
+ ]
+ )
+ elif (p, n) == (1, 16):
+ return torch.tensor(
+ [
+ [-2.7325894832611084],
+ [-2.069017171859741],
+ [-1.6180464029312134],
+ [-1.2562311887741089],
+ [-0.9423404335975647],
+ [-0.6567591428756714],
+ [-0.38804829120635986],
+ [-0.12839503586292267],
+ [0.12839503586292267],
+ [0.38804829120635986],
+ [0.6567591428756714],
+ [0.9423404335975647],
+ [1.2562311887741089],
+ [1.6180464029312134],
+ [2.069017171859741],
+ [2.7325894832611084],
+ ]
+ )
+ elif (p, n) == (1, 8):
+ return torch.tensor(
+ [
+ [-2.1519455909729004],
+ [-1.3439092636108398],
+ [-0.7560052871704102],
+ [-0.2450941801071167],
+ [0.2450941801071167],
+ [0.7560052871704102],
+ [1.3439092636108398],
+ [2.1519455909729004],
+ ]
+ )
+ elif (p, n) == (1, 4):
+ return torch.tensor([[-1.5104175806045532], [-0.4527800381183624], [0.4527800381183624], [1.5104175806045532]])
+ else:
+ raise NotImplementedError(f"Unsupported p={p}, n={n}")
+
+
+def quantize_with_higgs(weight, bits: int = 4, p: int = 2, group_size: int = 256, hadamard_size: int = 1024):
+ assert len(weight.shape) == 2, "Only 2D weights are supported for now"
+
+ grid = get_higgs_grid(p, 2 ** (p * bits)).to(weight.device)
+ grid_norm_2 = torch.linalg.norm(grid, axis=-1) ** 2
+
+ device = weight.device
+ dtype = weight.dtype
+ weight = weight.clone().float()
+ # Pad to Hadamard transform size
+ weight = pad_to_block(weight, [1], hadamard_size)
+
+ # Scale and Hadamard transform
+ mult = weight.shape[1] // hadamard_size
+ weight = weight.reshape(-1, mult, hadamard_size)
+ scales = torch.linalg.norm(weight, axis=-1)
+ weight = hadamard_transform(weight, 1) / scales[:, :, None]
+
+ # Pad to edenn_d and project
+ weight = pad_to_block(weight, [2], p).reshape(weight.shape[0], mult, -1, p)
+
+ # Quantize
+ codes = torch.empty(weight.shape[:-1], device=device, dtype=torch.uint8)
+ for i in range(0, weight.shape[0], 16):
+ codes[i : i + 16] = torch.argmax(2 * weight[i : i + 16] @ grid.T - grid_norm_2, dim=-1).to(torch.uint8)
+ del weight
+
+ codes = codes.reshape(codes.shape[0], -1)
+ scales = scales / sqrt(hadamard_size)
+
+ weight, scales, tables, tables2, tune_metadata = prepare_data_transposed(
+ codes,
+ torch.repeat_interleave(scales.to(dtype), hadamard_size // group_size, dim=1),
+ grid.to(dtype),
+ num_bits=bits,
+ group_size=group_size,
+ vector_size=p,
+ dtype=dtype,
+ device=device,
+ check_correctness=False,
+ )
+
+ return {
+ "weight": weight,
+ "scales": scales,
+ "tables": tables,
+ "tables2": tables2.view(dtype=torch.float16),
+ "tune_metadata": tune_metadata,
+ }
+
+
+class HiggsLinear(torch.nn.Module):
+ def __init__(
+ self,
+ in_features: int,
+ out_features: int,
+ num_bits: int,
+ bias=True,
+ dtype: torch.dtype = None,
+ device: torch.device = None,
+ group_size: int = 256,
+ hadamard_size: int = 1024,
+ ):
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+ self.num_bits = num_bits
+ self.group_size = group_size
+ self.hadamard_size = hadamard_size
+
+ assert in_features % group_size == 0
+ assert num_bits in [2, 3, 4]
+
+ self.weight = nn.Parameter(
+ torch.empty((out_features * num_bits // 16, in_features), dtype=torch.int16, device=device),
+ requires_grad=False,
+ )
+ self.scales = nn.Parameter(
+ torch.empty((out_features, in_features // group_size), dtype=dtype, device=device), requires_grad=False
+ )
+ self.tables = nn.Parameter(torch.empty((2**num_bits,), dtype=dtype, device=device), requires_grad=False)
+ self.tables2 = nn.Parameter(
+ torch.empty((2**num_bits, 2**num_bits, 2), dtype=dtype, device=device), requires_grad=False
+ )
+
+ if bias:
+ self.bias = nn.Parameter(torch.empty(out_features, device=device, dtype=dtype), requires_grad=False)
+ else:
+ self.register_parameter("bias", None)
+
+ self.workspace = None # must be set externally to be reused among layers
+ self.tune_metadata: TuneMetaData = None # must be set externally because architecture dependent
+
+ def forward(self, x):
+ x = pad_to_block(x, [-1], self.hadamard_size)
+
+ if self.workspace is None:
+ raise Exception("Workspace must be set before calling forward")
+
+ return qgemm_v2(
+ x,
+ self.weight,
+ self.scales,
+ self.tables,
+ self.tables2.view(dtype=torch.float32),
+ self.workspace,
+ self.tune_metadata,
+ hadamard_size=self.hadamard_size,
+ )
+
+
+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 model and a boolean that indicates if the
+ conversion has been successfull or not.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`HiggsConfig`):
+ The quantization config object that contains the quantization parameters.
+ current_key_name (`list`, *optional*):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+
+ from accelerate import init_empty_weights
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, nn.Linear):
+ # Check if the current key is not in the `quantization_config.modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+ if not any(current_key_name_str.endswith(key) for key in quantization_config.modules_to_not_convert):
+ with init_empty_weights():
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = HiggsLinear(
+ in_features,
+ out_features,
+ bias=module.bias is not None,
+ num_bits=quantization_config.bits,
+ hadamard_size=quantization_config.hadamard_size,
+ group_size=quantization_config.group_size,
+ )
+ has_been_replaced = True
+
+ # Store the module class in case we need to transpose the weight later
+ model._modules[name].source_cls = type(module)
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_higgs_linear(
+ module,
+ quantization_config=quantization_config,
+ current_key_name=current_key_name,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+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 list to keep track of the current module names during recursion. Defaults to None.
+ Returns:
+ torch.nn.Module: The model with HiggsLinear layers replaced by torch.nn.Linear layers.
+ """
+
+ with torch.no_grad():
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, HiggsLinear):
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = torch.nn.Linear(
+ in_features,
+ out_features,
+ bias=module.bias is not None,
+ device=module.scales.device,
+ dtype=module.scales.dtype,
+ )
+
+ model._modules[name].weight.data = module(
+ torch.eye(in_features, device=module.scales.device, dtype=module.scales.dtype)
+ ).T.contiguous()
+
+ if len(list(module.children())) > 0:
+ _ = dequantize_higgs(
+ module,
+ current_key_name=current_key_name,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/hqq.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/hqq.py
new file mode 100644
index 0000000000000000000000000000000000000000..162b365668a0474fc4b109627019546e21fb3b85
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/hqq.py
@@ -0,0 +1,129 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"HQQ (Half-Quadratic Quantization) integration file"
+
+from ..utils import is_hqq_available, is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+# Name all modules inside the model
+def autoname_modules(model):
+ for name, module in model.named_modules():
+ module.name = name
+
+
+# Get the linear_tag from a modul name. For example: model.layers.31.self_attn.k_proj -> self_attn.k_proj
+def name_to_linear_tag(name):
+ return ".".join([n for n in name.split(".") if ((n not in ["model", "layers"]) and (not n.isnumeric()))])
+
+
+# Get all linear tags available
+def get_linear_tags(model):
+ if is_hqq_available():
+ from hqq.core.quantize import HQQLinear
+
+ linear_tags = set()
+ for name, module in model.named_modules():
+ if isinstance(module, (torch.nn.Linear, HQQLinear)):
+ linear_tags.add(name_to_linear_tag(name))
+ return list(linear_tags)
+
+
+def _prepare_for_hqq_linear(model, patch_params, has_been_replaced, current_key_name=None):
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, torch.nn.Linear):
+ # Get linear tag
+ linear_tag = name_to_linear_tag(module.name)
+
+ # We put the module quant_config into the nn.Linear layer so we can access it later in quantizer_hqq.create_quantized_param()
+ if linear_tag in patch_params:
+ if patch_params[linear_tag] is not None:
+ model._modules[name].quant_config = patch_params[linear_tag]
+ # Store the module class in case we need to transpose the weight later
+ model._modules[name].source_cls = type(module)
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+
+ has_been_replaced = True
+
+ # Add these fake parameters to avoid loading fail
+ for att in ["W_q", "meta"]:
+ setattr(module, att, None)
+
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _prepare_for_hqq_linear(
+ module,
+ patch_params=patch_params,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+
+ return model, has_been_replaced
+
+
+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 neme via autoname_modules()
+ 2- Extract linear_tags (e.g. ['self_attn.q_proj', ...])
+ 3- Map quantization parameters as a dictionary linear_tag -> quant_params as HQQLinear exepects it, this is referred to as patch_params
+ """
+
+ modules_to_not_convert = [] if modules_to_not_convert is None else modules_to_not_convert
+
+ # Add name to module
+ autoname_modules(model)
+
+ # Get linear tags. This allows us to use different quant params to different layer types
+ linear_tags = get_linear_tags(model)
+
+ # Convert quantization_config to layer-wise config
+ skip_modules = quantization_config.skip_modules
+ quant_config = quantization_config.quant_config
+ linear_tags = list(set(linear_tags) - set(skip_modules) - set(modules_to_not_convert))
+
+ if any(key in linear_tags for key in quant_config.keys()):
+ # If the user doesn't specify a key from get_linear_tags, the layer is not quantized via (key, None)
+ patch_params = {key: None for key in linear_tags}
+ patch_params.update(quant_config)
+ else:
+ # Same quant_config for all layers
+ patch_params = {k: quant_config for k in linear_tags}
+
+ model, has_been_replaced = _prepare_for_hqq_linear(
+ model, patch_params=patch_params, has_been_replaced=has_been_replaced
+ )
+
+ # We store quantization config as linear_tag -> hqq quant config
+ model.config.quantization_config = {
+ "quant_config": quant_config,
+ "quant_method": quantization_config.quant_method,
+ "skip_modules": skip_modules,
+ }
+
+ if not has_been_replaced:
+ logger.warning("No linear modules were found in your model for quantization.")
+
+ return model
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/integration_utils.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/integration_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb9956905bbda05250d06662060f244443a46cbd
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/integration_utils.py
@@ -0,0 +1,2177 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Integrations with other Python libraries.
+"""
+
+import functools
+import importlib.metadata
+import importlib.util
+import json
+import numbers
+import os
+import pickle
+import shutil
+import sys
+import tempfile
+from dataclasses import asdict, fields
+from enum import Enum
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union
+
+import numpy as np
+import packaging.version
+
+from .. import PreTrainedModel, TFPreTrainedModel
+from .. import __version__ as version
+from ..utils import (
+ PushToHubMixin,
+ flatten_dict,
+ is_datasets_available,
+ is_pandas_available,
+ is_tf_available,
+ is_torch_available,
+ logging,
+)
+
+
+logger = logging.get_logger(__name__)
+
+if is_torch_available():
+ import torch
+
+# comet_ml requires to be imported before any ML frameworks
+_MIN_COMET_VERSION = "3.43.2"
+try:
+ _comet_version = importlib.metadata.version("comet_ml")
+ _is_comet_installed = True
+
+ _is_comet_recent_enough = packaging.version.parse(_comet_version) >= packaging.version.parse(_MIN_COMET_VERSION)
+
+ # Check if the Comet API Key is set
+ import comet_ml
+
+ if comet_ml.config.get_config("comet.api_key") is not None:
+ _is_comet_configured = True
+ else:
+ _is_comet_configured = False
+except (importlib.metadata.PackageNotFoundError, ImportError, ValueError, TypeError, AttributeError, KeyError):
+ _comet_version = None
+ _is_comet_installed = False
+ _is_comet_recent_enough = False
+ _is_comet_configured = False
+
+_has_neptune = (
+ importlib.util.find_spec("neptune") is not None or importlib.util.find_spec("neptune-client") is not None
+)
+if TYPE_CHECKING and _has_neptune:
+ try:
+ _neptune_version = importlib.metadata.version("neptune")
+ logger.info(f"Neptune version {_neptune_version} available.")
+ except importlib.metadata.PackageNotFoundError:
+ try:
+ _neptune_version = importlib.metadata.version("neptune-client")
+ logger.info(f"Neptune-client version {_neptune_version} available.")
+ except importlib.metadata.PackageNotFoundError:
+ _has_neptune = False
+
+from .. import modelcard # noqa: E402
+from ..trainer_callback import ProgressCallback, TrainerCallback # noqa: E402
+from ..trainer_utils import PREFIX_CHECKPOINT_DIR, BestRun, IntervalStrategy # noqa: E402
+from ..training_args import ParallelMode # noqa: E402
+from ..utils import ENV_VARS_TRUE_VALUES, is_torch_xla_available # noqa: E402
+
+
+# Integration functions:
+def is_wandb_available():
+ # any value of WANDB_DISABLED disables wandb
+ if os.getenv("WANDB_DISABLED", "").upper() in ENV_VARS_TRUE_VALUES:
+ logger.warning(
+ "Using the `WANDB_DISABLED` environment variable is deprecated and will be removed in v5. Use the "
+ "--report_to flag to control the integrations used for logging result (for instance --report_to none)."
+ )
+ return False
+ return importlib.util.find_spec("wandb") is not None
+
+
+def is_clearml_available():
+ return importlib.util.find_spec("clearml") is not None
+
+
+def is_comet_available():
+ if os.getenv("COMET_MODE", "").upper() == "DISABLED":
+ logger.warning(
+ "Using the `COMET_MODE=DISABLED` environment variable is deprecated and will be removed in v5. Use the "
+ "--report_to flag to control the integrations used for logging result (for instance --report_to none)."
+ )
+ return False
+
+ if _is_comet_installed is False:
+ return False
+
+ if _is_comet_recent_enough is False:
+ logger.warning(
+ "comet_ml version %s is installed, but version %s or higher is required. "
+ "Please update comet_ml to the latest version to enable Comet logging with pip install 'comet-ml>=%s'.",
+ _comet_version,
+ _MIN_COMET_VERSION,
+ _MIN_COMET_VERSION,
+ )
+ return False
+
+ if _is_comet_configured is False:
+ logger.warning(
+ "comet_ml is installed but the Comet API Key is not configured. "
+ "Please set the `COMET_API_KEY` environment variable to enable Comet logging. "
+ "Check out the documentation for other ways of configuring it: "
+ "https://www.comet.com/docs/v2/guides/experiment-management/configure-sdk/#set-the-api-key"
+ )
+ return False
+
+ return True
+
+
+def is_tensorboard_available():
+ return importlib.util.find_spec("tensorboard") is not None or importlib.util.find_spec("tensorboardX") is not None
+
+
+def is_optuna_available():
+ return importlib.util.find_spec("optuna") is not None
+
+
+def is_ray_available():
+ return importlib.util.find_spec("ray") is not None
+
+
+def is_ray_tune_available():
+ if not is_ray_available():
+ return False
+ return importlib.util.find_spec("ray.tune") is not None
+
+
+def is_sigopt_available():
+ return importlib.util.find_spec("sigopt") is not None
+
+
+def is_azureml_available():
+ if importlib.util.find_spec("azureml") is None:
+ return False
+ if importlib.util.find_spec("azureml.core") is None:
+ return False
+ return importlib.util.find_spec("azureml.core.run") is not None
+
+
+def is_mlflow_available():
+ if os.getenv("DISABLE_MLFLOW_INTEGRATION", "FALSE").upper() == "TRUE":
+ return False
+ return importlib.util.find_spec("mlflow") is not None
+
+
+def is_dagshub_available():
+ return None not in [importlib.util.find_spec("dagshub"), importlib.util.find_spec("mlflow")]
+
+
+def is_neptune_available():
+ return _has_neptune
+
+
+def is_codecarbon_available():
+ return importlib.util.find_spec("codecarbon") is not None
+
+
+def is_flytekit_available():
+ return importlib.util.find_spec("flytekit") is not None
+
+
+def is_flyte_deck_standard_available():
+ if not is_flytekit_available():
+ return False
+ return importlib.util.find_spec("flytekitplugins.deck") is not None
+
+
+def is_dvclive_available():
+ return importlib.util.find_spec("dvclive") is not None
+
+
+def hp_params(trial):
+ if is_optuna_available():
+ import optuna
+
+ if isinstance(trial, optuna.trial.BaseTrial):
+ return trial.params
+ if is_ray_tune_available():
+ if isinstance(trial, dict):
+ return trial
+
+ if is_sigopt_available():
+ if isinstance(trial, dict):
+ return trial
+
+ if is_wandb_available():
+ if isinstance(trial, dict):
+ return trial
+
+ raise RuntimeError(f"Unknown type for trial {trial.__class__}")
+
+
+def run_hp_search_optuna(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
+ import optuna
+ from accelerate.utils.memory import release_memory
+
+ if trainer.args.process_index == 0:
+
+ def _objective(trial: optuna.Trial, checkpoint_dir=None):
+ checkpoint = None
+ if checkpoint_dir:
+ for subdir in os.listdir(checkpoint_dir):
+ if subdir.startswith(PREFIX_CHECKPOINT_DIR):
+ checkpoint = os.path.join(checkpoint_dir, subdir)
+ trainer.objective = None
+ if trainer.args.world_size > 1:
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
+ raise RuntimeError("only support DDP optuna HPO for ParallelMode.DISTRIBUTED currently.")
+ trainer.hp_space(trial)
+ fixed_trial = optuna.trial.FixedTrial(trial.params, trial.number)
+ trial_main_rank_list = [fixed_trial]
+ torch.distributed.broadcast_object_list(trial_main_rank_list, src=0)
+ trainer.train(resume_from_checkpoint=checkpoint, trial=trial)
+ else:
+ trainer.train(resume_from_checkpoint=checkpoint, trial=trial)
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+
+ # Free GPU memory
+ trainer.model_wrapped, trainer.model = release_memory(trainer.model_wrapped, trainer.model)
+ trainer.accelerator.clear()
+
+ return trainer.objective
+
+ timeout = kwargs.pop("timeout", None)
+ n_jobs = kwargs.pop("n_jobs", 1)
+ gc_after_trial = kwargs.pop("gc_after_trial", False)
+ directions = direction if isinstance(direction, list) else None
+ direction = None if directions is not None else direction
+ study = optuna.create_study(direction=direction, directions=directions, **kwargs)
+ study.optimize(_objective, n_trials=n_trials, timeout=timeout, n_jobs=n_jobs, gc_after_trial=gc_after_trial)
+ if not study._is_multi_objective():
+ best_trial = study.best_trial
+ return BestRun(str(best_trial.number), best_trial.value, best_trial.params)
+ else:
+ best_trials = study.best_trials
+ return [BestRun(str(best.number), best.values, best.params) for best in best_trials]
+ else:
+ for i in range(n_trials):
+ trainer.objective = None
+ trial_main_rank_list = [None]
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
+ raise RuntimeError("only support DDP optuna HPO for ParallelMode.DISTRIBUTED currently.")
+ torch.distributed.broadcast_object_list(trial_main_rank_list, src=0)
+ trainer.train(resume_from_checkpoint=None, trial=trial_main_rank_list[0])
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+ return None
+
+
+def run_hp_search_ray(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
+ import ray
+ import ray.train
+
+ def _objective(trial: dict, local_trainer):
+ try:
+ from transformers.utils.notebook import NotebookProgressCallback
+
+ if local_trainer.pop_callback(NotebookProgressCallback):
+ local_trainer.add_callback(ProgressCallback)
+ except ModuleNotFoundError:
+ pass
+
+ local_trainer.objective = None
+
+ checkpoint = ray.train.get_checkpoint()
+ if checkpoint:
+ # Upon trial resume, the local_trainer's objective gets reset to None.
+ # If `local_trainer.train` is a noop (training has already reached
+ # the target number of epochs/steps), then this would
+ # trigger an unnecessary extra checkpoint at the end of training.
+ # -> Set the objective to a dummy value upon resume as a workaround.
+ local_trainer.objective = "objective"
+
+ with checkpoint.as_directory() as checkpoint_dir:
+ checkpoint_path = next(Path(checkpoint_dir).glob(f"{PREFIX_CHECKPOINT_DIR}*")).as_posix()
+ local_trainer.train(resume_from_checkpoint=checkpoint_path, trial=trial)
+ else:
+ local_trainer.train(trial=trial)
+
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(local_trainer, "objective", None) is None:
+ metrics = local_trainer.evaluate()
+ local_trainer.objective = local_trainer.compute_objective(metrics)
+
+ metrics.update({"objective": local_trainer.objective, "done": True})
+
+ with tempfile.TemporaryDirectory() as temp_checkpoint_dir:
+ local_trainer._tune_save_checkpoint(checkpoint_dir=temp_checkpoint_dir)
+ checkpoint = ray.train.Checkpoint.from_directory(temp_checkpoint_dir)
+ ray.train.report(metrics, checkpoint=checkpoint)
+
+ if not trainer._memory_tracker.skip_memory_metrics:
+ from ..trainer_utils import TrainerMemoryTracker
+
+ logger.warning(
+ "Memory tracking for your Trainer is currently "
+ "enabled. Automatically disabling the memory tracker "
+ "since the memory tracker is not serializable."
+ )
+ trainer._memory_tracker = TrainerMemoryTracker(skip_memory_metrics=True)
+
+ # The model and TensorBoard writer do not pickle so we have to remove them (if they exists)
+ # while doing the ray hp search.
+ _tb_writer = trainer.pop_callback(TensorBoardCallback)
+ trainer.model = None
+
+ # Setup default `resources_per_trial`.
+ if "resources_per_trial" not in kwargs:
+ # Default to 1 CPU and 1 GPU (if applicable) per trial.
+ kwargs["resources_per_trial"] = {"cpu": 1}
+ if trainer.args.n_gpu > 0:
+ kwargs["resources_per_trial"]["gpu"] = 1
+ resource_msg = "1 CPU" + (" and 1 GPU" if trainer.args.n_gpu > 0 else "")
+ logger.info(
+ "No `resources_per_trial` arg was passed into "
+ "`hyperparameter_search`. Setting it to a default value "
+ f"of {resource_msg} for each trial."
+ )
+ # Make sure each trainer only uses GPUs that were allocated per trial.
+ gpus_per_trial = kwargs["resources_per_trial"].get("gpu", 0)
+ trainer.args._n_gpu = gpus_per_trial
+
+ # Setup default `progress_reporter`.
+ if "progress_reporter" not in kwargs:
+ from ray.tune import CLIReporter
+
+ kwargs["progress_reporter"] = CLIReporter(metric_columns=["objective"])
+
+ if "scheduler" in kwargs:
+ from ray.tune.schedulers import ASHAScheduler, HyperBandForBOHB, MedianStoppingRule, PopulationBasedTraining
+
+ # Check for `do_eval` and `eval_during_training` for schedulers that require intermediate reporting.
+ if isinstance(
+ kwargs["scheduler"], (ASHAScheduler, MedianStoppingRule, HyperBandForBOHB, PopulationBasedTraining)
+ ) and (not trainer.args.do_eval or trainer.args.eval_strategy == IntervalStrategy.NO):
+ raise RuntimeError(
+ "You are using {cls} as a scheduler but you haven't enabled evaluation during training. "
+ "This means your trials will not report intermediate results to Ray Tune, and "
+ "can thus not be stopped early or used to exploit other trials parameters. "
+ "If this is what you want, do not use {cls}. If you would like to use {cls}, "
+ "make sure you pass `do_eval=True` and `eval_strategy='steps'` in the "
+ "Trainer `args`.".format(cls=type(kwargs["scheduler"]).__name__)
+ )
+
+ trainable = ray.tune.with_parameters(_objective, local_trainer=trainer)
+
+ @functools.wraps(trainable)
+ 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`, defined above, is a function.
+ """
+ if is_datasets_available():
+ import datasets.load
+
+ dynamic_modules_path = os.path.join(datasets.load.init_dynamic_modules(), "__init__.py")
+ # load dynamic_modules from path
+ spec = importlib.util.spec_from_file_location("datasets_modules", dynamic_modules_path)
+ datasets_modules = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = datasets_modules
+ spec.loader.exec_module(datasets_modules)
+ return trainable(*args, **kwargs)
+
+ # special attr set by tune.with_parameters
+ if hasattr(trainable, "__mixins__"):
+ dynamic_modules_import_trainable.__mixins__ = trainable.__mixins__
+
+ analysis = ray.tune.run(
+ dynamic_modules_import_trainable,
+ config=trainer.hp_space(None),
+ num_samples=n_trials,
+ **kwargs,
+ )
+ best_trial = analysis.get_best_trial(metric="objective", mode=direction[:3], scope=trainer.args.ray_scope)
+ best_run = BestRun(best_trial.trial_id, best_trial.last_result["objective"], best_trial.config, analysis)
+ if _tb_writer is not None:
+ trainer.add_callback(_tb_writer)
+ return best_run
+
+
+def run_hp_search_sigopt(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
+ import sigopt
+
+ if trainer.args.process_index == 0:
+ if importlib.metadata.version("sigopt") >= "8.0.0":
+ sigopt.set_project("huggingface")
+
+ experiment = sigopt.create_experiment(
+ name="huggingface-tune",
+ type="offline",
+ parameters=trainer.hp_space(None),
+ metrics=[{"name": "objective", "objective": direction, "strategy": "optimize"}],
+ parallel_bandwidth=1,
+ budget=n_trials,
+ )
+
+ logger.info(f"created experiment: https://app.sigopt.com/experiment/{experiment.id}")
+
+ for run in experiment.loop():
+ with run:
+ trainer.objective = None
+ if trainer.args.world_size > 1:
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
+ raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.")
+ trainer._hp_search_setup(run.run)
+ torch.distributed.broadcast_object_list(pickle.dumps(trainer.args), src=0)
+ trainer.train(resume_from_checkpoint=None)
+ else:
+ trainer.train(resume_from_checkpoint=None, trial=run.run)
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+ run.log_metric("objective", trainer.objective)
+
+ best = list(experiment.get_best_runs())[0]
+ best_run = BestRun(best.id, best.values["objective"].value, best.assignments)
+ else:
+ from sigopt import Connection
+
+ conn = Connection()
+ proxies = kwargs.pop("proxies", None)
+ if proxies is not None:
+ conn.set_proxies(proxies)
+
+ experiment = conn.experiments().create(
+ name="huggingface-tune",
+ parameters=trainer.hp_space(None),
+ metrics=[{"name": "objective", "objective": direction, "strategy": "optimize"}],
+ parallel_bandwidth=1,
+ observation_budget=n_trials,
+ project="huggingface",
+ )
+ logger.info(f"created experiment: https://app.sigopt.com/experiment/{experiment.id}")
+
+ while experiment.progress.observation_count < experiment.observation_budget:
+ suggestion = conn.experiments(experiment.id).suggestions().create()
+ trainer.objective = None
+ if trainer.args.world_size > 1:
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
+ raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.")
+ trainer._hp_search_setup(suggestion)
+ torch.distributed.broadcast_object_list(pickle.dumps(trainer.args), src=0)
+ trainer.train(resume_from_checkpoint=None)
+ else:
+ trainer.train(resume_from_checkpoint=None, trial=suggestion)
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+
+ values = [{"name": "objective", "value": trainer.objective}]
+ obs = conn.experiments(experiment.id).observations().create(suggestion=suggestion.id, values=values)
+ logger.info(f"[suggestion_id, observation_id]: [{suggestion.id}, {obs.id}]")
+ experiment = conn.experiments(experiment.id).fetch()
+
+ best = list(conn.experiments(experiment.id).best_assignments().fetch().iterate_pages())[0]
+ best_run = BestRun(best.id, best.value, best.assignments)
+ return best_run
+ else:
+ for i in range(n_trials):
+ trainer.objective = None
+ args_main_rank = list(pickle.dumps(trainer.args))
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
+ raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.")
+ torch.distributed.broadcast_object_list(args_main_rank, src=0)
+ args = pickle.loads(bytes(args_main_rank))
+ for key, value in asdict(args).items():
+ if key != "local_rank":
+ setattr(trainer.args, key, value)
+ trainer.train(resume_from_checkpoint=None)
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+ return None
+
+
+def run_hp_search_wandb(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
+ from ..integrations import is_wandb_available
+
+ if not is_wandb_available():
+ raise ImportError("This function needs wandb installed: `pip install wandb`")
+ import wandb
+
+ # add WandbCallback if not already added in trainer callbacks
+ reporting_to_wandb = False
+ for callback in trainer.callback_handler.callbacks:
+ if isinstance(callback, WandbCallback):
+ reporting_to_wandb = True
+ break
+ if not reporting_to_wandb:
+ trainer.add_callback(WandbCallback())
+ trainer.args.report_to = ["wandb"]
+ best_trial = {"run_id": None, "objective": None, "hyperparameters": None}
+ sweep_id = kwargs.pop("sweep_id", None)
+ project = kwargs.pop("project", None)
+ name = kwargs.pop("name", None)
+ entity = kwargs.pop("entity", None)
+ metric = kwargs.pop("metric", "eval/loss")
+
+ sweep_config = trainer.hp_space(None)
+ sweep_config["metric"]["goal"] = direction
+ sweep_config["metric"]["name"] = metric
+ if name:
+ sweep_config["name"] = name
+
+ def _objective():
+ run = wandb.run if wandb.run else wandb.init()
+ trainer.state.trial_name = run.name
+ run.config.update({"assignments": {}, "metric": metric})
+ config = wandb.config
+
+ trainer.objective = None
+
+ trainer.train(resume_from_checkpoint=None, trial=vars(config)["_items"])
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+ format_metrics = rewrite_logs(metrics)
+ if metric not in format_metrics:
+ logger.warning(
+ f"Provided metric {metric} not found. This might result in unexpected sweeps charts. The available"
+ f" metrics are {format_metrics.keys()}"
+ )
+ best_score = False
+ if best_trial["run_id"] is not None:
+ if direction == "minimize":
+ best_score = trainer.objective < best_trial["objective"]
+ elif direction == "maximize":
+ best_score = trainer.objective > best_trial["objective"]
+
+ if best_score or best_trial["run_id"] is None:
+ best_trial["run_id"] = run.id
+ best_trial["objective"] = trainer.objective
+ best_trial["hyperparameters"] = dict(config)
+
+ return trainer.objective
+
+ sweep_id = wandb.sweep(sweep_config, project=project, entity=entity) if not sweep_id else sweep_id
+ logger.info(f"wandb sweep id - {sweep_id}")
+ wandb.agent(sweep_id, function=_objective, count=n_trials)
+
+ return BestRun(best_trial["run_id"], best_trial["objective"], best_trial["hyperparameters"])
+
+
+def get_available_reporting_integrations():
+ integrations = []
+ if is_azureml_available() and not is_mlflow_available():
+ integrations.append("azure_ml")
+ if is_comet_available():
+ integrations.append("comet_ml")
+ if is_dagshub_available():
+ integrations.append("dagshub")
+ if is_dvclive_available():
+ integrations.append("dvclive")
+ if is_mlflow_available():
+ integrations.append("mlflow")
+ if is_neptune_available():
+ integrations.append("neptune")
+ if is_tensorboard_available():
+ integrations.append("tensorboard")
+ if is_wandb_available():
+ integrations.append("wandb")
+ if is_codecarbon_available():
+ integrations.append("codecarbon")
+ if is_clearml_available():
+ integrations.append("clearml")
+ return integrations
+
+
+def rewrite_logs(d):
+ new_d = {}
+ eval_prefix = "eval_"
+ eval_prefix_len = len(eval_prefix)
+ test_prefix = "test_"
+ test_prefix_len = len(test_prefix)
+ for k, v in d.items():
+ if k.startswith(eval_prefix):
+ new_d["eval/" + k[eval_prefix_len:]] = v
+ elif k.startswith(test_prefix):
+ new_d["test/" + k[test_prefix_len:]] = v
+ else:
+ new_d["train/" + k] = v
+ return new_d
+
+
+class TensorBoardCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [TensorBoard](https://www.tensorflow.org/tensorboard).
+
+ Args:
+ tb_writer (`SummaryWriter`, *optional*):
+ The writer to use. Will instantiate one if not set.
+ """
+
+ def __init__(self, tb_writer=None):
+ has_tensorboard = is_tensorboard_available()
+ if not has_tensorboard:
+ raise RuntimeError(
+ "TensorBoardCallback requires tensorboard to be installed. Either update your PyTorch version or"
+ " install tensorboardX."
+ )
+ if has_tensorboard:
+ try:
+ from torch.utils.tensorboard import SummaryWriter # noqa: F401
+
+ self._SummaryWriter = SummaryWriter
+ except ImportError:
+ try:
+ from tensorboardX import SummaryWriter
+
+ self._SummaryWriter = SummaryWriter
+ except ImportError:
+ self._SummaryWriter = None
+ else:
+ self._SummaryWriter = None
+ self.tb_writer = tb_writer
+
+ def _init_summary_writer(self, args, log_dir=None):
+ log_dir = log_dir or args.logging_dir
+ if self._SummaryWriter is not None:
+ self.tb_writer = self._SummaryWriter(log_dir=log_dir)
+
+ def on_train_begin(self, args, state, control, **kwargs):
+ if not state.is_world_process_zero:
+ return
+
+ log_dir = None
+
+ if state.is_hyper_param_search:
+ trial_name = state.trial_name
+ if trial_name is not None:
+ log_dir = os.path.join(args.logging_dir, trial_name)
+
+ if self.tb_writer is None:
+ self._init_summary_writer(args, log_dir)
+
+ if self.tb_writer is not None:
+ self.tb_writer.add_text("args", args.to_json_string())
+ if "model" in kwargs:
+ model = kwargs["model"]
+ if hasattr(model, "config") and model.config is not None:
+ model_config_json = model.config.to_json_string()
+ self.tb_writer.add_text("model_config", model_config_json)
+
+ def on_log(self, args, state, control, logs=None, **kwargs):
+ if not state.is_world_process_zero:
+ return
+
+ if self.tb_writer is None:
+ self._init_summary_writer(args)
+
+ if self.tb_writer is not None:
+ logs = rewrite_logs(logs)
+ for k, v in logs.items():
+ if isinstance(v, (int, float)):
+ self.tb_writer.add_scalar(k, v, state.global_step)
+ elif isinstance(v, str):
+ self.tb_writer.add_text(k, v, state.global_step)
+ else:
+ logger.warning(
+ "Trainer is attempting to log a value of "
+ f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
+ "This invocation of Tensorboard's writer.add_scalar() "
+ "is incorrect so we dropped this attribute."
+ )
+ self.tb_writer.flush()
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self.tb_writer:
+ self.tb_writer.close()
+ self.tb_writer = None
+
+
+def save_model_architecture_to_file(model: Any, output_dir: str):
+ with open(f"{output_dir}/model_architecture.txt", "w+") as f:
+ if isinstance(model, PreTrainedModel):
+ print(model, file=f)
+ elif is_tf_available() and isinstance(model, TFPreTrainedModel):
+
+ def print_to_file(s):
+ print(s, file=f)
+
+ model.summary(print_fn=print_to_file)
+ elif is_torch_available() and (
+ isinstance(model, (torch.nn.Module, PushToHubMixin)) and hasattr(model, "base_model")
+ ):
+ print(model, file=f)
+
+
+class WandbLogModel(str, Enum):
+ """Enum of possible log model values in W&B."""
+
+ CHECKPOINT = "checkpoint"
+ END = "end"
+ FALSE = "false"
+
+ @property
+ def is_enabled(self) -> bool:
+ """Check if the value corresponds to a state where the `WANDB_LOG_MODEL` setting is enabled."""
+ return self in (WandbLogModel.CHECKPOINT, WandbLogModel.END)
+
+ @classmethod
+ def _missing_(cls, value: Any) -> "WandbLogModel":
+ if not isinstance(value, str):
+ raise ValueError(f"Expecting to have a string `WANDB_LOG_MODEL` setting, but got {type(value)}")
+ if value.upper() in ENV_VARS_TRUE_VALUES:
+ raise DeprecationWarning(
+ f"Setting `WANDB_LOG_MODEL` as {os.getenv('WANDB_LOG_MODEL')} is deprecated and will be removed in "
+ "version 5 of transformers. Use one of `'end'` or `'checkpoint'` instead."
+ )
+ logger.info(f"Setting `WANDB_LOG_MODEL` from {os.getenv('WANDB_LOG_MODEL')} to `end` instead")
+ return WandbLogModel.END
+ logger.warning(
+ f"Received unrecognized `WANDB_LOG_MODEL` setting value={value}; so disabling `WANDB_LOG_MODEL`"
+ )
+ return WandbLogModel.FALSE
+
+
+class WandbCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that logs metrics, media, model checkpoints to [Weight and Biases](https://www.wandb.com/).
+ """
+
+ def __init__(self):
+ has_wandb = is_wandb_available()
+ if not has_wandb:
+ raise RuntimeError("WandbCallback requires wandb to be installed. Run `pip install wandb`.")
+ if has_wandb:
+ import wandb
+
+ self._wandb = wandb
+ self._initialized = False
+ self._log_model = WandbLogModel(os.getenv("WANDB_LOG_MODEL", "false"))
+
+ 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/guides/integrations/huggingface). You can also override the following environment
+ variables:
+
+ Environment:
+ - **WANDB_LOG_MODEL** (`str`, *optional*, defaults to `"false"`):
+ Whether to log model and checkpoints during training. Can be `"end"`, `"checkpoint"` or `"false"`. If set
+ to `"end"`, the model will be uploaded at the end of training. If set to `"checkpoint"`, the checkpoint
+ will be uploaded every `args.save_steps` . If set to `"false"`, the model will not be uploaded. Use along
+ with [`~transformers.TrainingArguments.load_best_model_at_end`] to upload best model.
+
+
+
+ Setting `WANDB_LOG_MODEL` as `bool` will be deprecated in version 5 of 🤗 Transformers.
+
+
+ - **WANDB_WATCH** (`str`, *optional* defaults to `"false"`):
+ Can be `"gradients"`, `"all"`, `"parameters"`, or `"false"`. Set to `"all"` to log gradients and
+ parameters.
+ - **WANDB_PROJECT** (`str`, *optional*, defaults to `"huggingface"`):
+ Set this to a custom string to store results in a different project.
+ - **WANDB_DISABLED** (`bool`, *optional*, defaults to `False`):
+ Whether to disable wandb entirely. Set `WANDB_DISABLED=true` to disable.
+ """
+ if self._wandb is None:
+ return
+ self._initialized = True
+
+ # prepare to handle potential configuration issues during setup
+ from wandb.sdk.lib.config_util import ConfigError as WandbConfigError
+
+ if state.is_world_process_zero:
+ logger.info(
+ 'Automatic Weights & Biases logging enabled, to disable set os.environ["WANDB_DISABLED"] = "true"'
+ )
+ combined_dict = {**args.to_dict()}
+
+ if hasattr(model, "config") and model.config is not None:
+ model_config = model.config if isinstance(model.config, dict) else model.config.to_dict()
+ combined_dict = {**model_config, **combined_dict}
+ if hasattr(model, "peft_config") and model.peft_config is not None:
+ peft_config = model.peft_config
+ combined_dict = {**{"peft_config": peft_config}, **combined_dict}
+ trial_name = state.trial_name
+ init_args = {}
+ if trial_name is not None:
+ init_args["name"] = trial_name
+ init_args["group"] = args.run_name
+ elif args.run_name is not None:
+ init_args["name"] = args.run_name
+ if args.run_name == args.output_dir:
+ self._wandb.termwarn(
+ "The `run_name` is currently set to the same value as `TrainingArguments.output_dir`. If this was "
+ "not intended, please specify a different run name by setting the `TrainingArguments.run_name` parameter.",
+ repeat=False,
+ )
+
+ if self._wandb.run is None:
+ self._wandb.init(
+ project=os.getenv("WANDB_PROJECT", "huggingface"),
+ **init_args,
+ )
+ # add config parameters (run may have been created manually)
+ self._wandb.config.update(combined_dict, allow_val_change=True)
+
+ # define default x-axis (for latest wandb versions)
+ if getattr(self._wandb, "define_metric", None):
+ self._wandb.define_metric("train/global_step")
+ self._wandb.define_metric("*", step_metric="train/global_step", step_sync=True)
+
+ # keep track of model topology and gradients, unsupported on TPU
+ _watch_model = os.getenv("WANDB_WATCH", "false")
+ if not is_torch_xla_available() and _watch_model in ("all", "parameters", "gradients"):
+ self._wandb.watch(model, log=_watch_model, log_freq=max(100, state.logging_steps))
+ self._wandb.run._label(code="transformers_trainer")
+
+ # add number of model parameters to wandb config
+ try:
+ self._wandb.config["model/num_parameters"] = model.num_parameters()
+ except AttributeError:
+ logger.info(
+ "Could not log the number of model parameters in Weights & Biases due to an AttributeError."
+ )
+ except WandbConfigError:
+ logger.warning(
+ "A ConfigError was raised whilst setting the number of model parameters in Weights & Biases config."
+ )
+
+ # log the initial model architecture to an artifact
+ if self._log_model.is_enabled:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ model_name = (
+ f"model-{self._wandb.run.id}"
+ if (args.run_name is None or args.run_name == args.output_dir)
+ else f"model-{self._wandb.run.name}"
+ )
+ model_artifact = self._wandb.Artifact(
+ name=model_name,
+ type="model",
+ metadata={
+ "model_config": model.config.to_dict() if hasattr(model, "config") else None,
+ "num_parameters": self._wandb.config.get("model/num_parameters"),
+ "initial_model": True,
+ },
+ )
+ # add the architecture to a separate text file
+ save_model_architecture_to_file(model, temp_dir)
+
+ for f in Path(temp_dir).glob("*"):
+ if f.is_file():
+ with model_artifact.new_file(f.name, mode="wb") as fa:
+ fa.write(f.read_bytes())
+ self._wandb.run.log_artifact(model_artifact, aliases=["base_model"])
+
+ badge_markdown = (
+ f'[
]({self._wandb.run.get_url()})'
+ )
+
+ modelcard.AUTOGENERATED_TRAINER_COMMENT += f"\n{badge_markdown}"
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if self._wandb is None:
+ return
+ hp_search = state.is_hyper_param_search
+ if hp_search:
+ self._wandb.finish()
+ self._initialized = False
+ args.run_name = None
+ if not self._initialized:
+ self.setup(args, state, model, **kwargs)
+
+ def on_train_end(self, args, state, control, model=None, processing_class=None, **kwargs):
+ if self._wandb is None:
+ return
+ if self._log_model.is_enabled and self._initialized and state.is_world_process_zero:
+ from ..trainer import Trainer
+
+ fake_trainer = Trainer(args=args, model=model, processing_class=processing_class, eval_dataset=["fake"])
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fake_trainer.save_model(temp_dir)
+ metadata = (
+ {
+ k: v
+ for k, v in dict(self._wandb.summary).items()
+ if isinstance(v, numbers.Number) and not k.startswith("_")
+ }
+ if not args.load_best_model_at_end
+ else {
+ f"eval/{args.metric_for_best_model}": state.best_metric,
+ "train/total_floss": state.total_flos,
+ "model/num_parameters": self._wandb.config.get("model/num_parameters"),
+ }
+ )
+ metadata["final_model"] = True
+ logger.info("Logging model artifacts. ...")
+ model_name = (
+ f"model-{self._wandb.run.id}"
+ if (args.run_name is None or args.run_name == args.output_dir)
+ else f"model-{self._wandb.run.name}"
+ )
+ # add the model architecture to a separate text file
+ save_model_architecture_to_file(model, temp_dir)
+
+ artifact = self._wandb.Artifact(name=model_name, type="model", metadata=metadata)
+ for f in Path(temp_dir).glob("*"):
+ if f.is_file():
+ with artifact.new_file(f.name, mode="wb") as fa:
+ fa.write(f.read_bytes())
+ self._wandb.run.log_artifact(artifact, aliases=["final_model"])
+
+ def on_log(self, args, state, control, model=None, logs=None, **kwargs):
+ single_value_scalars = [
+ "train_runtime",
+ "train_samples_per_second",
+ "train_steps_per_second",
+ "train_loss",
+ "total_flos",
+ ]
+
+ if self._wandb is None:
+ return
+ if not self._initialized:
+ self.setup(args, state, model)
+ if state.is_world_process_zero:
+ for k, v in logs.items():
+ if k in single_value_scalars:
+ self._wandb.run.summary[k] = v
+ non_scalar_logs = {k: v for k, v in logs.items() if k not in single_value_scalars}
+ non_scalar_logs = rewrite_logs(non_scalar_logs)
+ self._wandb.log({**non_scalar_logs, "train/global_step": state.global_step})
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._log_model == WandbLogModel.CHECKPOINT and self._initialized and state.is_world_process_zero:
+ checkpoint_metadata = {
+ k: v
+ for k, v in dict(self._wandb.summary).items()
+ if isinstance(v, numbers.Number) and not k.startswith("_")
+ }
+ checkpoint_metadata["model/num_parameters"] = self._wandb.config.get("model/num_parameters")
+
+ ckpt_dir = f"checkpoint-{state.global_step}"
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
+ logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. ...")
+ checkpoint_name = (
+ f"model-{self._wandb.run.id}"
+ if (args.run_name is None or args.run_name == args.output_dir)
+ else f"model-{self._wandb.run.name}"
+ )
+ artifact = self._wandb.Artifact(name=checkpoint_name, type="model", metadata=checkpoint_metadata)
+ artifact.add_dir(artifact_path)
+ self._wandb.log_artifact(
+ artifact, aliases=[f"epoch_{round(state.epoch, 2)}", f"checkpoint_global_step_{state.global_step}"]
+ )
+
+ def on_predict(self, args, state, control, metrics, **kwargs):
+ if self._wandb is None:
+ return
+ if not self._initialized:
+ self.setup(args, state, **kwargs)
+ if state.is_world_process_zero:
+ metrics = rewrite_logs(metrics)
+ self._wandb.log(metrics)
+
+
+class CometCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [Comet ML](https://www.comet.com/site/).
+ """
+
+ def __init__(self):
+ if _is_comet_installed is False or _is_comet_recent_enough is False:
+ raise RuntimeError(
+ f"CometCallback requires comet-ml>={_MIN_COMET_VERSION} to be installed. Run `pip install comet-ml>={_MIN_COMET_VERSION}`."
+ )
+ self._initialized = False
+ self._log_assets = False
+ self._experiment = None
+
+ 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 accepts the following values:
+ * `get_or_create`: Decides automatically depending if
+ `COMET_EXPERIMENT_KEY` is set and whether an Experiment
+ with that key already exists or not.
+ * `create`: Always create a new Comet Experiment.
+ * `get`: Always try to append to an Existing Comet Experiment.
+ Requires `COMET_EXPERIMENT_KEY` to be set.
+ * `ONLINE`: **deprecated**, used to create an online
+ Experiment. Use `COMET_START_ONLINE=1` instead.
+ * `OFFLINE`: **deprecated**, used to created an offline
+ Experiment. Use `COMET_START_ONLINE=0` instead.
+ * `DISABLED`: **deprecated**, used to disable Comet logging.
+ Use the `--report_to` flag to control the integrations used
+ for logging result instead.
+ - **COMET_PROJECT_NAME** (`str`, *optional*):
+ Comet project name for experiments.
+ - **COMET_LOG_ASSETS** (`str`, *optional*, defaults to `TRUE`):
+ Whether or not to log training assets (tf event logs, checkpoints, etc), to Comet. Can be `TRUE`, or
+ `FALSE`.
+
+ For a number of configurable items in the environment, see
+ [here](https://www.comet.com/docs/v2/guides/experiment-management/configure-sdk/#explore-comet-configuration-options).
+ """
+ self._initialized = True
+ log_assets = os.getenv("COMET_LOG_ASSETS", "FALSE").upper()
+ if log_assets in {"TRUE", "1"}:
+ self._log_assets = True
+ if state.is_world_process_zero:
+ comet_old_mode = os.getenv("COMET_MODE")
+
+ mode = None
+ online = None
+
+ if comet_old_mode is not None:
+ comet_old_mode = comet_old_mode.lower()
+
+ if comet_old_mode == "online":
+ online = True
+ elif comet_old_mode == "offline":
+ online = False
+ elif comet_old_mode in ("get", "get_or_create", "create"):
+ mode = comet_old_mode
+ elif comet_old_mode:
+ logger.warning("Invalid COMET_MODE env value %r, Comet logging is disabled", comet_old_mode)
+ return
+
+ # For HPO, we always create a new experiment for each trial
+ if state.is_hyper_param_search:
+ if mode is not None:
+ logger.warning(
+ "Hyperparameter Search is enabled, forcing the creation of new experimetns, COMET_MODE value %r is ignored",
+ comet_old_mode,
+ )
+ mode = "create"
+
+ import comet_ml
+
+ # Do not use the default run_name as the experiment name
+ if args.run_name is not None and args.run_name != args.output_dir:
+ experiment_config = comet_ml.ExperimentConfig(name=args.run_name)
+ else:
+ experiment_config = comet_ml.ExperimentConfig()
+
+ self._experiment = comet_ml.start(online=online, mode=mode, experiment_config=experiment_config)
+ self._experiment.__internal_api__set_model_graph__(model, framework="transformers")
+
+ params = {"args": args.to_dict()}
+
+ if hasattr(model, "config") and model.config is not None:
+ model_config = model.config.to_dict()
+ params["config"] = model_config
+ if hasattr(model, "peft_config") and model.peft_config is not None:
+ peft_config = model.peft_config
+ params["peft_config"] = peft_config
+
+ self._experiment.__internal_api__log_parameters__(
+ params, framework="transformers", source="manual", flatten_nested=True
+ )
+
+ if state.is_hyper_param_search:
+ optimization_id = getattr(state, "trial_name", None)
+ optimization_params = getattr(state, "trial_params", None)
+
+ self._experiment.log_optimization(optimization_id=optimization_id, parameters=optimization_params)
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+
+ def on_log(self, args, state, control, model=None, logs=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+ if state.is_world_process_zero:
+ if self._experiment is not None:
+ rewritten_logs = rewrite_logs(logs)
+ self._experiment.__internal_api__log_metrics__(
+ rewritten_logs, step=state.global_step, epoch=state.epoch, framework="transformers"
+ )
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self._initialized and state.is_world_process_zero:
+ if self._experiment is not None:
+ if self._log_assets is True:
+ logger.info("Logging checkpoints. This may take time.")
+ self._experiment.log_asset_folder(
+ args.output_dir, recursive=True, log_file_name=True, step=state.global_step
+ )
+
+ # We create one experiment per trial in HPO mode
+ if state.is_hyper_param_search:
+ self._experiment.clean()
+ self._initialized = False
+
+ def on_predict(self, args, state, control, metrics, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model=None)
+ if state.is_world_process_zero and self._experiment is not None:
+ rewritten_metrics = rewrite_logs(metrics)
+ self._experiment.__internal_api__log_metrics__(
+ rewritten_metrics, step=state.global_step, epoch=state.epoch, framework="transformers"
+ )
+
+
+class AzureMLCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [AzureML](https://pypi.org/project/azureml-sdk/).
+ """
+
+ def __init__(self, azureml_run=None):
+ if not is_azureml_available():
+ raise RuntimeError("AzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`.")
+ self.azureml_run = azureml_run
+
+ def on_init_end(self, args, state, control, **kwargs):
+ from azureml.core.run import Run
+
+ if self.azureml_run is None and state.is_world_process_zero:
+ self.azureml_run = Run.get_context()
+
+ def on_log(self, args, state, control, logs=None, **kwargs):
+ if self.azureml_run and state.is_world_process_zero:
+ for k, v in logs.items():
+ if isinstance(v, (int, float)):
+ self.azureml_run.log(k, v, description=k)
+
+
+class MLflowCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [MLflow](https://www.mlflow.org/). Can be disabled by setting
+ environment variable `DISABLE_MLFLOW_INTEGRATION = TRUE`.
+ """
+
+ def __init__(self):
+ if not is_mlflow_available():
+ raise RuntimeError("MLflowCallback requires mlflow to be installed. Run `pip install mlflow`.")
+ import mlflow
+
+ self._MAX_PARAM_VAL_LENGTH = mlflow.utils.validation.MAX_PARAM_VAL_LENGTH
+ self._MAX_PARAMS_TAGS_PER_BATCH = mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH
+
+ self._initialized = False
+ self._auto_end_run = False
+ self._log_artifacts = False
+ self._ml_flow = mlflow
+
+ 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, e.g. s3 or GCS. If set to `True` or *1*, will copy each saved checkpoint on each save in
+ [`TrainingArguments`]'s `output_dir` to the local or remote artifact storage. Using it without a remote
+ storage will just copy the files to your artifact location.
+ - **MLFLOW_TRACKING_URI** (`str`, *optional*):
+ Whether to store runs at a specific path or remote server. Unset by default, which skips setting the
+ tracking URI entirely.
+ - **MLFLOW_EXPERIMENT_NAME** (`str`, *optional*, defaults to `None`):
+ Whether to use an MLflow experiment_name under which to launch the run. Default to `None` which will point
+ to the `Default` experiment in MLflow. Otherwise, it is a case sensitive name of the experiment to be
+ activated. If an experiment with this name does not exist, a new experiment with this name is created.
+ - **MLFLOW_TAGS** (`str`, *optional*):
+ A string dump of a dictionary of key/value pair to be added to the MLflow run as tags. Example:
+ `os.environ['MLFLOW_TAGS']='{"release.candidate": "RC1", "release.version": "2.2.0"}'`.
+ - **MLFLOW_NESTED_RUN** (`str`, *optional*):
+ Whether to use MLflow nested runs. If set to `True` or *1*, will create a nested run inside the current
+ run.
+ - **MLFLOW_RUN_ID** (`str`, *optional*):
+ Allow to reattach to an existing run which can be usefull when resuming training from a checkpoint. When
+ `MLFLOW_RUN_ID` environment variable is set, `start_run` attempts to resume a run with the specified run ID
+ and other parameters are ignored.
+ - **MLFLOW_FLATTEN_PARAMS** (`str`, *optional*, defaults to `False`):
+ Whether to flatten the parameters dictionary before logging.
+ - **MLFLOW_MAX_LOG_PARAMS** (`int`, *optional*):
+ Set the maximum number of parameters to log in the run.
+ """
+ self._log_artifacts = os.getenv("HF_MLFLOW_LOG_ARTIFACTS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
+ self._nested_run = os.getenv("MLFLOW_NESTED_RUN", "FALSE").upper() in ENV_VARS_TRUE_VALUES
+ self._tracking_uri = os.getenv("MLFLOW_TRACKING_URI", None)
+ self._experiment_name = os.getenv("MLFLOW_EXPERIMENT_NAME", None)
+ self._flatten_params = os.getenv("MLFLOW_FLATTEN_PARAMS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
+ self._run_id = os.getenv("MLFLOW_RUN_ID", None)
+ self._max_log_params = os.getenv("MLFLOW_MAX_LOG_PARAMS", None)
+
+ # "synchronous" flag is only available with mlflow version >= 2.8.0
+ # https://github.com/mlflow/mlflow/pull/9705
+ # https://github.com/mlflow/mlflow/releases/tag/v2.8.0
+ self._async_log = packaging.version.parse(self._ml_flow.__version__) >= packaging.version.parse("2.8.0")
+
+ logger.debug(
+ f"MLflow experiment_name={self._experiment_name}, run_name={args.run_name}, nested={self._nested_run},"
+ f" tracking_uri={self._tracking_uri}"
+ )
+ if state.is_world_process_zero:
+ if not self._ml_flow.is_tracking_uri_set():
+ if self._tracking_uri:
+ self._ml_flow.set_tracking_uri(self._tracking_uri)
+ logger.debug(f"MLflow tracking URI is set to {self._tracking_uri}")
+ else:
+ logger.debug(
+ "Environment variable `MLFLOW_TRACKING_URI` is not provided and therefore will not be"
+ " explicitly set."
+ )
+ else:
+ logger.debug(f"MLflow tracking URI is set to {self._ml_flow.get_tracking_uri()}")
+
+ if self._ml_flow.active_run() is None or self._nested_run or self._run_id:
+ if self._experiment_name:
+ # Use of set_experiment() ensure that Experiment is created if not exists
+ self._ml_flow.set_experiment(self._experiment_name)
+ self._ml_flow.start_run(run_name=args.run_name, nested=self._nested_run)
+ logger.debug(f"MLflow run started with run_id={self._ml_flow.active_run().info.run_id}")
+ self._auto_end_run = True
+ combined_dict = args.to_dict()
+ if hasattr(model, "config") and model.config is not None:
+ model_config = model.config.to_dict()
+ combined_dict = {**model_config, **combined_dict}
+ combined_dict = flatten_dict(combined_dict) if self._flatten_params else combined_dict
+ # remove params that are too long for MLflow
+ for name, value in list(combined_dict.items()):
+ # internally, all values are converted to str in MLflow
+ if len(str(value)) > self._MAX_PARAM_VAL_LENGTH:
+ logger.warning(
+ f'Trainer is attempting to log a value of "{value}" for key "{name}" as a parameter. MLflow\'s'
+ " log_param() only accepts values no longer than 250 characters so we dropped this attribute."
+ " You can use `MLFLOW_FLATTEN_PARAMS` environment variable to flatten the parameters and"
+ " avoid this message."
+ )
+ del combined_dict[name]
+ # MLflow cannot log more than 100 values in one go, so we have to split it
+ combined_dict_items = list(combined_dict.items())
+ if self._max_log_params and self._max_log_params.isdigit():
+ max_log_params = int(self._max_log_params)
+ if max_log_params < len(combined_dict_items):
+ logger.debug(
+ f"Reducing the number of parameters to log from {len(combined_dict_items)} to {max_log_params}."
+ )
+ combined_dict_items = combined_dict_items[:max_log_params]
+ for i in range(0, len(combined_dict_items), self._MAX_PARAMS_TAGS_PER_BATCH):
+ if self._async_log:
+ self._ml_flow.log_params(
+ dict(combined_dict_items[i : i + self._MAX_PARAMS_TAGS_PER_BATCH]), synchronous=False
+ )
+ else:
+ self._ml_flow.log_params(dict(combined_dict_items[i : i + self._MAX_PARAMS_TAGS_PER_BATCH]))
+ mlflow_tags = os.getenv("MLFLOW_TAGS", None)
+ if mlflow_tags:
+ mlflow_tags = json.loads(mlflow_tags)
+ self._ml_flow.set_tags(mlflow_tags)
+ self._initialized = True
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+
+ def on_log(self, args, state, control, logs, model=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+ if state.is_world_process_zero:
+ metrics = {}
+ for k, v in logs.items():
+ if isinstance(v, (int, float)):
+ metrics[k] = v
+ elif isinstance(v, torch.Tensor) and v.numel() == 1:
+ metrics[k] = v.item()
+ else:
+ logger.warning(
+ f'Trainer is attempting to log a value of "{v}" of type {type(v)} for key "{k}" as a metric. '
+ "MLflow's log_metric() only accepts float and int types so we dropped this attribute."
+ )
+
+ if self._async_log:
+ self._ml_flow.log_metrics(metrics=metrics, step=state.global_step, synchronous=False)
+ else:
+ self._ml_flow.log_metrics(metrics=metrics, step=state.global_step)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self._initialized and state.is_world_process_zero:
+ if self._auto_end_run and self._ml_flow.active_run():
+ self._ml_flow.end_run()
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._initialized and state.is_world_process_zero and self._log_artifacts:
+ ckpt_dir = f"checkpoint-{state.global_step}"
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
+ logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. This may take time.")
+ self._ml_flow.pyfunc.log_model(
+ ckpt_dir,
+ artifacts={"model_path": artifact_path},
+ python_model=self._ml_flow.pyfunc.PythonModel(),
+ )
+
+ def __del__(self):
+ # if the previous run is not terminated correctly, the fluent API will
+ # not let you start a new run before the previous one is killed
+ if (
+ self._auto_end_run
+ and callable(getattr(self._ml_flow, "active_run", None))
+ and self._ml_flow.active_run() is not None
+ ):
+ self._ml_flow.end_run()
+
+
+class DagsHubCallback(MLflowCallback):
+ """
+ A [`TrainerCallback`] that logs to [DagsHub](https://dagshub.com/). Extends [`MLflowCallback`]
+ """
+
+ def __init__(self):
+ super().__init__()
+ if not is_dagshub_available():
+ raise ImportError("DagsHubCallback requires dagshub to be installed. Run `pip install dagshub`.")
+
+ from dagshub.upload import Repo
+
+ self.Repo = Repo
+
+ def setup(self, *args, **kwargs):
+ """
+ Setup the DagsHub's Logging integration.
+
+ Environment:
+ - **HF_DAGSHUB_LOG_ARTIFACTS** (`str`, *optional*):
+ Whether to save the data and model artifacts for the experiment. Default to `False`.
+ """
+
+ self.log_artifacts = os.getenv("HF_DAGSHUB_LOG_ARTIFACTS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
+ self.name = os.getenv("HF_DAGSHUB_MODEL_NAME") or "main"
+ self.remote = os.getenv("MLFLOW_TRACKING_URI")
+ self.repo = self.Repo(
+ owner=self.remote.split(os.sep)[-2],
+ name=self.remote.split(os.sep)[-1].split(".")[0],
+ branch=os.getenv("BRANCH") or "main",
+ )
+ self.path = Path("artifacts")
+
+ if self.remote is None:
+ raise RuntimeError(
+ "DagsHubCallback requires the `MLFLOW_TRACKING_URI` environment variable to be set. Did you run"
+ " `dagshub.init()`?"
+ )
+
+ super().setup(*args, **kwargs)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self.log_artifacts:
+ if getattr(self, "train_dataloader", None):
+ torch.save(self.train_dataloader.dataset, os.path.join(args.output_dir, "dataset.pt"))
+
+ self.repo.directory(str(self.path)).add_dir(args.output_dir)
+
+
+class NeptuneMissingConfiguration(Exception):
+ def __init__(self):
+ super().__init__(
+ """
+ ------ Unsupported ---- We were not able to create new runs. You provided a custom Neptune run to
+ `NeptuneCallback` with the `run` argument. For the integration to work fully, provide your `api_token` and
+ `project` by saving them as environment variables or passing them to the callback.
+ """
+ )
+
+
+class NeptuneCallback(TrainerCallback):
+ """TrainerCallback that sends the logs to [Neptune](https://app.neptune.ai).
+
+ Args:
+ api_token (`str`, *optional*): Neptune API token obtained upon registration.
+ You can leave this argument out if you have saved your token to the `NEPTUNE_API_TOKEN` environment
+ variable (strongly recommended). See full setup instructions in the
+ [docs](https://docs.neptune.ai/setup/installation).
+ project (`str`, *optional*): Name of an existing Neptune project, in the form "workspace-name/project-name".
+ You can find and copy the name in Neptune from the project settings -> Properties. If None (default), the
+ value of the `NEPTUNE_PROJECT` environment variable is used.
+ name (`str`, *optional*): Custom name for the run.
+ base_namespace (`str`, *optional*, defaults to "finetuning"): In the Neptune run, the root namespace
+ that will contain all of the metadata logged by the callback.
+ log_parameters (`bool`, *optional*, defaults to `True`):
+ If True, logs all Trainer arguments and model parameters provided by the Trainer.
+ log_checkpoints (`str`, *optional*): If "same", uploads checkpoints whenever they are saved by the Trainer.
+ If "last", uploads only the most recently saved checkpoint. If "best", uploads the best checkpoint (among
+ the ones saved by the Trainer). If `None`, does not upload checkpoints.
+ run (`Run`, *optional*): Pass a Neptune run object if you want to continue logging to an existing run.
+ Read more about resuming runs in the [docs](https://docs.neptune.ai/logging/to_existing_object).
+ **neptune_run_kwargs (*optional*):
+ Additional keyword arguments to be passed directly to the
+ [`neptune.init_run()`](https://docs.neptune.ai/api/neptune#init_run) function when a new run is created.
+
+ For instructions and examples, see the [Transformers integration
+ guide](https://docs.neptune.ai/integrations/transformers) in the Neptune documentation.
+ """
+
+ integration_version_key = "source_code/integrations/transformers"
+ model_parameters_key = "model_parameters"
+ trial_name_key = "trial"
+ trial_params_key = "trial_params"
+ trainer_parameters_key = "trainer_parameters"
+ flat_metrics = {"train/epoch"}
+
+ def __init__(
+ self,
+ *,
+ api_token: Optional[str] = None,
+ project: Optional[str] = None,
+ name: Optional[str] = None,
+ base_namespace: str = "finetuning",
+ run=None,
+ log_parameters: bool = True,
+ log_checkpoints: Optional[str] = None,
+ **neptune_run_kwargs,
+ ):
+ if not is_neptune_available():
+ raise ValueError(
+ "NeptuneCallback requires the Neptune client library to be installed. "
+ "To install the library, run `pip install neptune`."
+ )
+
+ try:
+ from neptune import Run
+ from neptune.internal.utils import verify_type
+ except ImportError:
+ from neptune.new.internal.utils import verify_type
+ from neptune.new.metadata_containers.run import Run
+
+ verify_type("api_token", api_token, (str, type(None)))
+ verify_type("project", project, (str, type(None)))
+ verify_type("name", name, (str, type(None)))
+ verify_type("base_namespace", base_namespace, str)
+ verify_type("run", run, (Run, type(None)))
+ verify_type("log_parameters", log_parameters, bool)
+ verify_type("log_checkpoints", log_checkpoints, (str, type(None)))
+
+ self._base_namespace_path = base_namespace
+ self._log_parameters = log_parameters
+ self._log_checkpoints = log_checkpoints
+ self._initial_run: Optional[Run] = run
+
+ self._run = None
+ self._is_monitoring_run = False
+ self._run_id = None
+ self._force_reset_monitoring_run = False
+ self._init_run_kwargs = {"api_token": api_token, "project": project, "name": name, **neptune_run_kwargs}
+
+ self._volatile_checkpoints_dir = None
+ self._should_upload_checkpoint = self._log_checkpoints is not None
+ self._recent_checkpoint_path = None
+
+ if self._log_checkpoints in {"last", "best"}:
+ self._target_checkpoints_namespace = f"checkpoints/{self._log_checkpoints}"
+ self._should_clean_recently_uploaded_checkpoint = True
+ else:
+ self._target_checkpoints_namespace = "checkpoints"
+ self._should_clean_recently_uploaded_checkpoint = False
+
+ def _stop_run_if_exists(self):
+ if self._run:
+ self._run.stop()
+ del self._run
+ self._run = None
+
+ def _initialize_run(self, **additional_neptune_kwargs):
+ try:
+ from neptune import init_run
+ from neptune.exceptions import NeptuneMissingApiTokenException, NeptuneMissingProjectNameException
+ except ImportError:
+ from neptune.new import init_run
+ from neptune.new.exceptions import NeptuneMissingApiTokenException, NeptuneMissingProjectNameException
+
+ self._stop_run_if_exists()
+
+ try:
+ run_params = additional_neptune_kwargs.copy()
+ run_params.update(self._init_run_kwargs)
+ self._run = init_run(**run_params)
+ self._run_id = self._run["sys/id"].fetch()
+ except (NeptuneMissingProjectNameException, NeptuneMissingApiTokenException) as e:
+ raise NeptuneMissingConfiguration() from e
+
+ def _use_initial_run(self):
+ self._run = self._initial_run
+ self._is_monitoring_run = True
+ self._run_id = self._run["sys/id"].fetch()
+ self._initial_run = None
+
+ def _ensure_run_with_monitoring(self):
+ if self._initial_run is not None:
+ self._use_initial_run()
+ else:
+ if not self._force_reset_monitoring_run and self._is_monitoring_run:
+ return
+
+ if self._run and not self._is_monitoring_run and not self._force_reset_monitoring_run:
+ self._initialize_run(with_id=self._run_id)
+ self._is_monitoring_run = True
+ else:
+ self._initialize_run()
+ self._force_reset_monitoring_run = False
+
+ def _ensure_at_least_run_without_monitoring(self):
+ if self._initial_run is not None:
+ self._use_initial_run()
+ else:
+ if not self._run:
+ self._initialize_run(
+ with_id=self._run_id,
+ capture_stdout=False,
+ capture_stderr=False,
+ capture_hardware_metrics=False,
+ capture_traceback=False,
+ )
+ self._is_monitoring_run = False
+
+ @property
+ def run(self):
+ if self._run is None:
+ self._ensure_at_least_run_without_monitoring()
+ return self._run
+
+ @property
+ def _metadata_namespace(self):
+ return self.run[self._base_namespace_path]
+
+ def _log_integration_version(self):
+ self.run[NeptuneCallback.integration_version_key] = version
+
+ def _log_trainer_parameters(self, args):
+ self._metadata_namespace[NeptuneCallback.trainer_parameters_key] = args.to_sanitized_dict()
+
+ def _log_model_parameters(self, model):
+ from neptune.utils import stringify_unsupported
+
+ if model and hasattr(model, "config") and model.config is not None:
+ self._metadata_namespace[NeptuneCallback.model_parameters_key] = stringify_unsupported(
+ model.config.to_dict()
+ )
+
+ def _log_hyper_param_search_parameters(self, state):
+ if state and hasattr(state, "trial_name"):
+ self._metadata_namespace[NeptuneCallback.trial_name_key] = state.trial_name
+
+ if state and hasattr(state, "trial_params") and state.trial_params is not None:
+ self._metadata_namespace[NeptuneCallback.trial_params_key] = state.trial_params
+
+ def _log_model_checkpoint(self, source_directory: str, checkpoint: str):
+ target_path = relative_path = os.path.join(source_directory, checkpoint)
+
+ if self._volatile_checkpoints_dir is not None:
+ consistent_checkpoint_path = os.path.join(self._volatile_checkpoints_dir, checkpoint)
+ try:
+ # Remove leading ../ from a relative path.
+ cpkt_path = relative_path.replace("..", "").lstrip(os.path.sep)
+ copy_path = os.path.join(consistent_checkpoint_path, cpkt_path)
+ shutil.copytree(relative_path, copy_path)
+ target_path = consistent_checkpoint_path
+ except IOError as e:
+ logger.warning(
+ "NeptuneCallback was unable to made a copy of checkpoint due to I/O exception: '{}'. "
+ "Could fail trying to upload.".format(e)
+ )
+
+ self._metadata_namespace[self._target_checkpoints_namespace].upload_files(target_path)
+
+ if self._should_clean_recently_uploaded_checkpoint and self._recent_checkpoint_path is not None:
+ self._metadata_namespace[self._target_checkpoints_namespace].delete_files(self._recent_checkpoint_path)
+
+ self._recent_checkpoint_path = relative_path
+
+ def on_init_end(self, args, state, control, **kwargs):
+ self._volatile_checkpoints_dir = None
+ if self._log_checkpoints and (args.overwrite_output_dir or args.save_total_limit is not None):
+ self._volatile_checkpoints_dir = tempfile.TemporaryDirectory().name
+
+ if self._log_checkpoints == "best" and not args.load_best_model_at_end:
+ raise ValueError("To save the best model checkpoint, the load_best_model_at_end argument must be enabled.")
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if not state.is_world_process_zero:
+ return
+
+ self._ensure_run_with_monitoring()
+ self._force_reset_monitoring_run = True
+
+ self._log_integration_version()
+ if self._log_parameters:
+ self._log_trainer_parameters(args)
+ self._log_model_parameters(model)
+
+ if state.is_hyper_param_search:
+ self._log_hyper_param_search_parameters(state)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ self._stop_run_if_exists()
+
+ def __del__(self):
+ if self._volatile_checkpoints_dir is not None:
+ shutil.rmtree(self._volatile_checkpoints_dir, ignore_errors=True)
+
+ self._stop_run_if_exists()
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._should_upload_checkpoint:
+ self._log_model_checkpoint(args.output_dir, f"checkpoint-{state.global_step}")
+
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
+ if self._log_checkpoints == "best":
+ best_metric_name = args.metric_for_best_model
+ if not best_metric_name.startswith("eval_"):
+ best_metric_name = f"eval_{best_metric_name}"
+
+ metric_value = metrics.get(best_metric_name)
+
+ operator = np.greater if args.greater_is_better else np.less
+
+ self._should_upload_checkpoint = state.best_metric is None or operator(metric_value, state.best_metric)
+
+ @classmethod
+ def get_run(cls, trainer):
+ for callback in trainer.callback_handler.callbacks:
+ if isinstance(callback, cls):
+ return callback.run
+
+ raise Exception("The trainer doesn't have a NeptuneCallback configured.")
+
+ def on_log(self, args, state, control, logs: Optional[Dict[str, float]] = None, **kwargs):
+ if not state.is_world_process_zero:
+ return
+
+ if logs is not None:
+ for name, value in rewrite_logs(logs).items():
+ if isinstance(value, (int, float)):
+ if name in NeptuneCallback.flat_metrics:
+ self._metadata_namespace[name] = value
+ else:
+ self._metadata_namespace[name].log(value, step=state.global_step)
+
+
+class CodeCarbonCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that tracks the CO2 emission of training.
+ """
+
+ def __init__(self):
+ if not is_codecarbon_available():
+ raise RuntimeError(
+ "CodeCarbonCallback requires `codecarbon` to be installed. Run `pip install codecarbon`."
+ )
+ elif torch.version.hip:
+ raise RuntimeError(
+ "CodeCarbonCallback requires `codecarbon` package, which is not compatible with AMD ROCm (https://github.com/mlco2/codecarbon/pull/490). When using the Trainer, please specify the `report_to` argument (https://huggingface.co/docs/transformers/v4.39.3/en/main_classes/trainer#transformers.TrainingArguments.report_to) to disable CodeCarbonCallback."
+ )
+
+ import codecarbon
+
+ self._codecarbon = codecarbon
+ self.tracker = None
+
+ def on_init_end(self, args, state, control, **kwargs):
+ if self.tracker is None and state.is_local_process_zero:
+ # CodeCarbon will automatically handle environment variables for configuration
+ self.tracker = self._codecarbon.EmissionsTracker(output_dir=args.output_dir)
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if self.tracker and state.is_local_process_zero:
+ self.tracker.start()
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self.tracker and state.is_local_process_zero:
+ self.tracker.stop()
+
+
+class ClearMLCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [ClearML](https://clear.ml/).
+
+ Environment:
+ - **CLEARML_PROJECT** (`str`, *optional*, defaults to `HuggingFace Transformers`):
+ ClearML project name.
+ - **CLEARML_TASK** (`str`, *optional*, defaults to `Trainer`):
+ ClearML task name.
+ - **CLEARML_LOG_MODEL** (`bool`, *optional*, defaults to `False`):
+ Whether to log models as artifacts during training.
+ """
+
+ log_suffix = ""
+
+ _hparams_section = "Transformers"
+ _model_config_section = "Model Configuration"
+ _ignore_hparams_overrides = "_ignore_hparams_ui_overrides_"
+ _ignoge_model_config_overrides = "_ignore_model_config_ui_overrides_"
+ _model_config_description = "The configuration of model number {}."
+ _model_config_description_note = (
+ "Note that, when cloning this task and running it remotely,"
+ " the configuration might be applied to another model instead of this one."
+ " To avoid this, initialize the task externally by calling `Task.init`"
+ " before the `ClearMLCallback` is instantiated."
+ )
+ _train_run_counter = 0
+ _model_connect_counter = 0
+ _task_created_in_callback = False
+ _should_close_on_train_end = None
+
+ def __init__(self):
+ if is_clearml_available():
+ import clearml
+
+ self._clearml = clearml
+ else:
+ raise RuntimeError("ClearMLCallback requires 'clearml' to be installed. Run `pip install clearml`.")
+
+ self._initialized = False
+ self._clearml_task = None
+
+ self._log_model = False
+ self._checkpoints_saved = []
+
+ def setup(self, args, state, model, processing_class, **kwargs):
+ if self._clearml is None:
+ return
+ if self._initialized:
+ return
+ ClearMLCallback._train_run_counter += 1
+ ClearMLCallback._model_connect_counter += 1
+ ClearMLCallback.log_suffix = (
+ "" if ClearMLCallback._train_run_counter == 1 else "_" + str(ClearMLCallback._train_run_counter)
+ )
+ if state.is_world_process_zero:
+ logger.info("Automatic ClearML logging enabled.")
+ if self._clearml_task is None:
+ if ClearMLCallback._should_close_on_train_end is None:
+ if not self._clearml.Task.running_locally() or self._clearml.Task.current_task():
+ ClearMLCallback._should_close_on_train_end = False
+ else:
+ ClearMLCallback._should_close_on_train_end = True
+
+ # This might happen when running inside of a pipeline, where the task is already initialized
+ # from outside of Hugging Face
+ if self._clearml.Task.running_locally() and self._clearml.Task.current_task():
+ self._clearml_task = self._clearml.Task.current_task()
+ self._log_model = os.getenv(
+ "CLEARML_LOG_MODEL",
+ "FALSE" if not ClearMLCallback._task_created_in_callback else "TRUE",
+ ).upper() in ENV_VARS_TRUE_VALUES.union({"TRUE"})
+ logger.info("External ClearML Task has been connected.")
+ else:
+ self._clearml_task = self._clearml.Task.init(
+ project_name=os.getenv("CLEARML_PROJECT", "HuggingFace Transformers"),
+ task_name=os.getenv("CLEARML_TASK", "Trainer"),
+ auto_connect_frameworks={"tensorboard": False, "pytorch": False},
+ output_uri=True,
+ )
+ self._log_model = os.getenv("CLEARML_LOG_MODEL", "TRUE").upper() in ENV_VARS_TRUE_VALUES.union(
+ {"TRUE"}
+ )
+ ClearMLCallback._task_created_in_callback = True
+ logger.info("ClearML Task has been initialized.")
+ self._initialized = True
+
+ suffixed_hparams_section = ClearMLCallback._hparams_section + ClearMLCallback.log_suffix
+ ignore_hparams_config_section = suffixed_hparams_section + "/" + ClearMLCallback._ignore_hparams_overrides
+ if self._clearml.Task.running_locally():
+ self._copy_training_args_as_hparams(args, suffixed_hparams_section)
+ self._clearml_task.set_parameter(
+ name=ignore_hparams_config_section,
+ value=True,
+ value_type=bool,
+ description=(
+ "If True, ignore Transformers hyperparameters overrides done in the UI/backend "
+ + "when running remotely. Otherwise, the overrides will be applied when running remotely"
+ ),
+ )
+ elif not self._clearml_task.get_parameter(ignore_hparams_config_section, default=True, cast=True):
+ self._clearml_task.connect(args, suffixed_hparams_section)
+ else:
+ self._copy_training_args_as_hparams(
+ args, ClearMLCallback._hparams_section + ClearMLCallback.log_suffix
+ )
+
+ if getattr(model, "config", None) is not None:
+ ignore_model_config_section = (
+ suffixed_hparams_section + "/" + ClearMLCallback._ignoge_model_config_overrides
+ )
+ configuration_object_description = ClearMLCallback._model_config_description.format(
+ ClearMLCallback._model_connect_counter
+ )
+ if ClearMLCallback._model_connect_counter != ClearMLCallback._train_run_counter:
+ configuration_object_description += " " + ClearMLCallback._model_config_description_note
+ if self._clearml.Task.running_locally():
+ self._clearml_task.set_parameter(
+ name=ignore_model_config_section,
+ value=True,
+ value_type=bool,
+ description=(
+ "If True, ignore Transformers model configuration overrides done in the UI/backend "
+ + "when running remotely. Otherwise, the overrides will be applied when running remotely"
+ ),
+ )
+ self._clearml_task.set_configuration_object(
+ name=ClearMLCallback._model_config_section + ClearMLCallback.log_suffix,
+ config_dict=model.config.to_dict(),
+ description=configuration_object_description,
+ )
+ elif not self._clearml_task.get_parameter(ignore_model_config_section, default=True, cast=True):
+ model.config = model.config.from_dict(
+ self._clearml_task.get_configuration_object_as_dict(
+ ClearMLCallback._model_config_section + ClearMLCallback.log_suffix
+ )
+ )
+ else:
+ self._clearml_task.set_configuration_object(
+ name=ClearMLCallback._model_config_section + ClearMLCallback.log_suffix,
+ config_dict=model.config.to_dict(),
+ description=configuration_object_description,
+ )
+
+ def on_train_begin(self, args, state, control, model=None, processing_class=None, **kwargs):
+ if self._clearml is None:
+ return
+ self._checkpoints_saved = []
+ if state.is_hyper_param_search:
+ self._initialized = False
+ if not self._initialized:
+ self.setup(args, state, model, processing_class, **kwargs)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if ClearMLCallback._should_close_on_train_end:
+ self._clearml_task.close()
+ ClearMLCallback._train_run_counter = 0
+
+ def on_log(self, args, state, control, model=None, processing_class=None, logs=None, **kwargs):
+ if self._clearml is None:
+ return
+ if not self._initialized:
+ self.setup(args, state, model, processing_class, **kwargs)
+ if state.is_world_process_zero:
+ eval_prefix = "eval_"
+ eval_prefix_len = len(eval_prefix)
+ test_prefix = "test_"
+ test_prefix_len = len(test_prefix)
+ single_value_scalars = [
+ "train_runtime",
+ "train_samples_per_second",
+ "train_steps_per_second",
+ "train_loss",
+ "total_flos",
+ "epoch",
+ ]
+ for k, v in logs.items():
+ if isinstance(v, (int, float)):
+ if k in single_value_scalars:
+ self._clearml_task.get_logger().report_single_value(
+ name=k + ClearMLCallback.log_suffix, value=v
+ )
+ elif k.startswith(eval_prefix):
+ self._clearml_task.get_logger().report_scalar(
+ title="eval" + ClearMLCallback.log_suffix,
+ series=k[eval_prefix_len:],
+ value=v,
+ iteration=state.global_step,
+ )
+ elif k.startswith(test_prefix):
+ self._clearml_task.get_logger().report_scalar(
+ title="test" + ClearMLCallback.log_suffix,
+ series=k[test_prefix_len:],
+ value=v,
+ iteration=state.global_step,
+ )
+ else:
+ self._clearml_task.get_logger().report_scalar(
+ title="train" + ClearMLCallback.log_suffix,
+ series=k,
+ value=v,
+ iteration=state.global_step,
+ )
+ else:
+ logger.warning(
+ "Trainer is attempting to log a value of "
+ f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
+ "This invocation of ClearML logger's report_scalar() "
+ "is incorrect so we dropped this attribute."
+ )
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._log_model and self._clearml_task and state.is_world_process_zero:
+ ckpt_dir = f"checkpoint-{state.global_step}"
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
+ name = ckpt_dir + ClearMLCallback.log_suffix
+ logger.info(f"Logging checkpoint artifact `{name}`. This may take some time.")
+ output_model = self._clearml.OutputModel(task=self._clearml_task, name=name)
+ output_model.connect(task=self._clearml_task, name=name)
+ output_model.update_weights_package(
+ weights_path=artifact_path,
+ target_filename=ckpt_dir,
+ iteration=state.global_step,
+ auto_delete_file=False,
+ )
+ self._checkpoints_saved.append(output_model)
+ while args.save_total_limit and args.save_total_limit < len(self._checkpoints_saved):
+ try:
+ self._clearml.model.Model.remove(
+ self._checkpoints_saved[0],
+ delete_weights_file=True,
+ force=True,
+ raise_on_errors=True,
+ )
+ except Exception as e:
+ logger.warning(
+ "Could not remove checkpoint `{}` after going over the `save_total_limit`. Error is: {}".format(
+ self._checkpoints_saved[0].name, e
+ )
+ )
+ break
+ self._checkpoints_saved = self._checkpoints_saved[1:]
+
+ def _copy_training_args_as_hparams(self, training_args, prefix):
+ as_dict = {
+ field.name: getattr(training_args, field.name)
+ for field in fields(training_args)
+ if field.init and not field.name.endswith("_token")
+ }
+ flat_dict = {str(k): v for k, v in self._clearml.utilities.proxy_object.flatten_dictionary(as_dict).items()}
+ self._clearml_task._arguments.copy_from_dict(flat_dict, prefix=prefix)
+
+
+class FlyteCallback(TrainerCallback):
+ """A [`TrainerCallback`] that sends the logs to [Flyte](https://flyte.org/).
+ NOTE: This callback only works within a Flyte task.
+
+ Args:
+ save_log_history (`bool`, *optional*, defaults to `True`):
+ When set to True, the training logs are saved as a Flyte Deck.
+
+ sync_checkpoints (`bool`, *optional*, defaults to `True`):
+ When set to True, checkpoints are synced with Flyte and can be used to resume training in the case of an
+ interruption.
+
+ Example:
+
+ ```python
+ # Note: This example skips over some setup steps for brevity.
+ from flytekit import current_context, task
+
+
+ @task
+ def train_hf_transformer():
+ cp = current_context().checkpoint
+ trainer = Trainer(..., callbacks=[FlyteCallback()])
+ output = trainer.train(resume_from_checkpoint=cp.restore())
+ ```
+ """
+
+ def __init__(self, save_log_history: bool = True, sync_checkpoints: bool = True):
+ super().__init__()
+ if not is_flytekit_available():
+ raise ImportError("FlyteCallback requires flytekit to be installed. Run `pip install flytekit`.")
+
+ if not is_flyte_deck_standard_available() or not is_pandas_available():
+ logger.warning(
+ "Syncing log history requires both flytekitplugins-deck-standard and pandas to be installed. "
+ "Run `pip install flytekitplugins-deck-standard pandas` to enable this feature."
+ )
+ save_log_history = False
+
+ from flytekit import current_context
+
+ self.cp = current_context().checkpoint
+ self.save_log_history = save_log_history
+ self.sync_checkpoints = sync_checkpoints
+
+ def on_save(self, args, state, control, **kwargs):
+ if self.sync_checkpoints and state.is_world_process_zero:
+ ckpt_dir = f"checkpoint-{state.global_step}"
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
+
+ logger.info(f"Syncing checkpoint in {ckpt_dir} to Flyte. This may take time.")
+ self.cp.save(artifact_path)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self.save_log_history:
+ import pandas as pd
+ from flytekit import Deck
+ from flytekitplugins.deck.renderer import TableRenderer
+
+ log_history_df = pd.DataFrame(state.log_history)
+ Deck("Log History", TableRenderer().to_html(log_history_df))
+
+
+class DVCLiveCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [DVCLive](https://www.dvc.org/doc/dvclive).
+
+ Use the environment variables below in `setup` to configure the integration. To customize this callback beyond
+ those environment variables, see [here](https://dvc.org/doc/dvclive/ml-frameworks/huggingface).
+
+ Args:
+ live (`dvclive.Live`, *optional*, defaults to `None`):
+ Optional Live instance. If None, a new instance will be created using **kwargs.
+ log_model (Union[Literal["all"], bool], *optional*, defaults to `None`):
+ Whether to use `dvclive.Live.log_artifact()` to log checkpoints created by [`Trainer`]. If set to `True`,
+ the final checkpoint is logged at the end of training. If set to `"all"`, the entire
+ [`TrainingArguments`]'s `output_dir` is logged at each checkpoint.
+ """
+
+ def __init__(
+ self,
+ live: Optional[Any] = None,
+ log_model: Optional[Union[Literal["all"], bool]] = None,
+ **kwargs,
+ ):
+ if not is_dvclive_available():
+ raise RuntimeError("DVCLiveCallback requires dvclive to be installed. Run `pip install dvclive`.")
+ from dvclive import Live
+
+ self._initialized = False
+ self.live = None
+ if isinstance(live, Live):
+ self.live = live
+ elif live is not None:
+ raise RuntimeError(f"Found class {live.__class__} for live, expected dvclive.Live")
+
+ self._log_model = log_model
+ if self._log_model is None:
+ log_model_env = os.getenv("HF_DVCLIVE_LOG_MODEL", "FALSE")
+ if log_model_env.upper() in ENV_VARS_TRUE_VALUES:
+ self._log_model = True
+ elif log_model_env.lower() == "all":
+ self._log_model = "all"
+
+ def setup(self, args, state, model):
+ """
+ Setup the optional DVCLive integration. To customize this callback beyond the environment variables below, see
+ [here](https://dvc.org/doc/dvclive/ml-frameworks/huggingface).
+
+ Environment:
+ - **HF_DVCLIVE_LOG_MODEL** (`str`, *optional*):
+ Whether to use `dvclive.Live.log_artifact()` to log checkpoints created by [`Trainer`]. If set to `True` or
+ *1*, the final checkpoint is logged at the end of training. If set to `all`, the entire
+ [`TrainingArguments`]'s `output_dir` is logged at each checkpoint.
+ """
+ from dvclive import Live
+
+ self._initialized = True
+ if state.is_world_process_zero:
+ if not self.live:
+ self.live = Live()
+ self.live.log_params(args.to_dict())
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+
+ def on_log(self, args, state, control, model=None, logs=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+ if state.is_world_process_zero:
+ from dvclive.plots import Metric
+ from dvclive.utils import standardize_metric_name
+
+ for key, value in logs.items():
+ if Metric.could_log(value):
+ self.live.log_metric(standardize_metric_name(key, "dvclive.huggingface"), value)
+ else:
+ logger.warning(
+ "Trainer is attempting to log a value of "
+ f'"{value}" of type {type(value)} for key "{key}" as a scalar. '
+ "This invocation of DVCLive's Live.log_metric() "
+ "is incorrect so we dropped this attribute."
+ )
+ self.live.next_step()
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._log_model == "all" and self._initialized and state.is_world_process_zero:
+ self.live.log_artifact(args.output_dir)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self._initialized and state.is_world_process_zero:
+ from transformers.trainer import Trainer
+
+ if self._log_model is True:
+ fake_trainer = Trainer(
+ args=args,
+ model=kwargs.get("model"),
+ processing_class=kwargs.get("processing_class"),
+ eval_dataset=["fake"],
+ )
+ name = "best" if args.load_best_model_at_end else "last"
+ output_dir = os.path.join(args.output_dir, name)
+ fake_trainer.save_model(output_dir)
+ self.live.log_artifact(output_dir, name=name, type="model", copy=True)
+ self.live.end()
+
+
+INTEGRATION_TO_CALLBACK = {
+ "azure_ml": AzureMLCallback,
+ "comet_ml": CometCallback,
+ "mlflow": MLflowCallback,
+ "neptune": NeptuneCallback,
+ "tensorboard": TensorBoardCallback,
+ "wandb": WandbCallback,
+ "codecarbon": CodeCarbonCallback,
+ "clearml": ClearMLCallback,
+ "dagshub": DagsHubCallback,
+ "flyte": FlyteCallback,
+ "dvclive": DVCLiveCallback,
+}
+
+
+def get_reporting_integration_callbacks(report_to):
+ if report_to is None:
+ return []
+
+ if isinstance(report_to, str):
+ if "none" == report_to:
+ return []
+ elif "all" == report_to:
+ report_to = get_available_reporting_integrations()
+ else:
+ report_to = [report_to]
+
+ for integration in report_to:
+ if integration not in INTEGRATION_TO_CALLBACK:
+ raise ValueError(
+ f"{integration} is not supported, only {', '.join(INTEGRATION_TO_CALLBACK.keys())} are supported."
+ )
+
+ return [INTEGRATION_TO_CALLBACK[integration] for integration in report_to]
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/mistral.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/mistral.py
new file mode 100644
index 0000000000000000000000000000000000000000..78172329277e4f5ac0b01795a123bdebe7bd8f51
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/mistral.py
@@ -0,0 +1,105 @@
+from tokenizers import Regex, Tokenizer, decoders, pre_tokenizers, processors
+from tokenizers.models import BPE
+
+from transformers import LlamaTokenizerFast
+from transformers.convert_slow_tokenizer import bytes_to_unicode
+
+
+class MistralConverter:
+ """
+ A general tiktoken converter.
+ """
+
+ def __init__(
+ self,
+ vocab=None,
+ pattern=r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+""",
+ add_prefix_space=False,
+ additional_special_tokens=None,
+ *args,
+ **kwargs,
+ ):
+ super().__init__(*args)
+ self.vocab = vocab
+ self.pattern = pattern
+ self.add_prefix_space = add_prefix_space
+ self.additional_special_tokens = additional_special_tokens
+
+ def extract_vocab_merges_from_model(self, vocab: str):
+ bpe_ranks = vocab
+ byte_encoder = bytes_to_unicode()
+
+ def token_bytes_to_string(b):
+ return "".join([byte_encoder[ord(char)] for char in b.decode("latin-1")])
+
+ merges = []
+ vocab = {}
+ for idx, (token, rank) in enumerate(bpe_ranks.items()):
+ if token not in self.additional_special_tokens:
+ vocab[token_bytes_to_string(token)] = idx
+ if len(token) == 1:
+ continue
+ local = []
+ for index in range(1, len(token)):
+ piece_l, piece_r = token[:index], token[index:]
+ if piece_l in bpe_ranks and piece_r in bpe_ranks and (piece_l + piece_r) in bpe_ranks:
+ local.append((piece_l, piece_r, rank))
+ local = sorted(local, key=lambda x: (bpe_ranks[x[0]], bpe_ranks[x[1]]), reverse=False)
+ merges.extend(local)
+ else:
+ vocab[token] = idx
+ merges = sorted(merges, key=lambda val: val[2], reverse=False)
+ merges = [(token_bytes_to_string(val[0]), token_bytes_to_string(val[1])) for val in merges]
+ return vocab, merges
+
+ def tokenizer(self):
+ vocab_scores, merges = self.extract_vocab_merges_from_model(self.vocab)
+ tokenizer = Tokenizer(BPE(vocab_scores, merges, fuse_unk=False))
+ if hasattr(tokenizer.model, "ignore_merges"):
+ tokenizer.model.ignore_merges = True
+ return tokenizer
+
+ def converted(self) -> Tokenizer:
+ tokenizer = self.tokenizer()
+ tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
+ [
+ pre_tokenizers.Split(Regex(self.pattern), behavior="isolated", invert=False),
+ pre_tokenizers.ByteLevel(add_prefix_space=self.add_prefix_space, use_regex=False),
+ ]
+ )
+ tokenizer.decoder = decoders.ByteLevel()
+ tokenizer.add_special_tokens(self.additional_special_tokens)
+
+ tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)
+
+ return tokenizer
+
+
+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_file(tokenizer_file)
+
+ # Extract vocab and special tokens
+ vocab = mistral_tokenizer.instruct_tokenizer.tokenizer._tekken_token2id_nospecial
+ all_special = [
+ token.value if hasattr(token, "value") else token
+ for token in mistral_tokenizer.instruct_tokenizer.tokenizer._all_special_tokens
+ ]
+ specials_tokens = {token: all_special.index(token) for token in all_special}
+ specials_tokens.update(vocab)
+ vocab = specials_tokens
+
+ # Convert
+ tokenizer = LlamaTokenizerFast(
+ tokenizer_object=MistralConverter(vocab=vocab, additional_special_tokens=all_special).converted(),
+ )
+
+ # Post-process
+ tokenizer.add_special_tokens({"additional_special_tokens": all_special})
+
+ return tokenizer
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/peft.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/peft.py
new file mode 100644
index 0000000000000000000000000000000000000000..791528a629acf431264634cfc7ae351604377388
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/peft.py
@@ -0,0 +1,589 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import importlib
+import inspect
+import warnings
+from typing import Any, Dict, List, Optional, Union
+
+from packaging import version
+
+from ..utils import (
+ check_peft_version,
+ find_adapter_config_file,
+ is_accelerate_available,
+ is_peft_available,
+ is_torch_available,
+ logging,
+)
+
+
+if is_torch_available():
+ import torch
+
+if is_accelerate_available():
+ from accelerate import dispatch_model
+ from accelerate.utils import get_balanced_memory, infer_auto_device_map
+
+# Minimum PEFT version supported for the integration
+MIN_PEFT_VERSION = "0.5.0"
+
+
+logger = logging.get_logger(__name__)
+
+
+class PeftAdapterMixin:
+ """
+ A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
+ more details about adapters and injecting them on a transformer-based model, check out the documentation of PEFT
+ library: https://huggingface.co/docs/peft/index
+
+ Currently supported PEFT methods are all non-prefix tuning methods. Below is the list of supported PEFT methods
+ that anyone can load, train and run with this mixin class:
+ - Low Rank Adapters (LoRA): https://huggingface.co/docs/peft/conceptual_guides/lora
+ - IA3: https://huggingface.co/docs/peft/conceptual_guides/ia3
+ - AdaLora: https://arxiv.org/abs/2303.10512
+
+ Other PEFT models such as prompt tuning, prompt learning are out of scope as these adapters are not "injectable"
+ into a torch module. For using these methods, please refer to the usage guide of PEFT library.
+
+ With this mixin, if the correct PEFT version is installed, it is possible to:
+
+ - Load an adapter stored on a local path or in a remote Hub repository, and inject it in the model
+ - Attach new adapters in the model and train them with Trainer or by your own.
+ - Attach multiple adapters and iteratively activate / deactivate them
+ - Activate / deactivate all adapters from the model.
+ - Get the `state_dict` of the active adapter.
+ """
+
+ _hf_peft_config_loaded = False
+
+ def load_adapter(
+ self,
+ peft_model_id: Optional[str] = None,
+ adapter_name: Optional[str] = None,
+ revision: Optional[str] = None,
+ token: Optional[str] = None,
+ device_map: Optional[str] = "auto",
+ max_memory: Optional[str] = None,
+ offload_folder: Optional[str] = None,
+ offload_index: Optional[int] = None,
+ peft_config: Dict[str, Any] = None,
+ adapter_state_dict: Optional[Dict[str, "torch.Tensor"]] = None,
+ low_cpu_mem_usage: bool = False,
+ is_trainable: bool = False,
+ adapter_kwargs: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ """
+ Load adapter weights from file or remote Hub folder. If you are not familiar with adapters and PEFT methods, we
+ invite you to read more about them on PEFT official documentation: https://huggingface.co/docs/peft
+
+ Requires peft as a backend to load the adapter weights.
+
+ Args:
+ peft_model_id (`str`, *optional*):
+ The identifier of the model to look for on the Hub, or a local path to the saved adapter config file
+ and adapter weights.
+ adapter_name (`str`, *optional*):
+ The adapter name to use. If not set, will use the default adapter.
+ revision (`str`, *optional*, defaults to `"main"`):
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
+ identifier allowed by git.
+
+
+
+ To test a pull request you made on the Hub, you can pass `revision="refs/pr/"`.
+
+
+
+ token (`str`, `optional`):
+ Whether to use authentication token to load the remote folder. Useful to load private repositories
+ that are on HuggingFace Hub. You might need to call `huggingface-cli login` and paste your tokens to
+ cache it.
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
+ A map that specifies where each submodule should go. It doesn't need to be refined to each
+ parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
+ same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
+ like `1`) on which the model will be allocated, the device map will map the entire model to this
+ device. Passing `device_map = 0` means put the whole model on GPU 0.
+
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
+ more information about each option see [designing a device
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
+ max_memory (`Dict`, *optional*):
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
+ GPU and the available CPU RAM if unset.
+ offload_folder (`str` or `os.PathLike`, `optional`):
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
+ offload_index (`int`, `optional`):
+ `offload_index` argument to be passed to `accelerate.dispatch_model` method.
+ peft_config (`Dict[str, Any]`, *optional*):
+ The configuration of the adapter to add, supported adapters are non-prefix tuning and adaption prompts
+ methods. This argument is used in case users directly pass PEFT state dicts
+ adapter_state_dict (`Dict[str, torch.Tensor]`, *optional*):
+ The state dict of the adapter to load. This argument is used in case users directly pass PEFT state
+ dicts
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `False`):
+ Reduce memory usage while loading the PEFT adapter. This should also speed up the loading process.
+ Requires PEFT version 0.13.0 or higher.
+ is_trainable (`bool`, *optional*, defaults to `False`):
+ Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be
+ used for inference.
+ adapter_kwargs (`Dict[str, Any]`, *optional*):
+ Additional keyword arguments passed along to the `from_pretrained` method of the adapter config and
+ `find_adapter_config_file` method.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ # peft only supports low_cpu_mem_usage starting from v0.13.0
+ peft_load_kwargs = {}
+ if low_cpu_mem_usage:
+ min_version_lcmu = "0.13.0"
+ if version.parse(importlib.metadata.version("peft")) >= version.parse(min_version_lcmu):
+ peft_load_kwargs["low_cpu_mem_usage"] = low_cpu_mem_usage
+ else:
+ raise ValueError(
+ "The version of PEFT you are using does not support `low_cpu_mem_usage` yet, "
+ f"please install PEFT >= {min_version_lcmu}."
+ )
+
+ adapter_name = adapter_name if adapter_name is not None else "default"
+ if adapter_kwargs is None:
+ adapter_kwargs = {}
+
+ from peft import PeftConfig, inject_adapter_in_model, load_peft_weights
+ from peft.utils import set_peft_model_state_dict
+
+ if self._hf_peft_config_loaded and adapter_name in self.peft_config:
+ raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
+
+ if peft_model_id is None and (adapter_state_dict is None and peft_config is None):
+ raise ValueError(
+ "You should either pass a `peft_model_id` or a `peft_config` and `adapter_state_dict` to load an adapter."
+ )
+
+ if "device" not in adapter_kwargs:
+ device = self.device if not hasattr(self, "hf_device_map") else list(self.hf_device_map.values())[0]
+ else:
+ device = adapter_kwargs.pop("device")
+
+ # To avoid PEFT errors later on with safetensors.
+ if isinstance(device, torch.device):
+ device = str(device)
+
+ # We keep `revision` in the signature for backward compatibility
+ if revision is not None and "revision" not in adapter_kwargs:
+ adapter_kwargs["revision"] = revision
+ elif revision is not None and "revision" in adapter_kwargs and revision != adapter_kwargs["revision"]:
+ logger.error(
+ "You passed a `revision` argument both in `adapter_kwargs` and as a standalone argument. "
+ "The one in `adapter_kwargs` will be used."
+ )
+
+ # Override token with adapter_kwargs' token
+ if "token" in adapter_kwargs:
+ token = adapter_kwargs.pop("token")
+
+ if peft_config is None:
+ adapter_config_file = find_adapter_config_file(
+ peft_model_id,
+ token=token,
+ **adapter_kwargs,
+ )
+
+ if adapter_config_file is None:
+ raise ValueError(
+ f"adapter model file not found in {peft_model_id}. Make sure you are passing the correct path to the "
+ "adapter model."
+ )
+
+ peft_config = PeftConfig.from_pretrained(
+ peft_model_id,
+ token=token,
+ **adapter_kwargs,
+ )
+ peft_config.inference_mode = not is_trainable
+
+ # Create and add fresh new adapters into the model.
+ inject_adapter_in_model(peft_config, self, adapter_name, **peft_load_kwargs)
+
+ if not self._hf_peft_config_loaded:
+ self._hf_peft_config_loaded = True
+
+ if peft_model_id is not None:
+ adapter_state_dict = load_peft_weights(peft_model_id, token=token, device=device, **adapter_kwargs)
+
+ # We need to pre-process the state dict to remove unneeded prefixes - for backward compatibility
+ processed_adapter_state_dict = {}
+ prefix = "base_model.model."
+ for key, value in adapter_state_dict.items():
+ if key.startswith(prefix):
+ new_key = key[len(prefix) :]
+ else:
+ new_key = key
+ processed_adapter_state_dict[new_key] = value
+
+ # Load state dict
+ incompatible_keys = set_peft_model_state_dict(
+ self, processed_adapter_state_dict, adapter_name, **peft_load_kwargs
+ )
+
+ if incompatible_keys is not None:
+ err_msg = ""
+ origin_name = peft_model_id if peft_model_id is not None else "state_dict"
+ # Check for unexpected keys.
+ if hasattr(incompatible_keys, "unexpected_keys") and len(incompatible_keys.unexpected_keys) > 0:
+ err_msg = (
+ f"Loading adapter weights from {origin_name} led to unexpected keys not found in the model: "
+ f"{', '.join(incompatible_keys.unexpected_keys)}. "
+ )
+
+ # Check for missing keys.
+ missing_keys = getattr(incompatible_keys, "missing_keys", None)
+ if missing_keys:
+ # Filter missing keys specific to the current adapter, as missing base model keys are expected.
+ lora_missing_keys = [k for k in missing_keys if "lora_" in k and adapter_name in k]
+ if lora_missing_keys:
+ err_msg += (
+ f"Loading adapter weights from {origin_name} led to missing keys in the model: "
+ f"{', '.join(lora_missing_keys)}"
+ )
+
+ if err_msg:
+ logger.warning(err_msg)
+
+ if peft_config.inference_mode:
+ self.eval()
+
+ # Re-dispatch model and hooks in case the model is offloaded to CPU / Disk.
+ if (
+ (getattr(self, "hf_device_map", None) is not None)
+ and (len(set(self.hf_device_map.values()).intersection({"cpu", "disk"})) > 0)
+ and len(self.peft_config) == 1
+ ):
+ self._dispatch_accelerate_model(
+ device_map=device_map,
+ max_memory=max_memory,
+ offload_folder=offload_folder,
+ offload_index=offload_index,
+ )
+
+ def add_adapter(self, adapter_config, adapter_name: Optional[str] = None) -> None:
+ r"""
+ 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
+
+ Adds a fresh new adapter to the current model for training purpose. If no adapter name is passed, a default
+ name is assigned to the adapter to follow the convention of PEFT library (in PEFT we use "default" as the
+ default adapter name).
+
+ Args:
+ adapter_config (`~peft.PeftConfig`):
+ The configuration of the adapter to add, supported adapters are non-prefix tuning and adaption prompts
+ methods
+ adapter_name (`str`, *optional*, defaults to `"default"`):
+ The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ from peft import PeftConfig, inject_adapter_in_model
+
+ adapter_name = adapter_name or "default"
+
+ if not self._hf_peft_config_loaded:
+ self._hf_peft_config_loaded = True
+ elif adapter_name in self.peft_config:
+ raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
+
+ if not isinstance(adapter_config, PeftConfig):
+ raise TypeError(f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead.")
+
+ # Retrieve the name or path of the model, one could also use self.config._name_or_path
+ # but to be consistent with what we do in PEFT: https://github.com/huggingface/peft/blob/6e783780ca9df3a623992cc4d1d665001232eae0/src/peft/mapping.py#L100
+ adapter_config.base_model_name_or_path = self.__dict__.get("name_or_path", None)
+ inject_adapter_in_model(adapter_config, self, adapter_name)
+
+ self.set_adapter(adapter_name)
+
+ def set_adapter(self, adapter_name: Union[List[str], str]) -> 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
+
+ Sets a specific adapter by forcing the model to use a that adapter and disable the other adapters.
+
+ Args:
+ adapter_name (`Union[List[str], str]`):
+ The name of the adapter to set. Can be also a list of strings to set multiple adapters.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+ elif isinstance(adapter_name, list):
+ missing = set(adapter_name) - set(self.peft_config)
+ if len(missing) > 0:
+ raise ValueError(
+ f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
+ f" current loaded adapters are: {list(self.peft_config.keys())}"
+ )
+ elif adapter_name not in self.peft_config:
+ raise ValueError(
+ f"Adapter with name {adapter_name} not found. Please pass the correct adapter name among {list(self.peft_config.keys())}"
+ )
+
+ from peft.tuners.tuners_utils import BaseTunerLayer
+ from peft.utils import ModulesToSaveWrapper
+
+ _adapters_has_been_set = False
+
+ for _, module in self.named_modules():
+ if isinstance(module, (BaseTunerLayer, ModulesToSaveWrapper)):
+ # For backward compatbility with previous PEFT versions
+ if hasattr(module, "set_adapter"):
+ module.set_adapter(adapter_name)
+ else:
+ module.active_adapter = adapter_name
+ _adapters_has_been_set = True
+
+ if not _adapters_has_been_set:
+ raise ValueError(
+ "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
+ )
+
+ def disable_adapters(self) -> None:
+ r"""
+ 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
+
+ Disable all adapters that are attached to the model. This leads to inferring with the base model only.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+
+ from peft.tuners.tuners_utils import BaseTunerLayer
+ from peft.utils import ModulesToSaveWrapper
+
+ for _, module in self.named_modules():
+ if isinstance(module, (BaseTunerLayer, ModulesToSaveWrapper)):
+ # The recent version of PEFT need to call `enable_adapters` instead
+ if hasattr(module, "enable_adapters"):
+ module.enable_adapters(enabled=False)
+ else:
+ module.disable_adapters = True
+
+ 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_version(min_version=MIN_PEFT_VERSION)
+
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+
+ from peft.tuners.tuners_utils import BaseTunerLayer
+
+ for _, module in self.named_modules():
+ if isinstance(module, BaseTunerLayer):
+ # The recent version of PEFT need to call `enable_adapters` instead
+ if hasattr(module, "enable_adapters"):
+ module.enable_adapters(enabled=True)
+ else:
+ module.disable_adapters = False
+
+ def active_adapters(self) -> List[str]:
+ """
+ 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 current active adapters of the model. In case of multi-adapter inference (combining multiple adapters
+ for inference) returns the list of all active adapters so that users can deal with them accordingly.
+
+ For previous PEFT versions (that does not support multi-adapter inference), `module.active_adapter` will return
+ a single string.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ if not is_peft_available():
+ raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
+
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+
+ from peft.tuners.tuners_utils import BaseTunerLayer
+
+ for _, module in self.named_modules():
+ if isinstance(module, BaseTunerLayer):
+ active_adapters = module.active_adapter
+ break
+
+ # For previous PEFT versions
+ if isinstance(active_adapters, str):
+ active_adapters = [active_adapters]
+
+ return active_adapters
+
+ def active_adapter(self) -> str:
+ warnings.warn(
+ "The `active_adapter` method is deprecated and will be removed in a future version.", FutureWarning
+ )
+
+ return self.active_adapters()[0]
+
+ def get_adapter_state_dict(self, adapter_name: Optional[str] = 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 the adapter state dict that should only contain the weights tensors of the specified adapter_name adapter.
+ If no adapter_name is passed, the active adapter is used.
+
+ Args:
+ adapter_name (`str`, *optional*):
+ The name of the adapter to get the state dict from. If no name is passed, the active adapter is used.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+
+ from peft import get_peft_model_state_dict
+
+ if adapter_name is None:
+ adapter_name = self.active_adapters()[0]
+
+ adapter_state_dict = get_peft_model_state_dict(self, adapter_name=adapter_name)
+ return adapter_state_dict
+
+ def _dispatch_accelerate_model(
+ self,
+ device_map: str,
+ max_memory: Optional[int] = None,
+ offload_folder: Optional[str] = None,
+ offload_index: Optional[int] = None,
+ ) -> None:
+ """
+ Optional re-dispatch the model and attach new hooks to the model in case the model has been loaded with
+ accelerate (i.e. with `device_map=xxx`)
+
+ Args:
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
+ A map that specifies where each submodule should go. It doesn't need to be refined to each
+ parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
+ same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
+ like `1`) on which the model will be allocated, the device map will map the entire model to this
+ device. Passing `device_map = 0` means put the whole model on GPU 0.
+
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
+ more information about each option see [designing a device
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
+ max_memory (`Dict`, *optional*):
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
+ GPU and the available CPU RAM if unset.
+ offload_folder (`str` or `os.PathLike`, *optional*):
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
+ offload_index (`int`, *optional*):
+ The offload_index argument to be passed to `accelerate.dispatch_model` method.
+ """
+ dispatch_model_kwargs = {}
+ # Safety checker for previous `accelerate` versions
+ # `offload_index` was introduced in https://github.com/huggingface/accelerate/pull/873/
+ if "offload_index" in inspect.signature(dispatch_model).parameters:
+ dispatch_model_kwargs["offload_index"] = offload_index
+
+ no_split_module_classes = self._no_split_modules
+
+ if device_map != "sequential":
+ max_memory = get_balanced_memory(
+ self,
+ max_memory=max_memory,
+ no_split_module_classes=no_split_module_classes,
+ low_zero=(device_map == "balanced_low_0"),
+ )
+ if isinstance(device_map, str):
+ device_map = infer_auto_device_map(
+ self, max_memory=max_memory, no_split_module_classes=no_split_module_classes
+ )
+ dispatch_model(
+ self,
+ device_map=device_map,
+ offload_dir=offload_folder,
+ **dispatch_model_kwargs,
+ )
+
+ 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
+ from diffusers import AutoPipelineForText2Image
+ import torch
+
+ pipeline = AutoPipelineForText2Image.from_pretrained(
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
+ ).to("cuda")
+ pipeline.load_lora_weights(
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
+ )
+ pipeline.delete_adapters("cinematic")
+ ```
+ """
+
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+
+ from peft.tuners.tuners_utils import BaseTunerLayer
+
+ if isinstance(adapter_names, str):
+ adapter_names = [adapter_names]
+
+ # Check that all adapter names are present in the config
+ missing_adapters = [name for name in adapter_names if name not in self.peft_config]
+ if missing_adapters:
+ raise ValueError(
+ f"The following adapter(s) are not present and cannot be deleted: {', '.join(missing_adapters)}"
+ )
+
+ for adapter_name in adapter_names:
+ for module in self.modules():
+ if isinstance(module, BaseTunerLayer):
+ if hasattr(module, "delete_adapter"):
+ module.delete_adapter(adapter_name)
+ else:
+ raise ValueError(
+ "The version of PEFT you are using is not compatible, please use a version that is greater than 0.6.1"
+ )
+
+ # For transformers integration - we need to pop the adapter from the config
+ if getattr(self, "_hf_peft_config_loaded", False) and hasattr(self, "peft_config"):
+ self.peft_config.pop(adapter_name, None)
+
+ # In case all adapters are deleted, we need to delete the config
+ # and make sure to set the flag to False
+ if len(self.peft_config) == 0:
+ del self.peft_config
+ self._hf_peft_config_loaded = False
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/quanto.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/quanto.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c5702321937da5f1238427156452cbccdbcea4a
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/quanto.py
@@ -0,0 +1,98 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from ..utils import is_optimum_quanto_available, is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+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 a boolean that indicates if the conversion has been successfull or not.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`AqlmConfig`, defaults to `None`):
+ The quantization config object that contains the quantization parameters.
+ modules_to_not_convert (`list`, *optional*, defaults to `None`):
+ A list of modules to not convert. If a module name is in the list (e.g. `lm_head`), it will not be
+ converted.
+ current_key_name (`list`, *optional*, defaults to `None`):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*, defaults to `None`):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+ from accelerate import init_empty_weights
+
+ if is_optimum_quanto_available():
+ from optimum.quanto import QLayerNorm, QLinear, qfloat8, qint2, qint4, qint8
+
+ w_mapping = {"float8": qfloat8, "int8": qint8, "int4": qint4, "int2": qint2}
+ a_mapping = {None: None, "float8": qfloat8, "int8": qint8}
+
+ if modules_to_not_convert is None:
+ modules_to_not_convert = []
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if not any(key in ".".join(current_key_name) for key in modules_to_not_convert):
+ with init_empty_weights():
+ if isinstance(module, torch.nn.Linear):
+ model._modules[name] = QLinear(
+ in_features=module.in_features,
+ out_features=module.out_features,
+ bias=module.bias is not None,
+ dtype=module.weight.dtype,
+ weights=w_mapping[quantization_config.weights],
+ activations=a_mapping[quantization_config.activations],
+ )
+ model._modules[name].requires_grad_(False)
+ has_been_replaced = True
+ elif isinstance(module, torch.nn.LayerNorm):
+ if quantization_config.activations is not None:
+ model._modules[name] = QLayerNorm(
+ module.normalized_shape,
+ module.eps,
+ module.elementwise_affine,
+ module.bias is not None,
+ activations=a_mapping[quantization_config.activations],
+ )
+ has_been_replaced = True
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_quanto_layers(
+ module,
+ quantization_config=quantization_config,
+ modules_to_not_convert=modules_to_not_convert,
+ current_key_name=current_key_name,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/sdpa_attention.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/sdpa_attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..890832a26e9d8ce6e49696b291d0833c596a7401
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/sdpa_attention.py
@@ -0,0 +1,65 @@
+from typing import Optional, Tuple
+
+import torch
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def sdpa_attention_forward(
+ module: torch.nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ dropout: float = 0.0,
+ scaling: Optional[float] = None,
+ is_causal: Optional[bool] = None,
+ **kwargs,
+) -> Tuple[torch.Tensor, None]:
+ if hasattr(module, "num_key_value_groups"):
+ key = repeat_kv(key, module.num_key_value_groups)
+ value = repeat_kv(value, module.num_key_value_groups)
+
+ causal_mask = attention_mask
+ if attention_mask is not None:
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
+
+ # SDPA with memory-efficient backend is bugged with non-contiguous inputs and custom attn_mask for some torch versions
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
+ query = query.contiguous()
+ key = key.contiguous()
+ value = value.contiguous()
+
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
+ # Note that it is important to check first for the shape, otherwise compile will fail with `argument 'is_causal' must be bool, not SymBool`
+ if is_causal is None:
+ is_causal = query.shape[2] > 1 and causal_mask is None
+
+ # Shapes (e.g. query.shape[2]) are tensors during jit tracing, resulting in `is_causal` being a tensor.
+ # We convert it to a bool for the SDPA kernel that only accepts bools.
+ if torch.jit.is_tracing() and isinstance(is_causal, torch.Tensor):
+ is_causal = is_causal.item()
+
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
+ query,
+ key,
+ value,
+ attn_mask=causal_mask,
+ dropout_p=dropout,
+ scale=scaling,
+ is_causal=is_causal,
+ )
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, None
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/spqr.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/spqr.py
new file mode 100644
index 0000000000000000000000000000000000000000..58b71740d37c77f24fe60ff65fe179b2737c4aa7
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/spqr.py
@@ -0,0 +1,122 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"SpQR (Sparse-Quantized Representation) integration file"
+
+from ..utils import is_accelerate_available, is_spqr_available, is_torch_available
+
+
+if is_torch_available():
+ import torch.nn as nn
+
+
+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 method. 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.Module` instance.
+ quantization_config (`SpQRConfig`):
+ The quantization config object that contains the quantization parameters.
+ modules_to_not_convert (`list[str]`, *optional*):
+ A list of nn.Linear weights to not convert. If a parameter path is in the list (e.g. `lm_head.weight`), the corresponding module will not be
+ converted.
+ current_key_name (`list`, *optional*):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+ if modules_to_not_convert is None:
+ modules_to_not_convert = []
+
+ if is_accelerate_available():
+ from accelerate import init_empty_weights
+ if is_spqr_available():
+ from spqr_quant import QuantizedLinear
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, nn.Linear):
+ # Check if the current key is not in the `modules_to_not_convert`
+ if ".".join(current_key_name) + ".weight" not in modules_to_not_convert:
+ with init_empty_weights():
+ tensor_name = ".".join(current_key_name)
+
+ shapes = quantization_config.shapes
+ shapes_keys = shapes.keys()
+
+ shapes_valid = (
+ f"{tensor_name}.dense_weights.shape" in shapes_keys
+ and f"{tensor_name}.row_offsets.shape" in shapes_keys
+ and f"{tensor_name}.col_vals.shape" in shapes_keys
+ and f"{tensor_name}.in_perm.shape" in shapes_keys
+ )
+
+ if not shapes_valid:
+ raise ValueError(
+ f"The SpQR quantization config does not contain the shape "
+ f"configuration for {tensor_name}. This indicates that the "
+ f"configuration is either invalid or corrupted."
+ )
+
+ dense_weights_shape = shapes[f"{tensor_name}.dense_weights.shape"]
+ row_offsets_shape = shapes[f"{tensor_name}.row_offsets.shape"]
+ col_vals_shape = shapes[f"{tensor_name}.col_vals.shape"]
+ in_perm_shape = shapes[f"{tensor_name}.in_perm.shape"]
+
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = QuantizedLinear.create_placehodler(
+ rows=out_features,
+ cols=in_features,
+ bits=quantization_config.bits,
+ beta1=quantization_config.beta1,
+ beta2=quantization_config.beta2,
+ dense_weights_shape=dense_weights_shape,
+ row_offsets_shape=row_offsets_shape,
+ col_vals_shape=col_vals_shape,
+ in_perm_shape=in_perm_shape,
+ )
+ has_been_replaced = True
+
+ # Store the module class in case we need to transpose the weight later
+ model._modules[name].source_cls = type(module)
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ else:
+ pass
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_spqr_linear(
+ module,
+ quantization_config=quantization_config,
+ modules_to_not_convert=modules_to_not_convert,
+ current_key_name=current_key_name,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/tiktoken.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/tiktoken.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f200bc355933bcb9ec119e08b560241fc1433c5
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/tiktoken.py
@@ -0,0 +1,43 @@
+from pathlib import Path
+from typing import Any
+
+from transformers.convert_slow_tokenizer import TikTokenConverter
+from transformers.tokenization_utils_fast import TIKTOKEN_VOCAB_FILE, TOKENIZER_FILE
+
+
+def convert_tiktoken_to_fast(encoding: Any, output_dir: str):
+ """
+ Converts given `tiktoken` encoding to `PretrainedTokenizerFast` and saves the configuration of converted tokenizer
+ on disk.
+
+ Args:
+ encoding (`str` or `tiktoken.Encoding`):
+ Tokenizer from `tiktoken` library. If `encoding` is `str`, the tokenizer will be loaded with
+ `tiktoken.get_encoding(encoding)`.
+ output_dir (`str`):
+ Save path for converted tokenizer configuration file.
+ """
+ output_dir = Path(output_dir)
+ output_dir.mkdir(exist_ok=True)
+
+ save_file = output_dir / "tiktoken" / TIKTOKEN_VOCAB_FILE
+ tokenizer_file = output_dir / TOKENIZER_FILE
+
+ save_file_absolute = str(save_file.absolute())
+ output_file_absolute = str(tokenizer_file.absolute())
+
+ try:
+ from tiktoken import get_encoding
+ from tiktoken.load import dump_tiktoken_bpe
+
+ if isinstance(encoding, str):
+ encoding = get_encoding(encoding)
+
+ dump_tiktoken_bpe(encoding._mergeable_ranks, save_file_absolute)
+ except ImportError:
+ raise ValueError("`tiktoken` is required to save a `tiktoken` file. Install it with `pip install tiktoken`.")
+
+ tokenizer = TikTokenConverter(
+ vocab_file=save_file_absolute, pattern=encoding._pat_str, additional_special_tokens=encoding._special_tokens
+ ).converted()
+ tokenizer.save(output_file_absolute)
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/tpu.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/tpu.py
new file mode 100644
index 0000000000000000000000000000000000000000..29262789dc98558ecc872b9e84cda4468e4b85ea
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/tpu.py
@@ -0,0 +1,36 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from torch.utils.data import DataLoader
+
+from ..utils import is_torch_xla_available
+
+
+def tpu_spmd_dataloader(dataloader: DataLoader):
+ if is_torch_xla_available():
+ import torch_xla.distributed.parallel_loader as pl
+
+ assert isinstance(
+ dataloader, pl.MpDeviceLoader
+ ), "The dataloader must be a `torch_xla.distributed.parallel_loader.MpDeviceLoader`."
+
+ # This is to support PyTorch/XLA FSDP via SPMD.
+ # Here we shard the input data's 0th dim across the fsdp axis.
+ import torch_xla.distributed.spmd as xs
+
+ sharding_spec = xs.ShardingSpec(xs.get_global_mesh(), ("fsdp", None))
+ dataloader._parallel_loader_kwargs["input_sharding"] = sharding_spec
+ return dataloader
+ else:
+ return dataloader
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/vptq.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/vptq.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa435517e81ebe3f9e624b45d34a601e512f5b1b
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/integrations/vptq.py
@@ -0,0 +1,101 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"VPTQ (Vector Post-Training Quantization) integration file"
+
+import torch.nn as nn
+from accelerate import init_empty_weights
+from vptq import VQuantLinear
+
+
+def replace_with_vptq_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 VPTQ quantized layers.
+ `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
+ conversion has been successfull or not.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`VptqConfig`):
+ The quantization config object that contains the quantization parameters.
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
+ Names of the modules to not convert in `VQuantLinear`. In practice we keep the `lm_head` in full precision
+ for numerical stability reasons.
+ current_key_name (`list`, *optional*):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+
+ modules_to_not_convert = ["lm_head"] if not modules_to_not_convert else modules_to_not_convert
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+ layer_name = ".".join(current_key_name)
+ shared_layer_config = quantization_config.shared_layer_config
+ config_for_layers = quantization_config.config_for_layers
+
+ if (
+ isinstance(module, nn.Linear)
+ and layer_name not in modules_to_not_convert
+ and ((layer_name in config_for_layers) or (current_key_name[-1] in shared_layer_config))
+ ):
+ layer_params = config_for_layers.get(layer_name, None) or shared_layer_config.get(
+ current_key_name[-1], None
+ )
+
+ with init_empty_weights():
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = VQuantLinear(
+ in_features,
+ out_features,
+ vector_lens=layer_params["vector_lens"],
+ num_centroids=layer_params["num_centroids"],
+ num_res_centroids=layer_params["num_res_centroids"],
+ group_num=layer_params["group_num"],
+ group_size=layer_params["group_size"],
+ outlier_size=layer_params["outlier_size"],
+ indices_as_float=layer_params["indices_as_float"],
+ enable_norm=layer_params["enable_norm"],
+ enable_perm=layer_params["enable_perm"],
+ is_indice_packed=True,
+ enable_proxy_error=False,
+ bias=module.bias is not None,
+ )
+ has_been_replaced = True
+
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_vptq_linear(
+ module,
+ quantization_config=quantization_config,
+ modules_to_not_convert=modules_to_not_convert,
+ current_key_name=current_key_name,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/keras_callbacks.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/keras_callbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6e832729a1eeb482d1193753cc2c07ad1f16c2e
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/keras_callbacks.py
@@ -0,0 +1,413 @@
+import logging
+import os
+from pathlib import Path
+from time import sleep
+from typing import Callable, List, Optional, Union
+
+import numpy as np
+import tensorflow as tf
+from huggingface_hub import Repository, create_repo
+from packaging.version import parse
+
+from . import IntervalStrategy, PreTrainedTokenizerBase
+from .modelcard import TrainingSummary
+from .modeling_tf_utils import keras
+
+
+logger = logging.getLogger(__name__)
+
+
+class KerasMetricCallback(keras.callbacks.Callback):
+ """
+ Callback to compute metrics at the end of every epoch. Unlike normal Keras metrics, these do not need to be
+ compilable by TF. It is particularly useful for common NLP metrics like BLEU and ROUGE that require string
+ operations or generation loops that cannot be compiled. Predictions (or generations) will be computed on the
+ `eval_dataset` before being passed to the `metric_fn` in `np.ndarray` format. The `metric_fn` should compute
+ metrics and return a dict mapping metric names to metric values.
+
+ We provide an example of a suitable metric_fn that computes ROUGE scores for a summarization model below. Note that
+ this example skips some post-processing for readability and simplicity, and should probably not be used as-is!
+
+ ```py
+ from datasets import load_metric
+
+ rouge_metric = load_metric("rouge")
+
+
+ def rouge_fn(predictions, labels):
+ decoded_predictions = tokenizer.batch_decode(predictions, skip_special_tokens=True)
+ decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
+ result = rouge_metric.compute(predictions=decoded_predictions, references=decoded_labels)
+ return {key: value.mid.fmeasure * 100 for key, value in result.items()}
+ ```
+
+ The above function will return a dict containing values which will be logged like any other Keras metric:
+
+ ```
+ {'rouge1': 37.4199, 'rouge2': 13.9768, 'rougeL': 34.361, 'rougeLsum': 35.0781
+ ```
+
+ Args:
+ metric_fn (`Callable`):
+ Metric function provided by the user. It will be called with two arguments - `predictions` and `labels`.
+ These contain the model's outputs and matching labels from the dataset. It should return a dict mapping
+ metric names to numerical values.
+ eval_dataset (`tf.data.Dataset` or `dict` or `tuple` or `np.ndarray` or `tf.Tensor`):
+ Validation data to be used to generate predictions for the `metric_fn`.
+ output_cols (`List[str], *optional*):
+ A list of columns to be retained from the model output as the predictions. Defaults to all.
+ label_cols ('`List[str]`, *optional*'):
+ A list of columns to be retained from the input dataset as the labels. Will be autodetected if this is not
+ supplied.
+ batch_size (`int`, *optional*):
+ Batch size. Only used when the data is not a pre-batched `tf.data.Dataset`.
+ predict_with_generate (`bool`, *optional*, defaults to `False`):
+ Whether we should use `model.generate()` to get outputs for the model.
+ use_xla_generation (`bool`, *optional*, defaults to `False`):
+ If we're generating, whether to compile model generation with XLA. This can massively increase the speed of
+ generation (up to 100X speedup) but will require a new XLA compilation for each input shape. When using XLA
+ generation, it's a good idea to pad your inputs to the same size, or to use the `pad_to_multiple_of`
+ argument in your `tokenizer` or `DataCollator`, which will reduce the number of unique input shapes and
+ save a lot of compilation time. This option has no effect is `predict_with_generate` is `False`.
+ generate_kwargs (`dict`, *optional*):
+ Keyword arguments to pass to `model.generate()` when generating. Has no effect if `predict_with_generate`
+ is `False`.
+
+ """
+
+ def __init__(
+ self,
+ metric_fn: Callable,
+ eval_dataset: Union[tf.data.Dataset, np.ndarray, tf.Tensor, tuple, dict],
+ output_cols: Optional[List[str]] = None,
+ label_cols: Optional[List[str]] = None,
+ batch_size: Optional[int] = None,
+ predict_with_generate: bool = False,
+ use_xla_generation: bool = False,
+ generate_kwargs: Optional[dict] = None,
+ ):
+ super().__init__()
+ self.metric_fn = metric_fn
+ self.batch_size = batch_size
+ if not isinstance(eval_dataset, tf.data.Dataset):
+ if batch_size is None:
+ raise ValueError(
+ "When passing data to KerasMetricCallback that is not a pre-batched tf.data.Dataset "
+ "the batch_size argument must be set."
+ )
+ # Wrap a tf.data.Dataset around it
+ eval_dataset = tf.data.Dataset.from_tensor_slices(eval_dataset).batch(batch_size, drop_remainder=False)
+ self.eval_dataset = eval_dataset
+ self.predict_with_generate = predict_with_generate
+ self.output_cols = output_cols
+
+ # This next block attempts to parse out which elements of the dataset should be appended to the labels list
+ # that is passed to the metric_fn
+ if isinstance(eval_dataset.element_spec, tuple) and len(eval_dataset.element_spec) == 2:
+ input_spec, label_spec = eval_dataset.element_spec
+ else:
+ input_spec = eval_dataset.element_spec
+ label_spec = None
+ if label_cols is not None:
+ for label in label_cols:
+ if label not in input_spec:
+ raise ValueError(f"Label {label} is in label_cols but could not be found in the dataset inputs!")
+ self.label_cols = label_cols
+ self.use_keras_label = False
+ elif label_spec is not None:
+ # If the dataset inputs are split into a 2-tuple of inputs and labels,
+ # assume the second element is the labels
+ self.label_cols = None
+ self.use_keras_label = True
+ elif "labels" in input_spec:
+ self.label_cols = ["labels"]
+ self.use_keras_label = False
+ logging.warning("No label_cols specified for KerasMetricCallback, assuming you want the 'labels' key.")
+ elif "start_positions" in input_spec and "end_positions" in input_spec:
+ self.label_cols = ["start_positions", "end_positions"]
+ self.use_keras_label = False
+ logging.warning(
+ "No label_cols specified for KerasMetricCallback, assuming you want the "
+ "start_positions and end_positions keys."
+ )
+ else:
+ raise ValueError("Could not autodetect label_cols for KerasMetricCallback, please specify them!")
+ if parse(tf.__version__) < parse("2.7"):
+ logging.warning("TF versions less than 2.7 may encounter issues with KerasMetricCallback!")
+
+ self.use_xla_generation = use_xla_generation
+ self.generate_kwargs = {} if generate_kwargs is None else generate_kwargs
+
+ self.generation_function = None
+
+ @staticmethod
+ def _concatenate_batches(batches, padding_index=-100):
+ # If all batches are unidimensional or same length, do a simple concatenation
+ if batches[0].ndim == 1 or all(batch.shape[1] == batches[0].shape[1] for batch in batches):
+ return np.concatenate(batches, axis=0)
+
+ # Welp, they're not the same length. Let's do some padding
+ max_len = max([batch.shape[1] for batch in batches])
+ num_samples = sum([batch.shape[0] for batch in batches])
+ output = np.full_like(
+ batches[0], fill_value=padding_index, shape=[num_samples, max_len] + list(batches[0].shape[2:])
+ )
+ # i keeps track of which part of the concatenated array we're writing the next batch to
+ i = 0
+ for batch in batches:
+ output[i : i + len(batch), : batch.shape[1]] = batch
+ i += len(batch)
+ return output
+
+ def _postprocess_predictions_or_labels(self, inputs):
+ if isinstance(inputs[0], dict):
+ outputs = {}
+ for key in inputs[0].keys():
+ outputs[key] = self._concatenate_batches([batch[key] for batch in inputs])
+ # If it's a dict with only one key, just return the array
+ if len(outputs) == 1:
+ outputs = list(outputs.values())[0]
+ elif isinstance(inputs[0], list) or isinstance(inputs[0], tuple):
+ outputs = []
+ for input_list in zip(*inputs):
+ outputs.append(self._concatenate_batches(input_list))
+ if len(outputs) == 1:
+ outputs = outputs[0] # If it's a list with only one element, just return the array
+ elif isinstance(inputs[0], np.ndarray):
+ outputs = self._concatenate_batches(inputs)
+ elif isinstance(inputs[0], tf.Tensor):
+ outputs = self._concatenate_batches([tensor.numpy() for tensor in inputs])
+ else:
+ raise TypeError(f"Couldn't handle batch of type {type(inputs[0])}!")
+ return outputs
+
+ def on_epoch_end(self, epoch, logs=None):
+ if hasattr(self.model, "config"):
+ ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
+ else:
+ ignore_keys = []
+
+ main_input_name = None
+ if self.predict_with_generate:
+ # This dense conditional recognizes the case where we have an encoder-decoder model, but
+ # avoids getting tangled up when we just have a model with a layer called 'encoder'
+ if hasattr(self.model, "encoder") and hasattr(self.model.encoder, "main_input_name"):
+ main_input_name = self.model.encoder.main_input_name
+ else:
+ main_input_name = getattr(self.model, "main_input_name", "input_ids")
+
+ if self.use_xla_generation and self.generation_function is None:
+
+ def generation_function(inputs, attention_mask):
+ return self.model.generate(inputs, attention_mask=attention_mask, **self.generate_kwargs)
+
+ self.generation_function = tf.function(generation_function, jit_compile=True)
+
+ prediction_list = []
+ label_list = []
+
+ # The whole predict/generate loop is handled inside this method
+ for batch in self.eval_dataset:
+ if isinstance(batch, tuple):
+ batch, labels = batch
+ else:
+ labels = None
+ if self.predict_with_generate:
+ if isinstance(batch, dict):
+ generation_inputs = batch[main_input_name]
+ attention_mask = batch.get("attention_mask", None)
+ else:
+ generation_inputs = batch
+ attention_mask = None
+ if self.use_xla_generation:
+ predictions = self.generation_function(generation_inputs, attention_mask=attention_mask)
+ else:
+ predictions = self.model.generate(
+ generation_inputs, attention_mask=attention_mask, **self.generate_kwargs
+ )
+ else:
+ predictions = self.model.predict_on_batch(batch)
+ if isinstance(predictions, dict):
+ # This converts any dict-subclass to a regular dict
+ # Keras REALLY doesn't like it when we pass around a BatchEncoding or other derived class
+ predictions = dict(predictions)
+ if self.output_cols is not None:
+ predictions = {key: predictions[key] for key in self.output_cols}
+ else:
+ predictions = {
+ key: val for key, val in predictions.items() if key not in ignore_keys + ["loss"]
+ }
+ prediction_list.append(predictions)
+ if not self.use_keras_label:
+ labels = {key: batch[key].numpy() for key in self.label_cols}
+ elif isinstance(labels, dict):
+ labels = {key: array.numpy() for key, array in labels.items()}
+ elif isinstance(labels, list) or isinstance(labels, tuple):
+ labels = [array.numpy() for array in labels]
+ elif isinstance(labels, tf.Tensor):
+ labels = labels.numpy()
+ else:
+ raise TypeError(f"Confused by labels of type {type(labels)}")
+ label_list.append(labels)
+
+ all_preds = self._postprocess_predictions_or_labels(prediction_list)
+ all_labels = self._postprocess_predictions_or_labels(label_list)
+
+ metric_output = self.metric_fn((all_preds, all_labels))
+ if not isinstance(metric_output, dict):
+ raise TypeError(
+ f"metric_fn should return a dict mapping metric names to values but instead returned {metric_output}"
+ )
+ # This is the critical bit - Keras passes a dict containing the loss and standard metric values for this epoch
+ # in the logs argument. Ordinarily, this is so the callback can read them, but in this case we write a bunch of
+ # new keys in there, which will then get read by the History callback and treated like any other metric value.
+ # I promise that I have it in writing from Chollet that this is okay.
+ logs.update(metric_output)
+
+
+class PushToHubCallback(keras.callbacks.Callback):
+ """
+ Callback that will save and push the model to the Hub regularly. By default, it pushes once per epoch, but this can
+ be changed with the `save_strategy` argument. Pushed models can be accessed like any other model on the hub, such
+ as with the `from_pretrained` method.
+
+ ```py
+ from transformers.keras_callbacks import PushToHubCallback
+
+ push_to_hub_callback = PushToHubCallback(
+ output_dir="./model_save",
+ tokenizer=tokenizer,
+ hub_model_id="gpt5-7xlarge",
+ )
+
+ model.fit(train_dataset, callbacks=[push_to_hub_callback])
+ ```
+
+ Args:
+ output_dir (`str`):
+ The output directory where the model predictions and checkpoints will be written and synced with the
+ repository on the Hub.
+ save_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"epoch"`):
+ The checkpoint save strategy to adopt during training. Possible values are:
+
+ - `"no"`: Save is done at the end of training.
+ - `"epoch"`: Save is done at the end of each epoch.
+ - `"steps"`: Save is done every `save_steps`
+ save_steps (`int`, *optional*):
+ The number of steps between saves when using the "steps" `save_strategy`.
+ tokenizer (`PreTrainedTokenizerBase`, *optional*):
+ The tokenizer used by the model. If supplied, will be uploaded to the repo alongside the weights.
+ hub_model_id (`str`, *optional*):
+ The name of the repository to keep in sync with the local `output_dir`. It can be a simple model ID in
+ which case the model will be pushed in your namespace. Otherwise it should be the whole repository name,
+ for instance `"user_name/model"`, which allows you to push to an organization you are a member of with
+ `"organization_name/model"`.
+
+ Will default to the name of `output_dir`.
+ hub_token (`str`, *optional*):
+ The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with
+ `huggingface-cli login`.
+ checkpoint (`bool`, *optional*, defaults to `False`):
+ Whether to save full training checkpoints (including epoch and optimizer state) to allow training to be
+ resumed. Only usable when `save_strategy` is `"epoch"`.
+ """
+
+ def __init__(
+ self,
+ output_dir: Union[str, Path],
+ save_strategy: Union[str, IntervalStrategy] = "epoch",
+ save_steps: Optional[int] = None,
+ tokenizer: Optional[PreTrainedTokenizerBase] = None,
+ hub_model_id: Optional[str] = None,
+ hub_token: Optional[str] = None,
+ checkpoint: bool = False,
+ **model_card_args,
+ ):
+ super().__init__()
+ if checkpoint and save_strategy != "epoch":
+ raise ValueError("Cannot save checkpoints when save_strategy is not 'epoch'!")
+ if isinstance(save_strategy, str):
+ save_strategy = IntervalStrategy(save_strategy.lower())
+ self.save_strategy = save_strategy
+ if self.save_strategy == IntervalStrategy.STEPS and (not isinstance(save_steps, int) or save_steps <= 0):
+ raise ValueError("Please supply a positive integer argument for save_steps when save_strategy == 'steps'!")
+ self.save_steps = save_steps
+ output_dir = Path(output_dir)
+
+ # Create repo and retrieve repo_id
+ if hub_model_id is None:
+ hub_model_id = output_dir.absolute().name
+ self.hub_model_id = create_repo(repo_id=hub_model_id, exist_ok=True, token=hub_token).repo_id
+
+ self.output_dir = output_dir
+ self.repo = Repository(str(self.output_dir), clone_from=self.hub_model_id, token=hub_token)
+
+ self.tokenizer = tokenizer
+ self.last_job = None
+ self.checkpoint = checkpoint
+ self.training_history = None
+ self.model_card_args = model_card_args
+
+ def on_train_begin(self, logs=None):
+ # Although we can access model.history, we have no guarantees that the History callback will fire before this
+ # one, so we keep track of it here too
+ self.training_history = []
+
+ def on_train_batch_end(self, batch, logs=None):
+ if self.save_strategy == IntervalStrategy.STEPS and (batch + 1) % self.save_steps == 0:
+ if self.last_job is not None and not self.last_job.is_done:
+ return # The last upload is still running, don't start another
+ self.model.save_pretrained(self.output_dir)
+ if self.tokenizer is not None:
+ self.tokenizer.save_pretrained(self.output_dir)
+ _, self.last_job = self.repo.push_to_hub(
+ commit_message=f"Training in progress steps {batch}", blocking=False
+ )
+
+ def on_epoch_end(self, epoch, logs=None):
+ logs = logs.copy() # Don't accidentally write things that Keras will read later
+ if "epoch" not in logs:
+ logs["epoch"] = epoch
+ self.training_history.append(logs)
+ if self.save_strategy == IntervalStrategy.EPOCH:
+ if self.last_job is not None and not self.last_job.is_done:
+ return # The last upload is still running, don't start another
+ self.model.save_pretrained(self.output_dir)
+ if self.tokenizer is not None:
+ self.tokenizer.save_pretrained(self.output_dir)
+ if self.checkpoint:
+ checkpoint_dir = os.path.join(self.output_dir, "checkpoint")
+ self.model._save_checkpoint(checkpoint_dir, epoch)
+ train_summary = TrainingSummary.from_keras(
+ model=self.model,
+ model_name=self.hub_model_id,
+ keras_history=self.training_history,
+ **self.model_card_args,
+ )
+ model_card = train_summary.to_model_card()
+ with (self.output_dir / "README.md").open("w") as f:
+ f.write(model_card)
+ _, self.last_job = self.repo.push_to_hub(
+ commit_message=f"Training in progress epoch {epoch}", blocking=False
+ )
+
+ def on_train_end(self, logs=None):
+ # Makes sure the latest version of the model is uploaded
+ if self.last_job is not None and not self.last_job.is_done:
+ logging.info("Pushing the last epoch to the Hub, this may take a while...")
+ while not self.last_job.is_done:
+ sleep(1)
+ else:
+ self.model.save_pretrained(self.output_dir)
+ if self.tokenizer is not None:
+ self.tokenizer.save_pretrained(self.output_dir)
+ train_summary = TrainingSummary.from_keras(
+ model=self.model,
+ model_name=self.hub_model_id,
+ keras_history=self.training_history,
+ **self.model_card_args,
+ )
+ model_card = train_summary.to_model_card()
+ with (self.output_dir / "README.md").open("w") as f:
+ f.write(model_card)
+ self.repo.push_to_hub(commit_message="End of training", blocking=True)
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/__init__.py b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..388a73d22d4c9b561e2a887b50a1897b8cf2def9
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp
@@ -0,0 +1,40 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+
+#include
+#include
+
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h
new file mode 100644
index 0000000000000000000000000000000000000000..7eac8c8bcd1bf529bb9c13d54d2d4215c9e4c89f
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h
@@ -0,0 +1,32 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
+
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu
new file mode 100644
index 0000000000000000000000000000000000000000..c2b3a462a1a06338d4a04c33a6867fcad42248e6
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu
@@ -0,0 +1,159 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+#include "cuda/ms_deform_im2col_cuda.cuh"
+
+#include
+#include
+#include
+#include
+
+#pragma once
+#include
+
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ at::DeviceGuard guard(value.device());
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.is_cuda(), "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
+
+ const int batch_n = im2col_step_;
+ auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, value.scalar_type(), "ms_deform_attn_forward_cuda", ([&] {
+ ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
+ value.data_ptr() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data_ptr(),
+ level_start_index.data_ptr(),
+ sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ columns.data_ptr());
+
+ }));
+ }
+
+ output = output.view({batch, num_query, num_heads*channels});
+
+ return output;
+}
+
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ at::DeviceGuard guard(value.device());
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.is_cuda(), "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.is_cuda(), "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto grad_value = at::zeros_like(value);
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
+ auto grad_attn_weight = at::zeros_like(attn_weight);
+
+ const int batch_n = im2col_step_;
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, value.scalar_type(), "ms_deform_attn_backward_cuda", ([&] {
+ ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
+ grad_output_g.data_ptr(),
+ value.data_ptr() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data_ptr(),
+ level_start_index.data_ptr(),
+ sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ grad_value.data_ptr() + n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size);
+
+ }));
+ }
+
+ return {
+ grad_value, grad_sampling_loc, grad_attn_weight
+ };
+}
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..20ae6892e4b9881578a72aae27ddc4ec9f68ae1c
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh
@@ -0,0 +1,1467 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+
+#include
+#include
+
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+
+#define CUDA_KERNEL_LOOP(i, n) \
+ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
+ i < (n); \
+ i += blockDim.x * gridDim.x)
+
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.is_cuda(), "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
+
+ const int batch_n = im2col_step_;
+ auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, value.scalar_type(), "ms_deform_attn_forward_cuda", ([&] {
+ ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
+ value.data_ptr() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data_ptr(),
+ level_start_index.data_ptr(),
+ sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ columns.data_ptr());
+
+ }));
+ }
+
+ output = output.view({batch, num_query, num_heads*channels});
+
+ return output;
+}
+
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.is_cuda(), "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.is_cuda(), "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto grad_value = at::zeros_like(value);
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
+ auto grad_attn_weight = at::zeros_like(attn_weight);
+
+ const int batch_n = im2col_step_;
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, value.scalar_type(), "ms_deform_attn_backward_cuda", ([&] {
+ ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
+ grad_output_g.data_ptr(),
+ value.data_ptr() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data_ptr(),
+ level_start_index.data_ptr(),
+ sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ grad_value.data_ptr() + n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size);
+
+ }));
+ }
+
+ return {
+ grad_value, grad_sampling_loc, grad_attn_weight
+ };
+}
+
+const int CUDA_NUM_THREADS = 1024;
+inline int GET_BLOCKS(const int N, const int num_threads)
+{
+ return (N + num_threads - 1) / num_threads;
+}
+
+
+template
+__device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ }
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ return val;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ *grad_attn_weight = top_grad * val;
+ *grad_sampling_loc = width * grad_w_weight * top_grad_value;
+ *(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ atomicAdd(grad_attn_weight, top_grad * val);
+ atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
+ atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
+}
+
+
+template
+__global__ void ms_deformable_im2col_gpu_kernel(const int n,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *data_col)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ scalar_t *data_col_ptr = data_col + index;
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+ scalar_t col = 0;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
+ }
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ }
+ }
+ *data_col_ptr = col;
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockSize; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockSize/2; s>0; s>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockDim.x; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
+ atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
+ atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear_gm(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ grad_sampling_loc, grad_attn_weight);
+ }
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+void ms_deformable_im2col_cuda(cudaStream_t stream,
+ const scalar_t* data_value,
+ const int64_t* data_spatial_shapes,
+ const int64_t* data_level_start_index,
+ const scalar_t* data_sampling_loc,
+ const scalar_t* data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* data_col)
+{
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ const int num_threads = CUDA_NUM_THREADS;
+ ms_deformable_im2col_gpu_kernel
+ <<>>(
+ num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
+
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
+
+template
+void ms_deformable_col2im_cuda(cudaStream_t stream,
+ const scalar_t* grad_col,
+ const scalar_t* data_value,
+ const int64_t * data_spatial_shapes,
+ const int64_t * data_level_start_index,
+ const scalar_t * data_sampling_loc,
+ const scalar_t * data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ if (channels > 1024)
+ {
+ if ((channels & 1023) == 0)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_gm
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ else{
+ switch(channels)
+ {
+ case 1:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 2:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 4:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 8:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 16:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 32:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 64:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 128:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 256:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 512:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 1024:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ default:
+ if (channels < 64)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ }
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h
new file mode 100644
index 0000000000000000000000000000000000000000..d8c21b4e54dcd7071f5fd27f62410326ac069a94
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h
@@ -0,0 +1,46 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+at::Tensor ms_deform_attn_cuda_forward_bf16(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
+
+std::vector ms_deform_attn_cuda_backward_bf16(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..4fb544bf791ddae79238924df591b7a33f3cccdd
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh
@@ -0,0 +1,1327 @@
+/*!
+**************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************
+* Modified from DCN (https://github.com/msracver/Deformable-ConvNets)
+* Copyright (c) 2018 Microsoft
+**************************************************************************
+*/
+
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+
+#define CUDA_KERNEL_LOOP(i, n) \
+ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
+ i < (n); \
+ i += blockDim.x * gridDim.x)
+
+const int CUDA_NUM_THREADS = 1024;
+inline int GET_BLOCKS(const int N, const int num_threads)
+{
+ return (N + num_threads - 1) / num_threads;
+}
+
+
+template
+__device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ }
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ return val;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ *grad_attn_weight = top_grad * val;
+ *grad_sampling_loc = width * grad_w_weight * top_grad_value;
+ *(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ atomicAdd(grad_attn_weight, top_grad * val);
+ atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
+ atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
+}
+
+
+template
+__global__ void ms_deformable_im2col_gpu_kernel(const int n,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *data_col)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ scalar_t *data_col_ptr = data_col + index;
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+ scalar_t col = 0;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
+ }
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ }
+ }
+ *data_col_ptr = col;
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockSize; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockSize/2; s>0; s>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockDim.x; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
+ atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
+ atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear_gm(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ grad_sampling_loc, grad_attn_weight);
+ }
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+void ms_deformable_im2col_cuda(cudaStream_t stream,
+ const scalar_t* data_value,
+ const int64_t* data_spatial_shapes,
+ const int64_t* data_level_start_index,
+ const scalar_t* data_sampling_loc,
+ const scalar_t* data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* data_col)
+{
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ const int num_threads = CUDA_NUM_THREADS;
+ ms_deformable_im2col_gpu_kernel
+ <<>>(
+ num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
+
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
+
+template
+void ms_deformable_col2im_cuda(cudaStream_t stream,
+ const scalar_t* grad_col,
+ const scalar_t* data_value,
+ const int64_t * data_spatial_shapes,
+ const int64_t * data_level_start_index,
+ const scalar_t * data_sampling_loc,
+ const scalar_t * data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ if (channels > 1024)
+ {
+ if ((channels & 1023) == 0)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_gm
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ else{
+ switch(channels)
+ {
+ case 1:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 2:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 4:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 8:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 16:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 32:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 64:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 128:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 256:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 512:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 1024:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ default:
+ if (channels < 64)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ }
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/ms_deform_attn.h b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/ms_deform_attn.h
new file mode 100644
index 0000000000000000000000000000000000000000..e649e65e37ae58d789a4cfb396e715ff2e33477f
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/ms_deform_attn.h
@@ -0,0 +1,61 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+
+#include "cpu/ms_deform_attn_cpu.h"
+
+#ifdef WITH_CUDA
+#include "cuda/ms_deform_attn_cuda.h"
+#endif
+
+
+at::Tensor
+ms_deform_attn_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ if (value.is_cuda())
+ {
+#ifdef WITH_CUDA
+ return ms_deform_attn_cuda_forward(
+ value, spatial_shapes, level_start_index, sampling_loc, attn_weight, im2col_step);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ }
+ AT_ERROR("Not implemented on the CPU");
+}
+
+std::vector
+ms_deform_attn_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ if (value.is_cuda())
+ {
+#ifdef WITH_CUDA
+ return ms_deform_attn_cuda_backward(
+ value, spatial_shapes, level_start_index, sampling_loc, attn_weight, grad_output, im2col_step);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ }
+ AT_ERROR("Not implemented on the CPU");
+}
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/vision.cpp b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/vision.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..6ce3875568b9ba8d660c90acc805077cca98f891
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deformable_detr/vision.cpp
@@ -0,0 +1,16 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include "ms_deform_attn.h"
+
+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("ms_deform_attn_forward", &ms_deform_attn_forward, "ms_deform_attn_forward");
+ m.def("ms_deform_attn_backward", &ms_deform_attn_backward, "ms_deform_attn_backward");
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.cpp b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..388a73d22d4c9b561e2a887b50a1897b8cf2def9
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.cpp
@@ -0,0 +1,40 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+
+#include
+#include
+
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.h b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.h
new file mode 100644
index 0000000000000000000000000000000000000000..7eac8c8bcd1bf529bb9c13d54d2d4215c9e4c89f
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.h
@@ -0,0 +1,32 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
+
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cu b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cu
new file mode 100644
index 0000000000000000000000000000000000000000..8ea1d7fabe2684dbb85f00fae2c47b469687cb2c
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cu
@@ -0,0 +1,156 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+#include "cuda/ms_deform_im2col_cuda.cuh"
+
+#include
+#include
+#include
+#include
+
+#pragma once
+#include
+
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
+
+ const int batch_n = im2col_step_;
+ auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_forward_cuda", ([&] {
+ ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(),
+ level_start_index.data(),
+ sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ columns.data());
+
+ }));
+ }
+
+ output = output.view({batch, num_query, num_heads*channels});
+
+ return output;
+}
+
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.type().is_cuda(), "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto grad_value = at::zeros_like(value);
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
+ auto grad_attn_weight = at::zeros_like(attn_weight);
+
+ const int batch_n = im2col_step_;
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_backward_cuda", ([&] {
+ ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
+ grad_output_g.data(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(),
+ level_start_index.data(),
+ sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ grad_value.data() + n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data() + n * im2col_step_ * per_attn_weight_size);
+
+ }));
+ }
+
+ return {
+ grad_value, grad_sampling_loc, grad_attn_weight
+ };
+}
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cuh b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..34f8ae9cb77bbaa8cb4dd25e0cb86632db9ad05d
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cuh
@@ -0,0 +1,1467 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+
+#include
+#include
+
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+
+#define CUDA_KERNEL_LOOP(i, n) \
+ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
+ i < (n); \
+ i += blockDim.x * gridDim.x)
+
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
+
+ const int batch_n = im2col_step_;
+ auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_forward_cuda", ([&] {
+ ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(),
+ level_start_index.data(),
+ sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ columns.data());
+
+ }));
+ }
+
+ output = output.view({batch, num_query, num_heads*channels});
+
+ return output;
+}
+
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.type().is_cuda(), "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto grad_value = at::zeros_like(value);
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
+ auto grad_attn_weight = at::zeros_like(attn_weight);
+
+ const int batch_n = im2col_step_;
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_backward_cuda", ([&] {
+ ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
+ grad_output_g.data(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(),
+ level_start_index.data(),
+ sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ grad_value.data() + n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data() + n * im2col_step_ * per_attn_weight_size);
+
+ }));
+ }
+
+ return {
+ grad_value, grad_sampling_loc, grad_attn_weight
+ };
+}
+
+const int CUDA_NUM_THREADS = 1024;
+inline int GET_BLOCKS(const int N, const int num_threads)
+{
+ return (N + num_threads - 1) / num_threads;
+}
+
+
+template
+__device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ }
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ return val;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ *grad_attn_weight = top_grad * val;
+ *grad_sampling_loc = width * grad_w_weight * top_grad_value;
+ *(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ atomicAdd(grad_attn_weight, top_grad * val);
+ atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
+ atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
+}
+
+
+template
+__global__ void ms_deformable_im2col_gpu_kernel(const int n,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *data_col)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ scalar_t *data_col_ptr = data_col + index;
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+ scalar_t col = 0;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
+ }
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ }
+ }
+ *data_col_ptr = col;
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockSize; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockSize/2; s>0; s>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockDim.x; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
+ atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
+ atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear_gm(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ grad_sampling_loc, grad_attn_weight);
+ }
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+void ms_deformable_im2col_cuda(cudaStream_t stream,
+ const scalar_t* data_value,
+ const int64_t* data_spatial_shapes,
+ const int64_t* data_level_start_index,
+ const scalar_t* data_sampling_loc,
+ const scalar_t* data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* data_col)
+{
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ const int num_threads = CUDA_NUM_THREADS;
+ ms_deformable_im2col_gpu_kernel
+ <<>>(
+ num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
+
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
+
+template
+void ms_deformable_col2im_cuda(cudaStream_t stream,
+ const scalar_t* grad_col,
+ const scalar_t* data_value,
+ const int64_t * data_spatial_shapes,
+ const int64_t * data_level_start_index,
+ const scalar_t * data_sampling_loc,
+ const scalar_t * data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ if (channels > 1024)
+ {
+ if ((channels & 1023) == 0)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_gm
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ else{
+ switch(channels)
+ {
+ case 1:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 2:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 4:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 8:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 16:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 32:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 64:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 128:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 256:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 512:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 1024:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ default:
+ if (channels < 64)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ }
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.h b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.h
new file mode 100644
index 0000000000000000000000000000000000000000..fbcf4543e66bb1162f42ce2ae57e1bac92243cb4
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.h
@@ -0,0 +1,29 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
diff --git a/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_im2col_cuda.cuh b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_im2col_cuda.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..c0db0c88c9db2c09d7f601937ea0f6ac480913bf
--- /dev/null
+++ b/tasks/tasksmith-e0f68dd4420c/environment/source/src/transformers/kernels/deta/cuda/ms_deform_im2col_cuda.cuh
@@ -0,0 +1,1327 @@
+/*!
+**************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************
+* Modified from DCN (https://github.com/msracver/Deformable-ConvNets)
+* Copyright (c) 2018 Microsoft
+**************************************************************************
+*/
+
+#include
+#include
+#include
+
+#include
+#include