code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optiona... |
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (... | forward | python | huggingface/transformers | examples/modular-transformers/modeling_dummy_bert.py | https://github.com/huggingface/transformers/blob/master/examples/modular-transformers/modeling_dummy_bert.py | Apache-2.0 |
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
"""
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
images. This method is also adapted to support torch.jit tracing.
... |
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
images. This method is also adapted to support torch.jit tracing.
Adapted from:
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362... | interpolate_pos_encoding | python | huggingface/transformers | examples/modular-transformers/modeling_multimodal2.py | https://github.com/huggingface/transformers/blob/master/examples/modular-transformers/modeling_multimodal2.py | Apache-2.0 |
def forward(
self,
pixel_values: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
interpolate_pos_encoding: bool = False,
) -> BaseModelOutputWithPooling:
r"""
Returns:
Examples... |
Returns:
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, Multimodal2VisionModel
>>> model = Multimodal2VisionModel.from_pretrained("openai/multimodal2-vit-base-patch32")
>>> processor = Auto... | forward | python | huggingface/transformers | examples/modular-transformers/modeling_multimodal2.py | https://github.com/huggingface/transformers/blob/master/examples/modular-transformers/modeling_multimodal2.py | Apache-2.0 |
def get_image_features(self, pixel_values: torch.FloatTensor):
"""
Obtains image last hidden states from the vision tower and apply multimodal projection.
Args:
pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
The tensors correspond... |
Obtains image last hidden states from the vision tower and apply multimodal projection.
Args:
pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
The tensors corresponding to the input images.
Returns:
image_features (`tor... | get_image_features | python | huggingface/transformers | examples/modular-transformers/modeling_new_task_model.py | https://github.com/huggingface/transformers/blob/master/examples/modular-transformers/modeling_new_task_model.py | Apache-2.0 |
def forward(
self,
input_ids: torch.LongTensor = None,
pixel_values: torch.FloatTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None,
... |
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are igno... | forward | python | huggingface/transformers | examples/modular-transformers/modeling_new_task_model.py | https://github.com/huggingface/transformers/blob/master/examples/modular-transformers/modeling_new_task_model.py | Apache-2.0 |
def forward(
self,
input_ids: torch.LongTensor = None,
pixel_values: torch.FloatTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Union[list[torch.FloatTensor], Cache]] = None,
... |
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are igno... | forward | python | huggingface/transformers | examples/modular-transformers/modeling_new_task_model.py | https://github.com/huggingface/transformers/blob/master/examples/modular-transformers/modeling_new_task_model.py | Apache-2.0 |
def replace_batch_norm(model):
r"""
Recursively replace all `torch.nn.BatchNorm2d` with `TestDetrFrozenBatchNorm2d`.
Args:
model (torch.nn.Module):
input model
"""
for name, module in model.named_children():
if isinstance(module, nn.BatchNorm2d):
new_module =... |
Recursively replace all `torch.nn.BatchNorm2d` with `TestDetrFrozenBatchNorm2d`.
Args:
model (torch.nn.Module):
input model
| replace_batch_norm | python | huggingface/transformers | examples/modular-transformers/modeling_test_detr.py | https://github.com/huggingface/transformers/blob/master/examples/modular-transformers/modeling_test_detr.py | Apache-2.0 |
def gen_encoder_output_proposals(self, enc_output, padding_mask, spatial_shapes):
"""Generate the encoder output proposals from encoded enc_output.
Args:
enc_output (Tensor[batch_size, sequence_length, hidden_size]): Output of the encoder.
padding_mask (Tensor[batch_size, sequen... | Generate the encoder output proposals from encoded enc_output.
Args:
enc_output (Tensor[batch_size, sequence_length, hidden_size]): Output of the encoder.
padding_mask (Tensor[batch_size, sequence_length]): Padding mask for `enc_output`.
spatial_shapes (List[Tuple[int, int]]... | gen_encoder_output_proposals | python | huggingface/transformers | examples/modular-transformers/modeling_test_detr.py | https://github.com/huggingface/transformers/blob/master/examples/modular-transformers/modeling_test_detr.py | Apache-2.0 |
def forward(
self,
pixel_values: torch.FloatTensor,
pixel_mask: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.FloatTensor] = None,
encoder_outputs: Optional[torch.FloatTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
d... |
Returns:
Examples:
```python
>>> from transformers import AutoImageProcessor, TestDetrModel
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream... | forward | python | huggingface/transformers | examples/modular-transformers/modeling_test_detr.py | https://github.com/huggingface/transformers/blob/master/examples/modular-transformers/modeling_test_detr.py | Apache-2.0 |
def sanity_check_tensor_sync(
tensor: torch.Tensor, mesh: DeviceMesh, rtol: float = 1e-4, atol: float = 1e-4, not_sync: bool = False
) -> None:
"""
Verify that a tensor is synchronized (or not synchronized) across all processes in the mesh's process group.
Handles both regular tensors and DTensors.
... |
Verify that a tensor is synchronized (or not synchronized) across all processes in the mesh's process group.
Handles both regular tensors and DTensors.
Args:
tensor (torch.Tensor): The tensor to check for synchronization (can be DTensor)
mesh (DeviceMesh): The device mesh containing the pr... | sanity_check_tensor_sync | python | huggingface/transformers | examples/pytorch/3d_parallel_checks.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/3d_parallel_checks.py | Apache-2.0 |
def check_params_sync(model_params, original_params):
"""
Check if original_params are being updated in sync with model parameters.
Args:
model_params: Iterator of model parameters after update
original_params: List of original parameters before DDP wrapping
"""
for mp, op in zip(mo... |
Check if original_params are being updated in sync with model parameters.
Args:
model_params: Iterator of model parameters after update
original_params: List of original parameters before DDP wrapping
| check_params_sync | python | huggingface/transformers | examples/pytorch/3d_parallel_checks.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/3d_parallel_checks.py | Apache-2.0 |
def get_parameters(model: nn.Module) -> Iterable[torch.Tensor]:
"""
Get all parameters from a model by iterating over its modules.
This is an alternative to model.parameters() that works with DTensor models.
Args:
model (nn.Module): The model to get parameters from
Returns:
Iterabl... |
Get all parameters from a model by iterating over its modules.
This is an alternative to model.parameters() that works with DTensor models.
Args:
model (nn.Module): The model to get parameters from
Returns:
Iterable[torch.Tensor]: An iterator over all parameters in the model
| get_parameters | python | huggingface/transformers | examples/pytorch/3d_parallel_checks.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/3d_parallel_checks.py | Apache-2.0 |
def update_model_parameters(model: nn.Module) -> None:
"""
Update model._parameters using named_modules() to ensure all parameters are properly tracked.
Args:
model (nn.Module): The model to update parameters for
"""
# Clear existing parameters
model._parameters = {}
# Add paramete... |
Update model._parameters using named_modules() to ensure all parameters are properly tracked.
Args:
model (nn.Module): The model to update parameters for
| update_model_parameters | python | huggingface/transformers | examples/pytorch/3d_parallel_checks.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/3d_parallel_checks.py | Apache-2.0 |
def __init__(
self,
image_processor: AutoImageProcessor,
id2label: Mapping[int, str],
threshold: float = 0.0,
):
"""
Initialize evaluator with image processor, id2label mapping and threshold for filtering predictions.
Args:
image_processor (AutoIm... |
Initialize evaluator with image processor, id2label mapping and threshold for filtering predictions.
Args:
image_processor (AutoImageProcessor): Image processor for
`post_process_instance_segmentation` method.
id2label (Mapping[int, str]): Mapping from class id ... | __init__ | python | huggingface/transformers | examples/pytorch/instance-segmentation/run_instance_segmentation.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/instance-segmentation/run_instance_segmentation.py | Apache-2.0 |
def postprocess_target_batch(self, target_batch) -> list[dict[str, torch.Tensor]]:
"""Collect targets in a form of list of dictionaries with keys "masks", "labels"."""
batch_masks = target_batch[0]
batch_labels = target_batch[1]
post_processed_targets = []
for masks, labels in zi... | Collect targets in a form of list of dictionaries with keys "masks", "labels". | postprocess_target_batch | python | huggingface/transformers | examples/pytorch/instance-segmentation/run_instance_segmentation.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/instance-segmentation/run_instance_segmentation.py | Apache-2.0 |
def postprocess_prediction_batch(self, prediction_batch, target_sizes) -> list[dict[str, torch.Tensor]]:
"""Collect predictions in a form of list of dictionaries with keys "masks", "labels", "scores"."""
model_output = ModelOutput(class_queries_logits=prediction_batch[0], masks_queries_logits=predictio... | Collect predictions in a form of list of dictionaries with keys "masks", "labels", "scores". | postprocess_prediction_batch | python | huggingface/transformers | examples/pytorch/instance-segmentation/run_instance_segmentation.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/instance-segmentation/run_instance_segmentation.py | Apache-2.0 |
def __call__(self, evaluation_results: EvalPrediction, compute_result: bool = False) -> Mapping[str, float]:
"""
Update metrics with current evaluation results and return metrics if `compute_result` is True.
Args:
evaluation_results (EvalPrediction): Predictions and targets from eva... |
Update metrics with current evaluation results and return metrics if `compute_result` is True.
Args:
evaluation_results (EvalPrediction): Predictions and targets from evaluation.
compute_result (bool): Whether to compute and return metrics.
Returns:
Mapping... | __call__ | python | huggingface/transformers | examples/pytorch/instance-segmentation/run_instance_segmentation.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/instance-segmentation/run_instance_segmentation.py | Apache-2.0 |
def find_last_checkpoint(training_args: TrainingArguments) -> Optional[str]:
"""Find the last checkpoint in the output directory according to parameters specified in `training_args`."""
checkpoint = None
if training_args.resume_from_checkpoint is not None:
checkpoint = training_args.resume_from_che... | Find the last checkpoint in the output directory according to parameters specified in `training_args`. | find_last_checkpoint | python | huggingface/transformers | examples/pytorch/instance-segmentation/run_instance_segmentation.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/instance-segmentation/run_instance_segmentation.py | Apache-2.0 |
def handle_repository_creation(accelerator: Accelerator, args: argparse.Namespace):
"""Create a repository for the model and dataset if `args.push_to_hub` is set."""
repo_id = None
if accelerator.is_main_process:
if args.push_to_hub:
# Retrieve of infer repo_name
repo_name =... | Create a repository for the model and dataset if `args.push_to_hub` is set. | handle_repository_creation | python | huggingface/transformers | examples/pytorch/instance-segmentation/run_instance_segmentation_no_trainer.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/instance-segmentation/run_instance_segmentation_no_trainer.py | Apache-2.0 |
def fim_transform(example):
"""
This function performs FIM transformation on a single example (list of tokens)
"""
if np_rng.binomial(1, data_args.fim_rate):
boundaries = sorted(np_rng.randint(low=0, high=len(example) + 1, size=2))
prefix = example[: boundaries[0... |
This function performs FIM transformation on a single example (list of tokens)
| fim_transform | python | huggingface/transformers | examples/pytorch/language-modeling/run_fim.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/language-modeling/run_fim.py | Apache-2.0 |
def apply_fim(examples):
"""
Apply FIM transformation to a batch of examples
"""
fim_transform_ids = [fim_transform(ids) for ids in examples["input_ids"]]
examples["input_ids"] = fim_transform_ids
examples["labels"] = fim_transform_ids
# If your application requir... |
Apply FIM transformation to a batch of examples
| apply_fim | python | huggingface/transformers | examples/pytorch/language-modeling/run_fim.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/language-modeling/run_fim.py | Apache-2.0 |
def format_image_annotations_as_coco(
image_id: str, categories: list[int], areas: list[float], bboxes: list[tuple[float]]
) -> dict:
"""Format one set of image annotations to the COCO format
Args:
image_id (str): image id. e.g. "0001"
categories (List[int]): list of categories/class labels... | Format one set of image annotations to the COCO format
Args:
image_id (str): image id. e.g. "0001"
categories (List[int]): list of categories/class labels corresponding to provided bounding boxes
areas (List[float]): list of corresponding areas to provided bounding boxes
bboxes (Lis... | format_image_annotations_as_coco | python | huggingface/transformers | examples/pytorch/object-detection/run_object_detection.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/object-detection/run_object_detection.py | Apache-2.0 |
def augment_and_transform_batch(
examples: Mapping[str, Any],
transform: A.Compose,
image_processor: AutoImageProcessor,
return_pixel_mask: bool = False,
) -> BatchFeature:
"""Apply augmentations and format annotations in COCO format for object detection task"""
images = []
annotations = []... | Apply augmentations and format annotations in COCO format for object detection task | augment_and_transform_batch | python | huggingface/transformers | examples/pytorch/object-detection/run_object_detection.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/object-detection/run_object_detection.py | Apache-2.0 |
def nested_to_cpu(objects):
"""Move nested tesnors in objects to CPU if they are on GPU"""
if isinstance(objects, torch.Tensor):
return objects.cpu()
elif isinstance(objects, Mapping):
return type(objects)({k: nested_to_cpu(v) for k, v in objects.items()})
elif isinstance(objects, (list,... | Move nested tesnors in objects to CPU if they are on GPU | nested_to_cpu | python | huggingface/transformers | examples/pytorch/object-detection/run_object_detection_no_trainer.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/object-detection/run_object_detection_no_trainer.py | Apache-2.0 |
def reduce_labels_transform(labels: np.ndarray, **kwargs) -> np.ndarray:
"""Set `0` label as with value 255 and then reduce all other labels by 1.
Example:
Initial class labels: 0 - background; 1 - road; 2 - car;
Transformed class labels: 255 - background; 0 - road; 1 - car;
**kw... | Set `0` label as with value 255 and then reduce all other labels by 1.
Example:
Initial class labels: 0 - background; 1 - road; 2 - car;
Transformed class labels: 255 - background; 0 - road; 1 - car;
**kwargs are required to use this function with albumentations.
| reduce_labels_transform | python | huggingface/transformers | examples/pytorch/semantic-segmentation/run_semantic_segmentation.py | https://github.com/huggingface/transformers/blob/master/examples/pytorch/semantic-segmentation/run_semantic_segmentation.py | Apache-2.0 |
def _replace_with_int8_symmetric_linear(
model,
modules_to_not_convert=None,
current_key_name=None,
quantization_config=None,
has_been_replaced=False,
pre_quantized=False,
):
"""
Recursively replaces nn.Linear modules with Int8SymmetricLinear modules.
"""
if current_key_name is N... |
Recursively replaces nn.Linear modules with Int8SymmetricLinear modules.
| _replace_with_int8_symmetric_linear | python | huggingface/transformers | examples/quantization/custom_quantization_int8_example.py | https://github.com/huggingface/transformers/blob/master/examples/quantization/custom_quantization_int8_example.py | Apache-2.0 |
def replace_with_int8_symmetric_linear(
model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, pre_quantized=False
):
"""
Main function to replace model layers with INT8 symmetric quantized versions.
"""
modules_to_not_convert = ["lm_head"] if modules_to_not_convert is ... |
Main function to replace model layers with INT8 symmetric quantized versions.
| replace_with_int8_symmetric_linear | python | huggingface/transformers | examples/quantization/custom_quantization_int8_example.py | https://github.com/huggingface/transformers/blob/master/examples/quantization/custom_quantization_int8_example.py | Apache-2.0 |
def _process_model_before_weight_loading(self, model, **kwargs):
"""
Replace model's linear layers with quantized versions before loading weights.
"""
self.modules_to_not_convert = self.quantization_config.modules_to_not_convert
model = replace_with_int8_symmetric_linear(
... |
Replace model's linear layers with quantized versions before loading weights.
| _process_model_before_weight_loading | python | huggingface/transformers | examples/quantization/custom_quantization_int8_example.py | https://github.com/huggingface/transformers/blob/master/examples/quantization/custom_quantization_int8_example.py | Apache-2.0 |
def load_audio(audio: Union[str, np.ndarray], sampling_rate=16000, timeout=None) -> np.ndarray:
"""
Loads `audio` to an np.ndarray object.
Args:
audio (`str` or `np.ndarray`):
The audio to be loaded to the numpy array format.
sampling_rate (`int`, *optional*, defaults to 16000):... |
Loads `audio` to an np.ndarray object.
Args:
audio (`str` or `np.ndarray`):
The audio to be loaded to the numpy array format.
sampling_rate (`int`, *optional*, defaults to 16000):
The sampling rate to be used when loading the audio. It should be same as the
... | load_audio | python | huggingface/transformers | src/transformers/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/audio_utils.py | Apache-2.0 |
def make_list_of_audio(
audio: Union[list[AudioInput], AudioInput],
) -> AudioInput:
"""
Ensure that the output is a list of audio.
Args:
audio (`Union[List[AudioInput], AudioInput]`):
The input audio.
Returns:
list: A list of audio.
"""
# If it's a list of audios... |
Ensure that the output is a list of audio.
Args:
audio (`Union[List[AudioInput], AudioInput]`):
The input audio.
Returns:
list: A list of audio.
| make_list_of_audio | python | huggingface/transformers | src/transformers/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/audio_utils.py | Apache-2.0 |
def hertz_to_octave(
freq: Union[float, np.ndarray], tuning: Optional[float] = 0.0, bins_per_octave: Optional[int] = 12
):
"""
Convert frequency from hertz to fractional octave numbers.
Adapted from *librosa*.
Args:
freq (`float` or `np.ndarray`):
The frequency, or multiple freq... |
Convert frequency from hertz to fractional octave numbers.
Adapted from *librosa*.
Args:
freq (`float` or `np.ndarray`):
The frequency, or multiple frequencies, in hertz (Hz).
tuning (`float`, defaults to `0.`):
Tuning deviation from the Stuttgart pitch (A440) in (f... | hertz_to_octave | python | huggingface/transformers | src/transformers/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/audio_utils.py | Apache-2.0 |
def chroma_filter_bank(
num_frequency_bins: int,
num_chroma: int,
sampling_rate: int,
tuning: float = 0.0,
power: Optional[float] = 2.0,
weighting_parameters: Optional[tuple[float, float]] = (5.0, 2.0),
start_at_c_chroma: Optional[bool] = True,
):
"""
Creates a chroma filter bank, i.... |
Creates a chroma filter bank, i.e a linear transformation to project spectrogram bins onto chroma bins.
Adapted from *librosa*.
Args:
num_frequency_bins (`int`):
Number of frequencies used to compute the spectrogram (should be the same as in `stft`).
num_chroma (`int`):
... | chroma_filter_bank | python | huggingface/transformers | src/transformers/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/audio_utils.py | Apache-2.0 |
def spectrogram(
waveform: np.ndarray,
window: np.ndarray,
frame_length: int,
hop_length: int,
fft_length: Optional[int] = None,
power: Optional[float] = 1.0,
center: bool = True,
pad_mode: str = "reflect",
onesided: bool = True,
dither: float = 0.0,
preemphasis: Optional[flo... |
Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.
This function can create the following kinds of spectrograms:
- amplitude spectrogram (`power = 1.0`)
- power spectrogram (`power = 2.0`)
- complex-valued spectrogram (`power = None`)
- log spectrogram ... | spectrogram | python | huggingface/transformers | src/transformers/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/audio_utils.py | Apache-2.0 |
def spectrogram_batch(
waveform_list: list[np.ndarray],
window: np.ndarray,
frame_length: int,
hop_length: int,
fft_length: Optional[int] = None,
power: Optional[float] = 1.0,
center: bool = True,
pad_mode: str = "reflect",
onesided: bool = True,
dither: float = 0.0,
preempha... |
Calculates spectrograms for a list of waveforms using the Short-Time Fourier Transform, optimized for batch processing.
This function extends the capabilities of the `spectrogram` function to handle multiple waveforms efficiently by leveraging broadcasting.
It supports generating various types of spectrog... | spectrogram_batch | python | huggingface/transformers | src/transformers/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/audio_utils.py | Apache-2.0 |
def power_to_db_batch(
spectrogram: np.ndarray,
reference: float = 1.0,
min_value: float = 1e-10,
db_range: Optional[float] = None,
) -> np.ndarray:
"""
Converts a batch of power spectrograms to the decibel scale. This computes `10 * log10(spectrogram / reference)`,
using basic logarithm pro... |
Converts a batch of power spectrograms to the decibel scale. This computes `10 * log10(spectrogram / reference)`,
using basic logarithm properties for numerical stability.
This function supports batch processing, where each item in the batch is an individual power (mel) spectrogram.
Args:
spe... | power_to_db_batch | python | huggingface/transformers | src/transformers/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/audio_utils.py | Apache-2.0 |
def amplitude_to_db_batch(
spectrogram: np.ndarray, reference: float = 1.0, min_value: float = 1e-5, db_range: Optional[float] = None
) -> np.ndarray:
"""
Converts a batch of amplitude spectrograms to the decibel scale. This computes `20 * log10(spectrogram / reference)`,
using basic logarithm propertie... |
Converts a batch of amplitude spectrograms to the decibel scale. This computes `20 * log10(spectrogram / reference)`,
using basic logarithm properties for numerical stability.
The function supports batch processing, where each item in the batch is an individual amplitude (mel) spectrogram.
Args:
... | amplitude_to_db_batch | python | huggingface/transformers | src/transformers/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/audio_utils.py | Apache-2.0 |
def stft(frames: np.array, windowing_function: np.array, fft_window_size: Optional[int] = None):
"""
Calculates the complex Short-Time Fourier Transform (STFT) of the given framed signal. Should give the same results
as `torch.stft`.
Args:
frames (`np.array` of dimension `(num_frames, fft_windo... |
Calculates the complex Short-Time Fourier Transform (STFT) of the given framed signal. Should give the same results
as `torch.stft`.
Args:
frames (`np.array` of dimension `(num_frames, fft_window_size)`):
A framed audio signal obtained using `audio_utils.fram_wav`.
windowing_fu... | stft | python | huggingface/transformers | src/transformers/audio_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/audio_utils.py | Apache-2.0 |
def _static_cache_update(
k_cache: torch.Tensor,
v_cache: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
cache_position: Optional[torch.LongTensor],
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Updates the static cache tensors in place.
Args:
k_cache (`torch.... |
Updates the static cache tensors in place.
Args:
k_cache (`torch.Tensor`): The key cache tensor to update.
v_cache (`torch.Tensor`): The value cache tensor to update.
key_states (`torch.Tensor`): The new key states to add.
value_states (`torch.Tensor`): The new value states to ... | _static_cache_update | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def _sliding_cache_update(
k_cache: torch.Tensor,
v_cache: torch.Tensor,
key_states: torch.Tensor,
value_states: torch.Tensor,
cache_position: torch.LongTensor,
max_cache_len: int,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Updates the sliding window cache tensors, returning the potenti... |
Updates the sliding window cache tensors, returning the potentially modified tensors.
Args:
k_cache (`torch.Tensor`): The key cache tensor to update.
v_cache (`torch.Tensor`): The value cache tensor to update.
key_states (`torch.Tensor`): The new key states to add.
value_states... | _sliding_cache_update | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
"""
Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
the given layer at `layer_idx`.
The masks are then prepared according to the given lengths... |
Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
the given layer at `layer_idx`.
The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns (i.e. sliding_window, chunk_size),
for each layer.
... | get_mask_sizes | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def from_dict(cls, config_dict, **kwargs):
"""
Constructs a CacheConfig instance from a dictionary of parameters.
Args:
config_dict (Dict[str, Any]): Dictionary containing configuration parameters.
**kwargs: Additional keyword arguments to override dictionary values.
... |
Constructs a CacheConfig instance from a dictionary of parameters.
Args:
config_dict (Dict[str, Any]): Dictionary containing configuration parameters.
**kwargs: Additional keyword arguments to override dictionary values.
Returns:
CacheConfig: Instance of Cac... | from_dict | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def validate(self):
"""Validates if the arguments passed are correct"""
incorrect_arg_msg = (
"Some of the keys in `cache_config` are defined incorrectly. `{key}` should be {correct_value}` "
"but found {found_value}"
)
# Check that the values are reasonable in g... | Validates if the arguments passed are correct | validate | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor, torch.Tensor]]:
"""Converts the `DynamicCache` instance into the its equivalent in the legacy cache format. Used for
backward compatibility."""
legacy_cache = ()
for layer_idx in range(len(self)):
legacy_cache += ((self.k... | Converts the `DynamicCache` instance into the its equivalent in the legacy cache format. Used for
backward compatibility. | to_legacy_cache | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def crop(self, max_length: int):
"""Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be
negative to remove `max_length` tokens. This is used in assisted decoding and contrastive search."""
# In case it is negative
if max_length < 0:
... | Crop the past key values up to a new `max_length` in terms of tokens. `max_length` can also be
negative to remove `max_length` tokens. This is used in assisted decoding and contrastive search. | crop | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def batch_split(self, full_batch_size: int, split_size: int) -> List["DynamicCache"]:
"""Split the current instance into a list of `DynamicCache` by the batch size. This will be used by
`_split_model_inputs()` in `generation.utils`"""
out = []
for i in range(0, full_batch_size, split_siz... | Split the current instance into a list of `DynamicCache` by the batch size. This will be used by
`_split_model_inputs()` in `generation.utils` | batch_split | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def from_batch_splits(cls, splits: List["DynamicCache"]) -> "DynamicCache":
"""This is the opposite of the above `batch_split()` method. This will be used by `stack_model_outputs` in
`generation.utils`"""
cache = cls()
for idx in range(len(splits[0])):
key_cache = [current.ke... | This is the opposite of the above `batch_split()` method. This will be used by `stack_model_outputs` in
`generation.utils` | from_batch_splits | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def batch_repeat_interleave(self, repeats: int):
"""Repeat the cache `repeats` times in the batch dimension. Used in contrastive search."""
for layer_idx in range(len(self)):
self.key_cache[layer_idx] = self.key_cache[layer_idx].repeat_interleave(repeats, dim=0)
self.value_cache[... | Repeat the cache `repeats` times in the batch dimension. Used in contrastive search. | batch_repeat_interleave | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def batch_select_indices(self, indices: torch.Tensor):
"""Only keep the `indices` in the batch dimension of the cache. Used in contrastive search."""
for layer_idx in range(len(self)):
self.key_cache[layer_idx] = self.key_cache[layer_idx][indices, ...]
self.value_cache[layer_idx]... | Only keep the `indices` in the batch dimension of the cache. Used in contrastive search. | batch_select_indices | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def _flatten_dynamic_cache(
dynamic_cache: DynamicCache,
):
"""Flattens DynamicCache into flat list of tensors for `torch.export.export` to consume"""
if not isinstance(dynamic_cache, DynamicCache):
raise RuntimeError("This pytree flattening function should only be applied to DynamicCache")
if ... | Flattens DynamicCache into flat list of tensors for `torch.export.export` to consume | _flatten_dynamic_cache | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def reorder_cache(self, beam_idx: torch.LongTensor):
"""Saves the beam indices and reorders the cache when the tensor is back to its device."""
# We delay this operation until the tensors are back to their original
# device because performing torch.index_select on the CPU is very slow
de... | Saves the beam indices and reorders the cache when the tensor is back to its device. | reorder_cache | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor]]:
"""Converts the `EncoderDecoderCache` instance into its equivalent in the legacy cache format."""
legacy_cache = ()
if len(self.cross_attention_cache) > 0:
for self_attn, cross_attn in zip(
self.self_attention_c... | Converts the `EncoderDecoderCache` instance into its equivalent in the legacy cache format. | to_legacy_cache | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def from_legacy_cache(
cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
) -> "EncoderDecoderCache":
"""Converts a cache in the legacy cache format into an equivalent `EncoderDecoderCache`."""
cache = cls(
self_attention_cache=DynamicCache(),
cros... | Converts a cache in the legacy cache format into an equivalent `EncoderDecoderCache`. | from_legacy_cache | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def initialise_cache_layer(self, layer_idx, key_states):
"""Overridden to use the correct device if offloaded layer (and pin memory)."""
if len(self.key_cache) > layer_idx:
return
num_key_value_heads = key_states.shape[1]
device = key_states.device if self.is_sliding[layer_i... | Overridden to use the correct device if offloaded layer (and pin memory). | initialise_cache_layer | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def _prefetch_next_layer(self, layer_idx: int) -> None:
"""Based on current layer_idx, prefetch next full layer to the device."""
# Switch the active layer
self.active_device_layer = 0 if self.active_device_layer == 1 else 1
# Find the next non-sliding layer
try:
ne... | Based on current layer_idx, prefetch next full layer to the device. | _prefetch_next_layer | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def _prefetch_layer_in_context(self, layer_idx: int) -> None:
"""Performs the actual copy of the layer to device cache."""
if len(self.key_cache) > layer_idx:
self.device_key_cache[self.active_device_layer].copy_(self.key_cache[layer_idx], non_blocking=True)
self.device_value_cac... | Performs the actual copy of the layer to device cache. | _prefetch_layer_in_context | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def update(
self,
key_states: torch.Tensor,
value_states: torch.Tensor,
layer_idx: int,
cache_kwargs: Optional[Dict[str, Any]] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Updates the cache with the new `key_states` and `value_states` for the layer `lay... |
Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
It is VERY important to index using a tensor, otherwise you introduce a copy to the device.
Parameters:
key_states (`torch.Tensor`):
The new key states to cache.
va... | update | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def reset(self) -> None:
"""Resets the cache values while preserving the objects."""
# For backwards compatibility.
# TODO(gante): Remove this.
self._seen_tokens = 0
# Zero out cache.
for layer_idx in range(len(self.key_cache)):
# In-place ops prevent breaki... | Resets the cache values while preserving the objects. | reset | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def _create_key_value_cache_tensors(
self, shape: Tuple[int, ...], device: torch.device
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Creates K/V cache tensors on a device. Pins memory for CPU tensors. Marks them as static
addresses for non-CPU tensors.
Args:
shape (`Tuple[... | Creates K/V cache tensors on a device. Pins memory for CPU tensors. Marks them as static
addresses for non-CPU tensors.
Args:
shape (`Tuple[int, ...]`): Shape.
device (`torch.device`): Device.
Returns:
Key and value cache tensors as a tuple.
| _create_key_value_cache_tensors | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def _prefetch_layer(self, layer_idx: int) -> None:
"""Prefetch a layer to the device. Needs to be called in order of layer indices."""
# Don't fetch layers that do not exist.
if layer_idx >= len(self.key_cache):
return
# Alternate between two on-device caches.
if se... | Prefetch a layer to the device. Needs to be called in order of layer indices. | _prefetch_layer | python | huggingface/transformers | src/transformers/cache_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/cache_utils.py | Apache-2.0 |
def to_diff_dict(self) -> dict[str, Any]:
"""
Removes all attributes from the configuration that correspond to the default config attributes for
better readability, while always retaining the `config` attribute from the class. Serializes to a
Python dictionary.
Returns:
... |
Removes all attributes from the configuration that correspond to the default config attributes for
better readability, while always retaining the `config` attribute from the class. Serializes to a
Python dictionary.
Returns:
Dict[str, Any]: Dictionary of all the attributes ... | to_diff_dict | python | huggingface/transformers | src/transformers/configuration_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/configuration_utils.py | Apache-2.0 |
def _remove_keys_not_serialized(self, d: dict[str, Any]) -> None:
"""
Checks and removes if there are any keys in the dict that should not be serialized when saving the config.
Runs recursive check on the dict, to remove from all sub configs.
"""
if hasattr(self, "quantization_co... |
Checks and removes if there are any keys in the dict that should not be serialized when saving the config.
Runs recursive check on the dict, to remove from all sub configs.
| _remove_keys_not_serialized | python | huggingface/transformers | src/transformers/configuration_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/configuration_utils.py | Apache-2.0 |
def register_for_auto_class(cls, auto_class="AutoConfig"):
"""
Register this class with a given auto class. This should only be used for custom configurations as the ones in
the library are already mapped with `AutoConfig`.
Args:
auto_class (`str` or `type`, *optional*, de... |
Register this class with a given auto class. This should only be used for custom configurations as the ones in
the library are already mapped with `AutoConfig`.
Args:
auto_class (`str` or `type`, *optional*, defaults to `"AutoConfig"`):
The auto class to register ... | register_for_auto_class | python | huggingface/transformers | src/transformers/configuration_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/configuration_utils.py | Apache-2.0 |
def _get_non_default_generation_parameters(self) -> dict[str, Any]:
"""
Gets the non-default generation parameters on the PretrainedConfig instance
"""
non_default_generation_parameters = {}
decoder_attribute_name = None
# Composite models don't have a default config, us... |
Gets the non-default generation parameters on the PretrainedConfig instance
| _get_non_default_generation_parameters | python | huggingface/transformers | src/transformers/configuration_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/configuration_utils.py | Apache-2.0 |
def get_text_config(self, decoder=False) -> "PretrainedConfig":
"""
Returns the config that is meant to be used with text IO. On most models, it is the original config instance
itself. On specific composite models, it is under a set of valid names.
Args:
decoder (`Optional[b... |
Returns the config that is meant to be used with text IO. On most models, it is the original config instance
itself. On specific composite models, it is under a set of valid names.
Args:
decoder (`Optional[bool]`, *optional*, defaults to `False`):
If set to `True`, ... | get_text_config | python | huggingface/transformers | src/transformers/configuration_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/configuration_utils.py | Apache-2.0 |
def recursive_diff_dict(dict_a, dict_b, config_obj=None):
"""
Helper function to recursively take the diff between two nested dictionaries. The resulting diff only contains the
values from `dict_a` that are different from values in `dict_b`.
dict_b : the default config dictionary. We want to remove val... |
Helper function to recursively take the diff between two nested dictionaries. The resulting diff only contains the
values from `dict_a` that are different from values in `dict_b`.
dict_b : the default config dictionary. We want to remove values that are in this one
| recursive_diff_dict | python | huggingface/transformers | src/transformers/configuration_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/configuration_utils.py | Apache-2.0 |
def layer_type_validation(layer_types: list[str]):
"""Check that each entry in `layer_types` are allowed."""
if not all(layer_type in ALLOWED_LAYER_TYPES for layer_type in layer_types):
raise ValueError(f"The `layer_types` entries must be in {ALLOWED_LAYER_TYPES}") | Check that each entry in `layer_types` are allowed. | layer_type_validation | python | huggingface/transformers | src/transformers/configuration_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/configuration_utils.py | Apache-2.0 |
def convert_slow_tokenizer(transformer_tokenizer, from_tiktoken=False) -> Tokenizer:
"""
Utilities to convert a slow tokenizer instance in a fast tokenizer instance.
Args:
transformer_tokenizer ([`~tokenization_utils_base.PreTrainedTokenizer`]):
Instance of a slow tokenizer to convert i... |
Utilities to convert a slow tokenizer instance in a fast tokenizer instance.
Args:
transformer_tokenizer ([`~tokenization_utils_base.PreTrainedTokenizer`]):
Instance of a slow tokenizer to convert in the backend tokenizer for
[`~tokenization_utils_base.PreTrainedTokenizerFast`]... | convert_slow_tokenizer | python | huggingface/transformers | src/transformers/convert_slow_tokenizer.py | https://github.com/huggingface/transformers/blob/master/src/transformers/convert_slow_tokenizer.py | Apache-2.0 |
def get_relative_imports(module_file: Union[str, os.PathLike]) -> list[str]:
"""
Get the list of modules that are relatively imported in a module file.
Args:
module_file (`str` or `os.PathLike`): The module file to inspect.
Returns:
`list[str]`: The list of relative imports in the modu... |
Get the list of modules that are relatively imported in a module file.
Args:
module_file (`str` or `os.PathLike`): The module file to inspect.
Returns:
`list[str]`: The list of relative imports in the module.
| get_relative_imports | python | huggingface/transformers | src/transformers/dynamic_module_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/dynamic_module_utils.py | Apache-2.0 |
def get_relative_import_files(module_file: Union[str, os.PathLike]) -> list[str]:
"""
Get the list of all files that are needed for a given module. Note that this function recurses through the relative
imports (if a imports b and b imports c, it will return module files for b and c).
Args:
modu... |
Get the list of all files that are needed for a given module. Note that this function recurses through the relative
imports (if a imports b and b imports c, it will return module files for b and c).
Args:
module_file (`str` or `os.PathLike`): The module file to inspect.
Returns:
`list... | get_relative_import_files | python | huggingface/transformers | src/transformers/dynamic_module_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/dynamic_module_utils.py | Apache-2.0 |
def get_imports(filename: Union[str, os.PathLike]) -> list[str]:
"""
Extracts all the libraries (not relative imports this time) that are imported in a file.
Args:
filename (`str` or `os.PathLike`): The module file to inspect.
Returns:
`list[str]`: The list of all packages required to ... |
Extracts all the libraries (not relative imports this time) that are imported in a file.
Args:
filename (`str` or `os.PathLike`): The module file to inspect.
Returns:
`list[str]`: The list of all packages required to use the input module.
| get_imports | python | huggingface/transformers | src/transformers/dynamic_module_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/dynamic_module_utils.py | Apache-2.0 |
def check_imports(filename: Union[str, os.PathLike]) -> list[str]:
"""
Check if the current Python environment contains all the libraries that are imported in a file. Will raise if a
library is missing.
Args:
filename (`str` or `os.PathLike`): The module file to check.
Returns:
`li... |
Check if the current Python environment contains all the libraries that are imported in a file. Will raise if a
library is missing.
Args:
filename (`str` or `os.PathLike`): The module file to check.
Returns:
`list[str]`: The list of relative imports in the file.
| check_imports | python | huggingface/transformers | src/transformers/dynamic_module_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/dynamic_module_utils.py | Apache-2.0 |
def get_class_in_module(
class_name: str,
module_path: Union[str, os.PathLike],
*,
force_reload: bool = False,
) -> type:
"""
Import a module on the cache directory for modules and extract a class from it.
Args:
class_name (`str`): The name of the class to import.
module_pat... |
Import a module on the cache directory for modules and extract a class from it.
Args:
class_name (`str`): The name of the class to import.
module_path (`str` or `os.PathLike`): The path to the module to import.
force_reload (`bool`, *optional*, defaults to `False`):
Whether... | get_class_in_module | python | huggingface/transformers | src/transformers/dynamic_module_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/dynamic_module_utils.py | Apache-2.0 |
def resolve_trust_remote_code(
trust_remote_code, model_name, has_local_code, has_remote_code, error_message=None, upstream_repo=None
):
"""
Resolves the `trust_remote_code` argument. If there is remote code to be loaded, the user must opt-in to loading
it.
Args:
trust_remote_code (`bool` o... |
Resolves the `trust_remote_code` argument. If there is remote code to be loaded, the user must opt-in to loading
it.
Args:
trust_remote_code (`bool` or `None`):
User-defined `trust_remote_code` value.
model_name (`str`):
The name of the model repository in huggingfa... | resolve_trust_remote_code | python | huggingface/transformers | src/transformers/dynamic_module_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/dynamic_module_utils.py | Apache-2.0 |
def check_python_requirements(path_or_repo_id, requirements_file="requirements.txt", **kwargs):
"""
Tries to locate `requirements_file` in a local folder or repo, and confirms that the environment has all the
python dependencies installed.
Args:
path_or_repo_id (`str` or `os.PathLike`):
... |
Tries to locate `requirements_file` in a local folder or repo, and confirms that the environment has all the
python dependencies installed.
Args:
path_or_repo_id (`str` or `os.PathLike`):
This can be either:
- a string, the *model id* of a model repo on huggingface.co.
... | check_python_requirements | python | huggingface/transformers | src/transformers/dynamic_module_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/dynamic_module_utils.py | Apache-2.0 |
def to(self, *args, **kwargs) -> "BatchFeature":
"""
Send all values to device by calling `v.to(*args, **kwargs)` (PyTorch only). This should support casting in
different `dtypes` and sending the `BatchFeature` to a different `device`.
Args:
args (`Tuple`):
W... |
Send all values to device by calling `v.to(*args, **kwargs)` (PyTorch only). This should support casting in
different `dtypes` and sending the `BatchFeature` to a different `device`.
Args:
args (`Tuple`):
Will be passed to the `to(...)` function of the tensors.
... | to | python | huggingface/transformers | src/transformers/feature_extraction_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/feature_extraction_utils.py | Apache-2.0 |
def register_for_auto_class(cls, auto_class="AutoFeatureExtractor"):
"""
Register this class with a given auto class. This should only be used for custom feature extractors as the ones
in the library are already mapped with `AutoFeatureExtractor`.
Args:
auto_class (`str` o... |
Register this class with a given auto class. This should only be used for custom feature extractors as the ones
in the library are already mapped with `AutoFeatureExtractor`.
Args:
auto_class (`str` or `type`, *optional*, defaults to `"AutoFeatureExtractor"`):
The... | register_for_auto_class | python | huggingface/transformers | src/transformers/feature_extraction_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/feature_extraction_utils.py | Apache-2.0 |
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 [`... |
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`):
... | get_image_processor_dict | python | huggingface/transformers | src/transformers/image_processing_base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_base.py | Apache-2.0 |
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 `.
Args:
auto_class (`str` or `ty... |
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 `.
Args:
auto_class (`str` or `type`, *optional*, defaults to `"AutoImageProcessor "`):
The aut... | register_for_auto_class | python | huggingface/transformers | src/transformers/image_processing_base.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_base.py | Apache-2.0 |
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 i... |
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.
Ar... | select_best_resolution | python | huggingface/transformers | src/transformers/image_processing_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils.py | Apache-2.0 |
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_wid... |
Given an image and a target resolution, calculate the output size of the image after cropping to the target
| get_patch_output_size | python | huggingface/transformers | src/transformers/image_processing_utils.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils.py | Apache-2.0 |
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,
... |
Checks validity of typically used arguments in an `ImageProcessorFast` `preprocess` method.
Raises `ValueError` if arguments incompatibility is caught.
| validate_fast_preprocess_arguments | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
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 |
Squeezes a tensor, but only if the axis specified has dim 1.
| safe_squeeze | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
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`):
... |
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.
| divide_to_patches | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
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 (`to... |
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.
interpolation (`... | resize | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
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`):
... |
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.
| rescale | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
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.Tenso... |
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 ... | normalize | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
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 the... |
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]`):
... | center_crop | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
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.
... |
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.
| convert_to_rgb | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
def filter_out_unused_kwargs(self, kwargs: dict):
"""
Filter out the unused kwargs from the kwargs dictionary.
"""
if self.unused_kwargs is None:
return kwargs
for kwarg_name in self.unused_kwargs:
if kwarg_name in kwargs:
logger.warning_o... |
Filter out the unused kwargs from the kwargs dictionary.
| filter_out_unused_kwargs | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
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 vali... |
Prepare the images structure for processing.
Args:
images (`ImageInput`):
The input images to process.
Returns:
`ImageInput`: The images with a valid nesting.
| _prepare_images_structure | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
def _prepare_input_images(
self,
images: ImageInput,
do_convert_rgb: Optional[bool] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
device: Optional["torch.device"] = None,
) -> list["torch.Tensor"]:
"""
Prepare the input images for p... |
Prepare the input images for processing.
| _prepare_input_images | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
def _further_process_kwargs(
self,
size: Optional[SizeDict] = None,
crop_size: Optional[SizeDict] = None,
default_to_square: Optional[bool] = None,
image_mean: Optional[Union[float, list[float]]] = None,
image_std: Optional[Union[float, list[float]]] = None,
data_... |
Update kwargs that need further processing before being validated
Can be overridden by subclasses to customize the processing of kwargs.
| _further_process_kwargs | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
def _validate_preprocess_kwargs(
self,
do_rescale: Optional[bool] = None,
rescale_factor: Optional[float] = None,
do_normalize: Optional[bool] = None,
image_mean: Optional[Union[float, tuple[float]]] = None,
image_std: Optional[Union[float, tuple[float]]] = None,
... |
validate the kwargs for the preprocess method.
| _validate_preprocess_kwargs | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
def post_process_semantic_segmentation(self, outputs, target_sizes: Optional[list[tuple]] = None):
"""
Converts the output of [`MobileNetV2ForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch.
Args:
outputs ([`MobileNetV2ForSemanticSegmentation`]):
... |
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*... | post_process_semantic_segmentation | python | huggingface/transformers | src/transformers/image_processing_utils_fast.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_processing_utils_fast.py | Apache-2.0 |
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`. The input
can have arbitrary number o... |
Converts `image` to the channel dimension format specified by `channel_dim`. The input
can have arbitrary number of leading dimensions. Only last three dimension will be permuted
to format the `image`.
Args:
image (`numpy.ndarray`):
The image to have its channel dimension set.
... | to_channel_dimension_format | python | huggingface/transformers | src/transformers/image_transforms.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_transforms.py | Apache-2.0 |
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 ... |
Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
needed.
Args:
image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor` or `tf.Tensor`):
The image to convert to the `PIL.Image` format.
do_rescale (`bool`, *opti... | to_pil_image | python | huggingface/transformers | src/transformers/image_transforms.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_transforms.py | Apache-2.0 |
def get_resize_output_image_size(
input_image: np.ndarray,
size: Union[int, tuple[int, int], list[int], tuple[int]],
default_to_square: bool = True,
max_size: Optional[int] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
) -> tuple:
"""
Find the target (height, widt... |
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 resizi... | get_resize_output_image_size | python | huggingface/transformers | src/transformers/image_transforms.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_transforms.py | Apache-2.0 |
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... |
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` o... | normalize | python | huggingface/transformers | src/transformers/image_transforms.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_transforms.py | Apache-2.0 |
def center_crop(
image: np.ndarray,
size: tuple[int, int],
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
) -> np.ndarray:
"""
Crops the `image` to the specified `size` using a center crop. Note that if the image is t... |
Crops the `image` to the specified `size` using a center crop. Note that if the image is too small to be cropped to
the size given, it will be padded (so the returned result will always be of size `size`).
Args:
image (`np.ndarray`):
The image to crop.
size (`Tuple[int, int]`):... | center_crop | python | huggingface/transformers | src/transformers/image_transforms.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_transforms.py | Apache-2.0 |
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"])
... |
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.
| convert_to_rgb | python | huggingface/transformers | src/transformers/image_transforms.py | https://github.com/huggingface/transformers/blob/master/src/transformers/image_transforms.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.