text
stringlengths
5
631k
id
stringlengths
14
178
metadata
dict
__index_level_0__
int64
0
647
# Copyright 2023 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. """Collection of utils to be used by backbones and their components.""" import enum import inspect from collections.abc import Iterable from typing import TYPE_CHECKING, Optional, Union if TYPE_CHECKING: from ..configuration_utils import PretrainedConfig class BackboneType(enum.Enum): TIMM = "timm" TRANSFORMERS = "transformers" def verify_out_features_out_indices( out_features: Optional[Iterable[str]], out_indices: Optional[Iterable[int]], stage_names: Optional[Iterable[str]] ): """ Verify that out_indices and out_features are valid for the given stage_names. """ if stage_names is None: raise ValueError("Stage_names must be set for transformers backbones") if out_features is not None: if not isinstance(out_features, (list,)): raise ValueError(f"out_features must be a list got {type(out_features)}") if any(feat not in stage_names for feat in out_features): raise ValueError(f"out_features must be a subset of stage_names: {stage_names} got {out_features}") if len(out_features) != len(set(out_features)): raise ValueError(f"out_features must not contain any duplicates, got {out_features}") if out_features != (sorted_feats := [feat for feat in stage_names if feat in out_features]): raise ValueError( f"out_features must be in the same order as stage_names, expected {sorted_feats} got {out_features}" ) if out_indices is not None: if not isinstance(out_indices, list): raise ValueError(f"out_indices must be a list, got {type(out_indices)}") # Convert negative indices to their positive equivalent: [-1,] -> [len(stage_names) - 1,] positive_indices = tuple(idx % len(stage_names) if idx < 0 else idx for idx in out_indices) if any(idx for idx in positive_indices if idx not in range(len(stage_names))): raise ValueError(f"out_indices must be valid indices for stage_names {stage_names}, got {out_indices}") if len(positive_indices) != len(set(positive_indices)): msg = f"out_indices must not contain any duplicates, got {out_indices}" msg += f"(equivalent to {positive_indices}))" if positive_indices != out_indices else "" raise ValueError(msg) if positive_indices != tuple(sorted(positive_indices)): sorted_negative = [idx for _, idx in sorted(zip(positive_indices, out_indices), key=lambda x: x[0])] raise ValueError( f"out_indices must be in the same order as stage_names, expected {sorted_negative} got {out_indices}" ) if out_features is not None and out_indices is not None: if len(out_features) != len(out_indices): raise ValueError("out_features and out_indices should have the same length if both are set") if out_features != [stage_names[idx] for idx in out_indices]: raise ValueError("out_features and out_indices should correspond to the same stages if both are set") def _align_output_features_output_indices( out_features: Optional[list[str]], out_indices: Optional[Union[list[int], tuple[int]]], stage_names: list[str], ): """ Finds the corresponding `out_features` and `out_indices` for the given `stage_names`. The logic is as follows: - `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the `out_indices`. - `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the `out_features`. - `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage. - `out_indices` and `out_features` set: input `out_indices` and `out_features` are returned. Args: out_features (`list[str]`): The names of the features for the backbone to output. out_indices (`list[int]` or `tuple[int]`): The indices of the features for the backbone to output. stage_names (`list[str]`): The names of the stages of the backbone. """ if out_indices is None and out_features is None: out_indices = [len(stage_names) - 1] out_features = [stage_names[-1]] elif out_indices is None and out_features is not None: out_indices = [stage_names.index(layer) for layer in out_features] elif out_features is None and out_indices is not None: out_features = [stage_names[idx] for idx in out_indices] return out_features, out_indices def get_aligned_output_features_output_indices( out_features: Optional[list[str]], out_indices: Optional[Union[list[int], tuple[int]]], stage_names: list[str], ) -> tuple[list[str], list[int]]: """ Get the `out_features` and `out_indices` so that they are aligned. The logic is as follows: - `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the `out_indices`. - `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the `out_features`. - `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage. - `out_indices` and `out_features` set: they are verified to be aligned. Args: out_features (`list[str]`): The names of the features for the backbone to output. out_indices (`list[int]` or `tuple[int]`): The indices of the features for the backbone to output. stage_names (`list[str]`): The names of the stages of the backbone. """ out_indices = list(out_indices) if out_indices is not None else None # First verify that the out_features and out_indices are valid verify_out_features_out_indices(out_features=out_features, out_indices=out_indices, stage_names=stage_names) output_features, output_indices = _align_output_features_output_indices( out_features=out_features, out_indices=out_indices, stage_names=stage_names ) # Verify that the aligned out_features and out_indices are valid verify_out_features_out_indices(out_features=output_features, out_indices=output_indices, stage_names=stage_names) return output_features, output_indices class BackboneMixin: backbone_type: Optional[BackboneType] = None def _init_timm_backbone(self, config) -> None: """ Initialize the backbone model from timm The backbone must already be loaded to self._backbone """ if getattr(self, "_backbone", None) is None: raise ValueError("self._backbone must be set before calling _init_timm_backbone") # These will diagree with the defaults for the transformers models e.g. for resnet50 # the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4'] # the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4'] self.stage_names = [stage["module"] for stage in self._backbone.feature_info.info] self.num_features = [stage["num_chs"] for stage in self._backbone.feature_info.info] # In some timm versions, out_indices reflects the input type of out_indices on the `create_model` call, # in later versions >= 1, it is always a tuple out_indices = list(self._backbone.feature_info.out_indices) out_features = self._backbone.feature_info.module_name() # We verify the out indices and out features are valid verify_out_features_out_indices( out_features=out_features, out_indices=out_indices, stage_names=self.stage_names ) self._out_features, self._out_indices = out_features, out_indices def _init_transformers_backbone(self, config) -> None: stage_names = getattr(config, "stage_names") out_features = getattr(config, "out_features", None) out_indices = getattr(config, "out_indices", None) self.stage_names = stage_names self._out_features, self._out_indices = get_aligned_output_features_output_indices( out_features=out_features, out_indices=out_indices, stage_names=stage_names ) # Number of channels for each stage. This is set in the transformer backbone model init self.num_features = None def _init_backbone(self, config) -> None: """ Method to initialize the backbone. This method is called by the constructor of the base class after the pretrained model weights have been loaded. """ self.config = config self.use_timm_backbone = getattr(config, "use_timm_backbone", False) self.backbone_type = BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS if self.backbone_type == BackboneType.TIMM: self._init_timm_backbone(config) elif self.backbone_type == BackboneType.TRANSFORMERS: self._init_transformers_backbone(config) else: raise ValueError(f"backbone_type {self.backbone_type} not supported.") @property def out_features(self): return self._out_features @out_features.setter def out_features(self, out_features: list[str]): """ Set the out_features attribute. This will also update the out_indices attribute to match the new out_features. """ self._out_features, self._out_indices = get_aligned_output_features_output_indices( out_features=out_features, out_indices=None, stage_names=self.stage_names ) @property def out_indices(self): return self._out_indices @out_indices.setter def out_indices(self, out_indices: Union[tuple[int], list[int]]): """ Set the out_indices attribute. This will also update the out_features attribute to match the new out_indices. """ self._out_features, self._out_indices = get_aligned_output_features_output_indices( out_features=None, out_indices=out_indices, stage_names=self.stage_names ) @property def out_feature_channels(self): # the current backbones will output the number of channels for each stage # even if that stage is not in the out_features list. return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names)} @property def channels(self): return [self.out_feature_channels[name] for name in self.out_features] def forward_with_filtered_kwargs(self, *args, **kwargs): signature = dict(inspect.signature(self.forward).parameters) filtered_kwargs = {k: v for k, v in kwargs.items() if k in signature} return self(*args, **filtered_kwargs) def forward( self, pixel_values, output_hidden_states: Optional[bool] = None, output_attentions: Optional[bool] = None, return_dict: Optional[bool] = None, ): raise NotImplementedError("This method should be implemented by the derived class.") def to_dict(self): """ Serializes this instance to a Python dictionary. Override the default `to_dict()` from `PretrainedConfig` to include the `out_features` and `out_indices` attributes. """ output = super().to_dict() output["out_features"] = output.pop("_out_features") output["out_indices"] = output.pop("_out_indices") return output class BackboneConfigMixin: """ A Mixin to support handling the `out_features` and `out_indices` attributes for the backbone configurations. """ @property def out_features(self): return self._out_features @out_features.setter def out_features(self, out_features: list[str]): """ Set the out_features attribute. This will also update the out_indices attribute to match the new out_features. """ self._out_features, self._out_indices = get_aligned_output_features_output_indices( out_features=out_features, out_indices=None, stage_names=self.stage_names ) @property def out_indices(self): return self._out_indices @out_indices.setter def out_indices(self, out_indices: Union[tuple[int], list[int]]): """ Set the out_indices attribute. This will also update the out_features attribute to match the new out_indices. """ self._out_features, self._out_indices = get_aligned_output_features_output_indices( out_features=None, out_indices=out_indices, stage_names=self.stage_names ) def to_dict(self): """ Serializes this instance to a Python dictionary. Override the default `to_dict()` from `PretrainedConfig` to include the `out_features` and `out_indices` attributes. """ output = super().to_dict() output["out_features"] = output.pop("_out_features") output["out_indices"] = output.pop("_out_indices") return output def load_backbone(config): """ Loads the backbone model from a config object. If the config is from the backbone model itself, then we return a backbone model with randomly initialized weights. If the config is from the parent model of the backbone model itself, then we load the pretrained backbone weights if specified. """ from transformers import AutoBackbone, AutoConfig backbone_config = getattr(config, "backbone_config", None) use_timm_backbone = getattr(config, "use_timm_backbone", None) use_pretrained_backbone = getattr(config, "use_pretrained_backbone", None) backbone_checkpoint = getattr(config, "backbone", None) backbone_kwargs = getattr(config, "backbone_kwargs", None) backbone_kwargs = {} if backbone_kwargs is None else backbone_kwargs if backbone_kwargs and backbone_config is not None: raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.") # If there is a backbone_config and a backbone checkpoint, and use_pretrained_backbone=False then the desired # behaviour is ill-defined: do you want to load from the checkpoint's config or the backbone_config? if backbone_config is not None and backbone_checkpoint is not None and use_pretrained_backbone is not None: raise ValueError("Cannot specify both config.backbone_config and config.backbone") # If any of the following are set, then the config passed in is from a model which contains a backbone. if backbone_config is None and use_timm_backbone is None and backbone_checkpoint is None: return AutoBackbone.from_config(config=config, **backbone_kwargs) # config from the parent model that has a backbone if use_timm_backbone: if backbone_checkpoint is None: raise ValueError("config.backbone must be set if use_timm_backbone is True") # Because of how timm backbones were originally added to models, we need to pass in use_pretrained_backbone # to determine whether to load the pretrained weights. backbone = AutoBackbone.from_pretrained( backbone_checkpoint, use_timm_backbone=use_timm_backbone, use_pretrained_backbone=use_pretrained_backbone, **backbone_kwargs, ) elif use_pretrained_backbone: if backbone_checkpoint is None: raise ValueError("config.backbone must be set if use_pretrained_backbone is True") backbone = AutoBackbone.from_pretrained(backbone_checkpoint, **backbone_kwargs) else: if backbone_config is None and backbone_checkpoint is None: raise ValueError("Either config.backbone_config or config.backbone must be set") if backbone_config is None: backbone_config = AutoConfig.from_pretrained(backbone_checkpoint, **backbone_kwargs) backbone = AutoBackbone.from_config(config=backbone_config) return backbone def verify_backbone_config_arguments( use_timm_backbone: bool, use_pretrained_backbone: bool, backbone: Optional[str], backbone_config: Optional[Union[dict, "PretrainedConfig"]], backbone_kwargs: Optional[dict], ): """ Verify that the config arguments to be passed to load_backbone are valid """ if backbone_config is not None and backbone is not None: raise ValueError("You can't specify both `backbone` and `backbone_config`.") if backbone_config is not None and use_timm_backbone: raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`.") if backbone_kwargs is not None and backbone_kwargs and backbone_config is not None: raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.")
transformers/src/transformers/utils/backbone_utils.py/0
{ "file_path": "transformers/src/transformers/utils/backbone_utils.py", "repo_id": "transformers", "token_count": 6418 }
527
# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends class TFForcedBOSTokenLogitsProcessor(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFForcedEOSTokenLogitsProcessor(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFForceTokensLogitsProcessor(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFGenerationMixin(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFLogitsProcessor(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFLogitsProcessorList(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFLogitsWarper(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFMinLengthLogitsProcessor(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFNoBadWordsLogitsProcessor(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFNoRepeatNGramLogitsProcessor(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFRepetitionPenaltyLogitsProcessor(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFSuppressTokensAtBeginLogitsProcessor(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFSuppressTokensLogitsProcessor(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFTemperatureLogitsWarper(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFTopKLogitsWarper(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFTopPLogitsWarper(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class KerasMetricCallback(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class PushToHubCallback(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFPreTrainedModel(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFSequenceSummary(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class TFSharedEmbeddings(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) def shape_list(*args, **kwargs): requires_backends(shape_list, ["tf"]) class AdamWeightDecay(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class GradientAccumulator(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) class WarmUp(metaclass=DummyObject): _backends = ["tf"] def __init__(self, *args, **kwargs): requires_backends(self, ["tf"]) def create_optimizer(*args, **kwargs): requires_backends(create_optimizer, ["tf"])
transformers/src/transformers/utils/dummy_tf_objects.py/0
{ "file_path": "transformers/src/transformers/utils/dummy_tf_objects.py", "repo_id": "transformers", "token_count": 1698 }
528
#!/usr/bin/env python # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # Modifications Copyright (C) 2025, Advanced Micro Devices, Inc. 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 dataclasses import importlib.metadata import json import os from dataclasses import dataclass, is_dataclass from enum import Enum from inspect import Parameter, signature from typing import Any, Optional, Union from packaging import version from ..utils import ( is_auto_awq_available, is_compressed_tensors_available, is_gptqmodel_available, is_hqq_available, is_quark_available, is_torch_available, is_torchao_available, logging, ) from .import_utils import is_auto_gptq_available if is_torch_available(): import torch logger = logging.get_logger(__name__) class QuantizationMethod(str, Enum): BITS_AND_BYTES = "bitsandbytes" GPTQ = "gptq" AWQ = "awq" AQLM = "aqlm" VPTQ = "vptq" QUANTO = "quanto" EETQ = "eetq" HIGGS = "higgs" HQQ = "hqq" COMPRESSED_TENSORS = "compressed-tensors" FBGEMM_FP8 = "fbgemm_fp8" TORCHAO = "torchao" BITNET = "bitnet" SPQR = "spqr" FP8 = "fp8" QUARK = "quark" FPQUANT = "fp_quant" AUTOROUND = "auto-round" MXFP4 = "mxfp4" class AWQLinearVersion(str, Enum): GEMM = "gemm" GEMV = "gemv" EXLLAMA = "exllama" IPEX = "ipex" @staticmethod def from_str(version: str): version = version.lower() if version == "gemm": return AWQLinearVersion.GEMM elif version == "gemv": return AWQLinearVersion.GEMV elif version == "exllama": return AWQLinearVersion.EXLLAMA elif version == "ipex": return AWQLinearVersion.IPEX else: raise ValueError(f"Unknown AWQLinearVersion {version}") class AwqBackendPackingMethod(str, Enum): AUTOAWQ = "autoawq" LLMAWQ = "llm-awq" @dataclass class QuantizationConfigMixin: """ Mixin class for quantization config """ quant_method: QuantizationMethod @classmethod def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): """ Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters. Args: config_dict (`dict[str, Any]`): Dictionary that will be used to instantiate the configuration object. return_unused_kwargs (`bool`,*optional*, defaults to `False`): Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in `PreTrainedModel`. kwargs (`dict[str, Any]`): Additional parameters from which to initialize the configuration object. Returns: [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters. """ config = cls(**config_dict) to_remove = [] for key, value in kwargs.items(): if hasattr(config, key): setattr(config, key, value) to_remove.append(key) for key in to_remove: kwargs.pop(key, None) if return_unused_kwargs: return config, kwargs else: return config 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 configuration instance's parameters will be saved. use_diff (`bool`, *optional*, defaults to `True`): If set to `True`, only the difference between the config instance and the default `QuantizationConfig()` is serialized to JSON file. """ with open(json_file_path, "w", encoding="utf-8") as writer: config_dict = self.to_dict() json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n" writer.write(json_string) 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 configuration instance. """ return copy.deepcopy(self.__dict__) def __iter__(self): """allows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixin""" for attr, value in copy.deepcopy(self.__dict__).items(): yield attr, value def __repr__(self): return f"{self.__class__.__name__} {self.to_json_string()}" def to_json_string(self, use_diff: bool = True) -> str: """ Serializes this instance to a JSON string. Args: use_diff (`bool`, *optional*, defaults to `True`): If set to `True`, only the difference between the config instance and the default `PretrainedConfig()` is serialized to JSON string. Returns: `str`: String containing all the attributes that make up this configuration instance in JSON format. """ if use_diff is True: config_dict = self.to_diff_dict() else: config_dict = self.to_dict() return json.dumps(config_dict, indent=2, sort_keys=True) + "\n" def update(self, **kwargs): """ Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes, returning all the unused kwargs. Args: kwargs (`dict[str, Any]`): Dictionary of attributes to tentatively update this class. Returns: `dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance. """ to_remove = [] for key, value in kwargs.items(): if hasattr(self, key): setattr(self, key, value) to_remove.append(key) # Remove all the attributes that were updated, without modifying the input dict unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove} return unused_kwargs @dataclass class AutoRoundConfig(QuantizationConfigMixin): """This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded AutoRound quantization. Args: bits (`int`, *optional*, defaults to 4): The number of bits to quantize to, supported numbers are (2, 3, 4, 8). group_size (`int`, *optional*, defaults to 128): Group-size value sym (`bool`, *optional*, defaults to `True`): Symmetric quantization or not backend (`str`, *optional*, defaults to `"auto"`): The kernel to use, e.g., ipex,marlin, exllamav2, triton, etc. Ref. https://github.com/intel/auto-round?tab=readme-ov-file#specify-backend """ def __init__( self, bits: int = 4, group_size: int = 128, sym: bool = True, backend: str = "auto", **kwargs, ): self.bits = bits self.group_size = group_size self.sym = sym self.backend = backend self.packing_format = "auto_round:gptq" if kwargs is not None: for key, value in kwargs.items(): setattr(self, key, value) self.quant_method = QuantizationMethod.AUTOROUND self.post_init() def post_init(self): r"""Safety checker that arguments are correct.""" if self.bits not in [2, 3, 4, 8]: raise ValueError(f"Only support quantization to [2,3,4,8] bits but found {self.bits}") if self.group_size != -1 and self.group_size <= 0: raise ValueError("group_size must be greater than 0 or equal to -1") def get_loading_attributes(self): loading_attibutes_dict = {"backend": self.backend} return loading_attibutes_dict def to_dict(self): config_dict = super().to_dict() return config_dict @classmethod def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): quant_method = config_dict["quant_method"] if "auto-round" not in quant_method and "gptq" not in quant_method and "awq" not in quant_method: raise NotImplementedError( "Failed to convert to auto_round format. Only `gptqv1`, `awq`, and `auto-round` formats are supported." ) if "gptq" in quant_method and "meta" in config_dict: raise NotImplementedError("Failed to convert gptq format to auto_round format. Only supports `gptqv1`") if "awq" in quant_method and config_dict.get("version", "gemm") != "gemm": raise NotImplementedError( "Failed to convert awq format to auto_round format. Only supports awq format with gemm version" ) if "auto-round" not in quant_method: config_dict["packing_format"] = f"auto_round:{quant_method}" return super().from_dict(config_dict, return_unused_kwargs=return_unused_kwargs, **kwargs) @dataclass class HqqConfig(QuantizationConfigMixin): """ This is wrapper around hqq's BaseQuantizeConfig. Args: nbits (`int`, *optional*, defaults to 4): Number of bits. Supported values are (8, 4, 3, 2, 1). group_size (`int`, *optional*, defaults to 64): Group-size value. Supported values are any value that is divisible by weight.shape[axis]). view_as_float (`bool`, *optional*, defaults to `False`): View the quantized weight as float (used in distributed training) if set to `True`. axis (`Optional[int]`, *optional*): Axis along which grouping is performed. Supported values are 0 or 1. dynamic_config (dict, *optional*): Parameters for dynamic configuration. The key is the name tag of the layer and the value is a quantization config. If set, each layer specified by its id will use its dedicated quantization configuration. skip_modules (`list[str]`, *optional*, defaults to `['lm_head']`): List of `nn.Linear` layers to skip. kwargs (`dict[str, Any]`, *optional*): Additional parameters from which to initialize the configuration object. """ def __init__( self, nbits: int = 4, group_size: int = 64, view_as_float: bool = False, axis: Optional[int] = None, dynamic_config: Optional[dict] = None, skip_modules: list[str] = ["lm_head"], **kwargs, ): if is_hqq_available(): from hqq.core.quantize import BaseQuantizeConfig as HQQBaseQuantizeConfig else: raise ImportError( "A valid HQQ version (>=0.2.1) is not available. Please follow the instructions to install it: `https://github.com/mobiusml/hqq/`." ) for deprecated_key in ["quant_zero", "quant_scale", "offload_meta"]: if deprecated_key in kwargs: logger.info( deprecated_key + " is deprecated. This parameter will be ignored in quantization settings." ) if axis is None: axis = 1 logger.info("Setting axis=1 as faster backends such as TorchAO or BitBlas are only compatible with it.") if axis not in [0, 1]: raise ValueError("Invalid axis value. Only 0 and 1 are allowed.") if dynamic_config is not None: self.quant_config = {} for key in dynamic_config: self.quant_config[key] = HQQBaseQuantizeConfig(**dynamic_config[key]) else: self.quant_config = HQQBaseQuantizeConfig( **{ "nbits": nbits, "group_size": group_size, "view_as_float": view_as_float, "axis": axis, } ) self.quant_method = QuantizationMethod.HQQ self.skip_modules = skip_modules self.post_init() def post_init(self): r""" Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. """ pass @classmethod def from_dict(cls, config: dict[str, Any]): """ Override from_dict, used in AutoQuantizationConfig.from_dict in quantizers/auto.py """ instance = cls() instance.quant_config = config["quant_config"] instance.skip_modules = config["skip_modules"] return instance 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 configuration instance. """ return { "quant_config": self.quant_config, "quant_method": self.quant_method, "skip_modules": self.skip_modules, } def __repr__(self): config_dict = self.to_dict() return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n" def to_diff_dict(self) -> dict[str, Any]: """ Removes all attributes from config which correspond to the default config attributes for better readability and serializes to a Python dictionary. Returns: `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance, """ config_dict = self.to_dict() # get the default config dict default_config_dict = HqqConfig().to_dict() serializable_config_dict = {} # only serialize values that differ from the default config for key, value in config_dict.items(): if value != default_config_dict[key]: serializable_config_dict[key] = value return serializable_config_dict @dataclass class BitsAndBytesConfig(QuantizationConfigMixin): """ This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded using `bitsandbytes`. This replaces `load_in_8bit` or `load_in_4bit`therefore both options are mutually exclusive. Currently only supports `LLM.int8()`, `FP4`, and `NF4` quantization. If more methods are added to `bitsandbytes`, then more arguments will be added to this class. Args: load_in_8bit (`bool`, *optional*, defaults to `False`): This flag is used to enable 8-bit quantization with LLM.int8(). load_in_4bit (`bool`, *optional*, defaults to `False`): This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from `bitsandbytes`. llm_int8_threshold (`float`, *optional*, defaults to 6.0): This corresponds to the outlier threshold for outlier detection as described in `LLM.int8() : 8-bit Matrix Multiplication for Transformers at Scale` paper: https://huggingface.co/papers/2208.07339 Any hidden states value that is above this threshold will be considered an outlier and the operation on those values will be done in fp16. Values are usually normally distributed, that is, most values are in the range [-3.5, 3.5], but there are some exceptional systematic outliers that are very differently distributed for large models. These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6, but a lower threshold might be needed for more unstable models (small models, fine-tuning). llm_int8_skip_modules (`list[str]`, *optional*): An explicit list of the modules that we do not want to convert in 8-bit. This is useful for models such as Jukebox that has several heads in different places and not necessarily at the last position. For example for `CausalLM` models, the last `lm_head` is kept in its original `dtype`. llm_int8_enable_fp32_cpu_offload (`bool`, *optional*, defaults to `False`): This flag is used for advanced use cases and users that are aware of this feature. If you want to split your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use this flag. This is useful for offloading large models such as `google/flan-t5-xxl`. Note that the int8 operations will not be run on CPU. llm_int8_has_fp16_weight (`bool`, *optional*, defaults to `False`): This flag runs LLM.int8() with 16-bit main weights. This is useful for fine-tuning as the weights do not have to be converted back and forth for the backward pass. bnb_4bit_compute_dtype (`torch.dtype` or str, *optional*, defaults to `torch.float32`): This sets the computational type which might be different than the input type. For example, inputs might be fp32, but computation can be set to bf16 for speedups. bnb_4bit_quant_type (`str`, *optional*, defaults to `"fp4"`): This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types which are specified by `fp4` or `nf4`. bnb_4bit_use_double_quant (`bool`, *optional*, defaults to `False`): This flag is used for nested quantization where the quantization constants from the first quantization are quantized again. bnb_4bit_quant_storage (`torch.dtype` or str, *optional*, defaults to `torch.uint8`): This sets the storage type to pack the quanitzed 4-bit prarams. kwargs (`dict[str, Any]`, *optional*): Additional parameters from which to initialize the configuration object. """ def __init__( self, load_in_8bit=False, load_in_4bit=False, llm_int8_threshold=6.0, llm_int8_skip_modules=None, llm_int8_enable_fp32_cpu_offload=False, llm_int8_has_fp16_weight=False, bnb_4bit_compute_dtype=None, bnb_4bit_quant_type="fp4", bnb_4bit_use_double_quant=False, bnb_4bit_quant_storage=None, **kwargs, ): self.quant_method = QuantizationMethod.BITS_AND_BYTES if load_in_4bit and load_in_8bit: raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time") self._load_in_8bit = load_in_8bit self._load_in_4bit = load_in_4bit self.llm_int8_threshold = llm_int8_threshold self.llm_int8_skip_modules = llm_int8_skip_modules self.llm_int8_enable_fp32_cpu_offload = llm_int8_enable_fp32_cpu_offload self.llm_int8_has_fp16_weight = llm_int8_has_fp16_weight self.bnb_4bit_quant_type = bnb_4bit_quant_type self.bnb_4bit_use_double_quant = bnb_4bit_use_double_quant if bnb_4bit_compute_dtype is None: self.bnb_4bit_compute_dtype = torch.float32 elif isinstance(bnb_4bit_compute_dtype, str): self.bnb_4bit_compute_dtype = getattr(torch, bnb_4bit_compute_dtype) elif isinstance(bnb_4bit_compute_dtype, torch.dtype): self.bnb_4bit_compute_dtype = bnb_4bit_compute_dtype else: raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype") if bnb_4bit_quant_storage is None: self.bnb_4bit_quant_storage = torch.uint8 elif isinstance(bnb_4bit_quant_storage, str): if bnb_4bit_quant_storage not in ["float16", "float32", "int8", "uint8", "float64", "bfloat16"]: raise ValueError( "`bnb_4bit_quant_storage` must be a valid string (one of 'float16', 'float32', 'int8', 'uint8', 'float64', 'bfloat16') " ) self.bnb_4bit_quant_storage = getattr(torch, bnb_4bit_quant_storage) elif isinstance(bnb_4bit_quant_storage, torch.dtype): self.bnb_4bit_quant_storage = bnb_4bit_quant_storage else: raise ValueError("bnb_4bit_quant_storage must be a string or a torch.dtype") if kwargs: logger.info(f"Unused kwargs: {list(kwargs.keys())}. These kwargs are not used in {self.__class__}.") self.post_init() @property def load_in_4bit(self): return self._load_in_4bit @load_in_4bit.setter def load_in_4bit(self, value: bool): if not isinstance(value, bool): raise TypeError("load_in_4bit must be a boolean") if self.load_in_8bit and value: raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time") self._load_in_4bit = value @property def load_in_8bit(self): return self._load_in_8bit @load_in_8bit.setter def load_in_8bit(self, value: bool): if not isinstance(value, bool): raise TypeError("load_in_8bit must be a boolean") if self.load_in_4bit and value: raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time") self._load_in_8bit = value def post_init(self): r""" Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. """ if not isinstance(self.load_in_4bit, bool): raise TypeError("load_in_4bit must be a boolean") if not isinstance(self.load_in_8bit, bool): raise TypeError("load_in_8bit must be a boolean") if not isinstance(self.llm_int8_threshold, float): raise TypeError("llm_int8_threshold must be a float") if self.llm_int8_skip_modules is not None and not isinstance(self.llm_int8_skip_modules, list): raise TypeError("llm_int8_skip_modules must be a list of strings") if not isinstance(self.llm_int8_enable_fp32_cpu_offload, bool): raise TypeError("llm_int8_enable_fp32_cpu_offload must be a boolean") if not isinstance(self.llm_int8_has_fp16_weight, bool): raise TypeError("llm_int8_has_fp16_weight must be a boolean") if self.bnb_4bit_compute_dtype is not None and not isinstance(self.bnb_4bit_compute_dtype, torch.dtype): raise TypeError("bnb_4bit_compute_dtype must be torch.dtype") if not isinstance(self.bnb_4bit_quant_type, str): raise TypeError("bnb_4bit_quant_type must be a string") if not isinstance(self.bnb_4bit_use_double_quant, bool): raise TypeError("bnb_4bit_use_double_quant must be a boolean") if self.load_in_4bit and not version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse( "0.39.0" ): raise ValueError( "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version" ) def is_quantizable(self): r""" Returns `True` if the model is quantizable, `False` otherwise. """ return self.load_in_8bit or self.load_in_4bit def quantization_method(self): r""" This method returns the quantization method used for the model. If the model is not quantizable, it returns `None`. """ if self.load_in_8bit: return "llm_int8" elif self.load_in_4bit and self.bnb_4bit_quant_type == "fp4": return "fp4" elif self.load_in_4bit and self.bnb_4bit_quant_type == "nf4": return "nf4" else: return None 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 configuration instance. """ output = copy.deepcopy(self.__dict__) output["bnb_4bit_compute_dtype"] = str(output["bnb_4bit_compute_dtype"]).split(".")[1] output["bnb_4bit_quant_storage"] = str(output["bnb_4bit_quant_storage"]).split(".")[1] output["load_in_4bit"] = self.load_in_4bit output["load_in_8bit"] = self.load_in_8bit return output def __repr__(self): config_dict = self.to_dict() return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n" def to_diff_dict(self) -> dict[str, Any]: """ Removes all attributes from config which correspond to the default config attributes for better readability and serializes to a Python dictionary. Returns: `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance, """ config_dict = self.to_dict() # get the default config dict default_config_dict = BitsAndBytesConfig().to_dict() serializable_config_dict = {} # only serialize values that differ from the default config for key, value in config_dict.items(): if value != default_config_dict[key]: serializable_config_dict[key] = value return serializable_config_dict class ExllamaVersion(int, Enum): ONE = 1 TWO = 2 @dataclass class GPTQConfig(QuantizationConfigMixin): """ This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded using `optimum` api for gptq quantization relying on auto_gptq backend. Args: bits (`int`): The number of bits to quantize to, supported numbers are (2, 3, 4, 8). tokenizer (`str` or `PreTrainedTokenizerBase`, *optional*): The tokenizer used to process the dataset. You can pass either: - A custom tokenizer object. - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co. - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`. dataset (`Union[list[str]]`, *optional*): The dataset used for quantization. You can provide your own dataset in a list of string or just use the original datasets used in GPTQ paper ['wikitext2','c4','c4-new'] group_size (`int`, *optional*, defaults to 128): The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization. damp_percent (`float`, *optional*, defaults to 0.1): The percent of the average Hessian diagonal to use for dampening. Recommended value is 0.1. desc_act (`bool`, *optional*, defaults to `False`): Whether to quantize columns in order of decreasing activation size. Setting it to False can significantly speed up inference but the perplexity may become slightly worse. Also known as act-order. sym (`bool`, *optional*, defaults to `True`): Whether to use symmetric quantization. true_sequential (`bool`, *optional*, defaults to `True`): Whether to perform sequential quantization even within a single Transformer block. Instead of quantizing the entire block at once, we perform layer-wise quantization. As a result, each layer undergoes quantization using inputs that have passed through the previously quantized layers. checkpoint_format (`str`, *optional*, defaults to `"gptq"`): GPTQ weight format. `gptq`(v1) is supported by both gptqmodel and auto-gptq. `gptq_v2` is gptqmodel only. meta (`dict[str, any]`, *optional*): Properties, such as tooling:version, that do not directly contributes to quantization or quant inference are stored in meta. i.e. `meta.quantizer`: ["optimum:_version_", "gptqmodel:_version_"] backend (`str`, *optional*): Controls which gptq kernel to be used. Valid values for gptqmodel are `auto`, `auto_trainable` and more. For auto-gptq, only valid value is None and `auto_trainable`. Ref gptqmodel backends: https://github.com/ModelCloud/GPTQModel/blob/main/gptqmodel/utils/backend.py use_cuda_fp16 (`bool`, *optional*, defaults to `False`): Whether or not to use optimized cuda kernel for fp16 model. Need to have model in fp16. Auto-gptq only. model_seqlen (`int`, *optional*): The maximum sequence length that the model can take. block_name_to_quantize (`str`, *optional*): The transformers block name to quantize. If None, we will infer the block name using common patterns (e.g. model.layers) module_name_preceding_first_block (`list[str]`, *optional*): The layers that are preceding the first Transformer block. batch_size (`int`, *optional*, defaults to 1): The batch size used when processing the dataset pad_token_id (`int`, *optional*): The pad token id. Needed to prepare the dataset when `batch_size` > 1. use_exllama (`bool`, *optional*): Whether to use exllama backend. Defaults to `True` if unset. Only works with `bits` = 4. max_input_length (`int`, *optional*): The maximum input length. This is needed to initialize a buffer that depends on the maximum expected input length. It is specific to the exllama backend with act-order. exllama_config (`dict[str, Any]`, *optional*): The exllama config. You can specify the version of the exllama kernel through the `version` key. Defaults to `{"version": 1}` if unset. cache_block_outputs (`bool`, *optional*, defaults to `True`): Whether to cache block outputs to reuse as inputs for the succeeding block. modules_in_block_to_quantize (`list[list[str]]`, *optional*): List of list of module names to quantize in the specified block. This argument is useful to exclude certain linear modules from being quantized. The block to quantize can be specified by setting `block_name_to_quantize`. We will quantize each list sequentially. If not set, we will quantize all linear layers. Example: `modules_in_block_to_quantize =[["self_attn.k_proj", "self_attn.v_proj", "self_attn.q_proj"], ["self_attn.o_proj"]]`. In this example, we will first quantize the q,k,v layers simultaneously since they are independent. Then, we will quantize `self_attn.o_proj` layer with the q,k,v layers quantized. This way, we will get better results since it reflects the real input `self_attn.o_proj` will get when the model is quantized. """ def __init__( self, bits: int, tokenizer: Any = None, dataset: Optional[Union[list[str], str]] = None, group_size: int = 128, damp_percent: float = 0.1, desc_act: bool = False, sym: bool = True, true_sequential: bool = True, checkpoint_format: str = "gptq", meta: Optional[dict[str, Any]] = None, backend: Optional[str] = None, use_cuda_fp16: bool = False, model_seqlen: Optional[int] = None, block_name_to_quantize: Optional[str] = None, module_name_preceding_first_block: Optional[list[str]] = None, batch_size: int = 1, pad_token_id: Optional[int] = None, use_exllama: Optional[bool] = None, max_input_length: Optional[int] = None, exllama_config: Optional[dict[str, Any]] = None, cache_block_outputs: bool = True, modules_in_block_to_quantize: Optional[list[list[str]]] = None, **kwargs, ): self.quant_method = QuantizationMethod.GPTQ self.bits = bits self.tokenizer = tokenizer self.dataset = dataset self.group_size = group_size self.damp_percent = damp_percent self.desc_act = desc_act self.sym = sym self.true_sequential = true_sequential self.checkpoint_format = checkpoint_format.lower() self.meta = meta self.backend = backend.lower() if isinstance(backend, str) else backend self.use_cuda_fp16 = use_cuda_fp16 self.model_seqlen = model_seqlen self.block_name_to_quantize = block_name_to_quantize self.module_name_preceding_first_block = module_name_preceding_first_block self.batch_size = batch_size self.pad_token_id = pad_token_id self.use_exllama = use_exllama self.max_input_length = max_input_length self.exllama_config = exllama_config self.cache_block_outputs = cache_block_outputs self.modules_in_block_to_quantize = modules_in_block_to_quantize self.post_init() def get_loading_attributes(self): attibutes_dict = copy.deepcopy(self.__dict__) loading_attibutes = [ "use_exllama", "exllama_config", "use_cuda_fp16", "max_input_length", "backend", ] loading_attibutes_dict = {i: j for i, j in attibutes_dict.items() if i in loading_attibutes} return loading_attibutes_dict def post_init(self): r""" Safety checker that arguments are correct """ if self.bits not in [2, 3, 4, 8]: raise ValueError(f"Only support quantization to [2,3,4,8] bits but found {self.bits}") if self.group_size != -1 and self.group_size <= 0: raise ValueError("group_size must be greater than 0 or equal to -1") if not (0 < self.damp_percent < 1): raise ValueError("damp_percent must between 0 and 1.") if self.dataset is not None: if isinstance(self.dataset, str): if self.dataset in ["ptb", "ptb-new"]: raise ValueError( f"""{self.dataset} dataset was deprecated. You can only choose between ['wikitext2','c4','c4-new']""" ) if self.dataset not in ["wikitext2", "c4", "c4-new"]: raise ValueError( f"""You have entered a string value for dataset. You can only choose between ['wikitext2','c4','c4-new'], but we found {self.dataset}""" ) elif not isinstance(self.dataset, list): raise ValueError( f"""dataset needs to be either a list of string or a value in ['wikitext2','c4','c4-new'], but we found {self.dataset}""" ) # make sure backend is back/forward compatible with both gptqmodel (full) and auto-gptq (partial) if is_gptqmodel_available(): # convert auto-gptq control into gptqmodel backend if self.backend is None: self.backend = "auto_trainable" if self.use_exllama is not None and not self.use_exllama else "auto" else: # convert gptqmodel backend `auto_trainable` into auto-gptq control if self.backend == "auto_trainable": self.use_exllama = False # auto-gptq specific kernel control logic if self.use_exllama is None: # New default behaviour self.use_exllama = True if self.exllama_config is None: self.exllama_config = {"version": ExllamaVersion.ONE} else: if "version" not in self.exllama_config: raise ValueError("`exllama_config` needs to have a `version` key.") elif self.exllama_config["version"] not in [ExllamaVersion.ONE, ExllamaVersion.TWO]: exllama_version = self.exllama_config["version"] raise ValueError( f"Only supported versions are in [ExllamaVersion.ONE, ExllamaVersion.TWO] - not recognized version {exllama_version}" ) if self.bits == 4 and self.use_exllama: if self.exllama_config["version"] == ExllamaVersion.ONE: logger.info( "You have activated exllama backend. Note that you can get better inference " "speed using exllamav2 kernel by setting `exllama_config`." ) elif self.exllama_config["version"] == ExllamaVersion.TWO: if is_auto_gptq_available(): optimum_version = version.parse(importlib.metadata.version("optimum")) autogptq_version = version.parse(importlib.metadata.version("auto_gptq")) if optimum_version <= version.parse("1.13.2") or autogptq_version <= version.parse("0.4.2"): raise ValueError( f"You need optimum > 1.13.2 and auto-gptq > 0.4.2 . Make sure to have that version installed - detected version : optimum {optimum_version} and autogptq {autogptq_version}" ) if self.modules_in_block_to_quantize is not None: optimum_version = version.parse(importlib.metadata.version("optimum")) if optimum_version < version.parse("1.15.0"): raise ValueError( "You current version of `optimum` does not support `modules_in_block_to_quantize` quantization argument, please upgrade `optimum` package to a version superior than 1.15.0 ." ) def to_dict(self): config_dict = super().to_dict() config_dict.pop("disable_exllama", None) return config_dict def to_dict_optimum(self): """ Get compatible dict for optimum gptq config """ quant_dict = self.to_dict() # make it compatible with optimum config quant_dict["disable_exllama"] = not self.use_exllama return quant_dict @classmethod def from_dict_optimum(cls, config_dict): """ Get compatible class with optimum gptq config dict """ if "disable_exllama" in config_dict: config_dict["use_exllama"] = not config_dict["disable_exllama"] # switch to None to not trigger the warning config_dict.pop("disable_exllama") config = cls(**config_dict) return config @dataclass class AwqConfig(QuantizationConfigMixin): """ This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded using `auto-awq` library awq quantization relying on auto_awq backend. Args: bits (`int`, *optional*, defaults to 4): The number of bits to quantize to. group_size (`int`, *optional*, defaults to 128): The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization. zero_point (`bool`, *optional*, defaults to `True`): Whether to use zero point quantization. version (`AWQLinearVersion`, *optional*, defaults to `AWQLinearVersion.GEMM`): The version of the quantization algorithm to use. GEMM is better for big batch_size (e.g. >= 8) otherwise, GEMV is better (e.g. < 8 ). GEMM models are compatible with Exllama kernels. backend (`AwqBackendPackingMethod`, *optional*, defaults to `AwqBackendPackingMethod.AUTOAWQ`): The quantization backend. Some models might be quantized using `llm-awq` backend. This is useful for users that quantize their own models using `llm-awq` library. do_fuse (`bool`, *optional*, defaults to `False`): Whether to fuse attention and mlp layers together for faster inference fuse_max_seq_len (`int`, *optional*): The Maximum sequence length to generate when using fusing. modules_to_fuse (`dict`, *optional*, default to `None`): Overwrite the natively supported fusing scheme with the one specified by the users. modules_to_not_convert (`list`, *optional*, default to `None`): The list of modules to not quantize, useful for quantizing models that explicitly require to have some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers). Note you cannot quantize directly with transformers, please refer to `AutoAWQ` documentation for quantizing HF models. exllama_config (`dict[str, Any]`, *optional*): You can specify the version of the exllama kernel through the `version` key, the maximum sequence length through the `max_input_len` key, and the maximum batch size through the `max_batch_size` key. Defaults to `{"version": 2, "max_input_len": 2048, "max_batch_size": 8}` if unset. """ def __init__( self, bits: int = 4, group_size: int = 128, zero_point: bool = True, version: AWQLinearVersion = AWQLinearVersion.GEMM, backend: AwqBackendPackingMethod = AwqBackendPackingMethod.AUTOAWQ, do_fuse: Optional[bool] = None, fuse_max_seq_len: Optional[int] = None, modules_to_fuse: Optional[dict] = None, modules_to_not_convert: Optional[list] = None, exllama_config: Optional[dict[str, int]] = None, **kwargs, ): self.quant_method = QuantizationMethod.AWQ self.bits = bits self.group_size = group_size self.zero_point = zero_point self.version = version self.backend = backend self.fuse_max_seq_len = fuse_max_seq_len self.modules_to_not_convert = modules_to_not_convert self.exllama_config = exllama_config self.modules_to_fuse = modules_to_fuse if do_fuse is None: self.do_fuse = modules_to_fuse is not None and len(modules_to_fuse) > 0 else: self.do_fuse = do_fuse self.fuse_max_seq_len = fuse_max_seq_len self.post_init() def post_init(self): r""" Safety checker that arguments are correct """ if self.backend not in [AwqBackendPackingMethod.AUTOAWQ, AwqBackendPackingMethod.LLMAWQ]: raise ValueError( f"Only supported quantization backends in {AwqBackendPackingMethod.AUTOAWQ} and {AwqBackendPackingMethod.LLMAWQ} - not recognized backend {self.backend}" ) self.version = AWQLinearVersion.from_str(self.version) if self.version not in [ AWQLinearVersion.GEMM, AWQLinearVersion.GEMV, AWQLinearVersion.EXLLAMA, AWQLinearVersion.IPEX, ]: raise ValueError( f"Only supported versions are in [AWQLinearVersion.GEMM, AWQLinearVersion.GEMV, AWQLinearVersion.EXLLAMA, AWQLinearVersion.IPEX] - not recognized version {self.version}" ) if self.backend == AwqBackendPackingMethod.LLMAWQ: # Only cuda device can run this function if not (torch.cuda.is_available() or torch.xpu.is_available()): raise ValueError("LLM-AWQ backend is only supported on CUDA and XPU") if torch.cuda.is_available(): compute_capability = torch.cuda.get_device_capability() major, minor = compute_capability if major < 8: raise ValueError("LLM-AWQ backend is only supported on CUDA GPUs with compute capability >= 8.0") if self.do_fuse and self.fuse_max_seq_len is None: raise ValueError( "You cannot enable fused modules without specifying a `fuse_max_seq_len`, make sure to pass a valid `fuse_max_seq_len` for your usecase" ) if self.do_fuse: awq_version_supports_fusing = False MIN_AWQ_VERSION = "0.1.7" if is_auto_awq_available(): awq_version_supports_fusing = version.parse(importlib.metadata.version("autoawq")) >= version.parse( MIN_AWQ_VERSION ) if not awq_version_supports_fusing: raise ValueError( f"You current version of `autoawq` does not support module fusing, please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}." ) if self.modules_to_not_convert is not None: awq_version_supports_non_conversion = False MIN_AWQ_VERSION = "0.1.8" if is_auto_awq_available(): awq_version_supports_non_conversion = version.parse( importlib.metadata.version("autoawq") ) >= version.parse(MIN_AWQ_VERSION) if not awq_version_supports_non_conversion: raise ValueError( f"You current version of `autoawq` does not support module quantization skipping, please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}." ) if self.do_fuse and self.modules_to_fuse is not None: required_keys = [ "hidden_size", "num_attention_heads", "num_key_value_heads", "mlp", "attention", "layernorm", "use_alibi", ] if not all(key in self.modules_to_fuse for key in required_keys): raise ValueError( f"Required fields are missing in the fusing mapping, required fields are {required_keys}" ) if self.version == AWQLinearVersion.EXLLAMA: awq_version_supports_exllama = False MIN_AWQ_VERSION = "0.2.0" if is_auto_awq_available(): awq_version_supports_exllama = version.parse(importlib.metadata.version("autoawq")) >= version.parse( MIN_AWQ_VERSION ) if not awq_version_supports_exllama: raise ValueError( f"You current version of `autoawq` does not support exllama backend, " f"please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}." ) if self.exllama_config is None: self.exllama_config = {"version": ExllamaVersion.TWO, "max_input_len": 2048, "max_batch_size": 8} else: if "version" not in self.exllama_config: raise ValueError("`exllama_config` needs to have a `version` key.") elif self.exllama_config["version"] not in [ExllamaVersion.ONE, ExllamaVersion.TWO]: exllama_version = self.exllama_config["version"] raise ValueError( f"Only supported versions are in [ExllamaVersion.ONE, ExllamaVersion.TWO] - not recognized version {exllama_version}" ) def get_loading_attributes(self): attibutes_dict = copy.deepcopy(self.__dict__) loading_attibutes = ["version", "do_fuse", "modules_to_fuse", "fuse_max_seq_len", "exllama_config"] loading_attibutes_dict = {i: j for i, j in attibutes_dict.items() if i in loading_attibutes} return loading_attibutes_dict @dataclass class AqlmConfig(QuantizationConfigMixin): """ This is a wrapper class about `aqlm` parameters. Args: in_group_size (`int`, *optional*, defaults to 8): The group size along the input dimension. out_group_size (`int`, *optional*, defaults to 1): The group size along the output dimension. It's recommended to always use 1. num_codebooks (`int`, *optional*, defaults to 1): Number of codebooks for the Additive Quantization procedure. nbits_per_codebook (`int`, *optional*, defaults to 16): Number of bits encoding a single codebook vector. Codebooks size is 2**nbits_per_codebook. linear_weights_not_to_quantize (`Optional[list[str]]`, *optional*): List of full paths of `nn.Linear` weight parameters that shall not be quantized. kwargs (`dict[str, Any]`, *optional*): Additional parameters from which to initialize the configuration object. """ def __init__( self, in_group_size: int = 8, out_group_size: int = 1, num_codebooks: int = 1, nbits_per_codebook: int = 16, linear_weights_not_to_quantize: Optional[list[str]] = None, **kwargs, ): self.quant_method = QuantizationMethod.AQLM self.in_group_size = in_group_size self.out_group_size = out_group_size self.num_codebooks = num_codebooks self.nbits_per_codebook = nbits_per_codebook self.linear_weights_not_to_quantize = linear_weights_not_to_quantize self.post_init() def post_init(self): r""" Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. """ if not isinstance(self.in_group_size, int): raise TypeError("in_group_size must be a float") if not isinstance(self.out_group_size, int): raise TypeError("out_group_size must be a float") if not isinstance(self.num_codebooks, int): raise TypeError("num_codebooks must be a float") if not isinstance(self.nbits_per_codebook, int): raise TypeError("nbits_per_codebook must be a float") if self.linear_weights_not_to_quantize is not None and not isinstance( self.linear_weights_not_to_quantize, list ): raise ValueError("linear_weights_not_to_quantize must be a list of strings") if self.linear_weights_not_to_quantize is None: self.linear_weights_not_to_quantize = [] @dataclass class VptqLayerConfig(QuantizationConfigMixin): """ This is used to explain vptq config params for each layer Args: enable_norm (`bool`, *optional*, defaults to `True`): to control if we have scale/bias for fp-weight enable_perm (`bool`, *optional*, defaults to `True`): to perm input_channel or not group_num (`int`, *optional*, defaults to `1`): how many single groups for vector-quantization group_size (`int`, *optional*, defaults to `-1`): depends on out-features indices_as_float (`bool`, *optional*, defaults to `False`): for Finetuning is_indice_packed (`bool`, *optional*, defaults to `True`): should always be True num_centroids (`list`, *optional*, defaults to `[-1, -1]`): centroid numbers of clusters num_res_centroids (`list`, *optional*, defaults to `[-1, -1]`): ditto for residual outlier_size (`int`, *optional*, defaults to `1`): outliers vector_lens (`list`, *optional*, defaults to `[-1, -1]`): centroid vector length in quantization """ def __init__( self, enable_norm: bool = True, enable_perm: bool = True, group_num: int = 1, group_size: int = -1, in_features: int = -1, indices_as_float: bool = False, is_indice_packed: bool = True, num_centroids: tuple = [-1, -1], num_res_centroids: tuple = [-1, -1], out_features: int = -1, outlier_size: int = 0, vector_lens: tuple = [-1, -1], **kwargs, ): self.enable_norm = enable_norm self.enable_perm = enable_perm self.group_num = group_num self.group_size = group_size self.in_features = in_features self.indices_as_float = indices_as_float self.is_indice_packed = is_indice_packed self.num_centroids = num_centroids self.num_res_centroids = num_res_centroids self.out_features = out_features self.outlier_size = outlier_size self.vector_lens = vector_lens self.post_init() def post_init(self): r""" Safety checker that arguments are correct """ if self.is_indice_packed is False: raise ValueError("is_indice_packed should always be True") @dataclass class VptqConfig(QuantizationConfigMixin): """ This is a wrapper class about `vptq` parameters. Args: enable_proxy_error (`bool`, *optional*, defaults to `False`): calculate proxy error for each layer config_for_layers (`Dict`, *optional*, defaults to `{}`): quantization params for each layer shared_layer_config (`Dict`, *optional*, defaults to `{}`): shared quantization params among layers modules_to_not_convert (`list`, *optional*, default to `None`): The list of modules to not quantize, useful for quantizing models that explicitly require to have some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers). kwargs (`dict[str, Any]`, *optional*): Additional parameters from which to initialize the configuration object. """ def __init__( self, enable_proxy_error: bool = False, config_for_layers: dict[str, Any] = {}, shared_layer_config: dict[str, Any] = {}, modules_to_not_convert: Optional[list] = None, **kwargs, ): self.quant_method = QuantizationMethod.VPTQ self.enable_proxy_error = enable_proxy_error self.config_for_layers: dict[str, Any] = config_for_layers self.shared_layer_config: dict[str, Any] = shared_layer_config self.modules_to_not_convert = modules_to_not_convert self.post_init() def post_init(self): r""" Safety checker that arguments are correct """ for layer_param in self.config_for_layers.values(): VptqLayerConfig(**layer_param) if self.enable_proxy_error is True: raise ValueError("enable_proxy_error should always be False until we support training") @dataclass class QuantoConfig(QuantizationConfigMixin): """ This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded using `quanto`. Args: weights (`str`, *optional*, defaults to `"int8"`): The target dtype for the weights after quantization. Supported values are ("float8","int8","int4","int2") activations (`str`, *optional*): The target dtype for the activations after quantization. Supported values are (None,"int8","float8") modules_to_not_convert (`list`, *optional*, default to `None`): The list of modules to not quantize, useful for quantizing models that explicitly require to have some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers). """ def __init__( self, weights="int8", activations=None, modules_to_not_convert: Optional[list] = None, **kwargs, ): self.quant_method = QuantizationMethod.QUANTO self.weights = weights self.activations = activations self.modules_to_not_convert = modules_to_not_convert self.post_init() def post_init(self): r""" Safety checker that arguments are correct """ accepted_weights = ["float8", "int8", "int4", "int2"] accepted_activations = [None, "int8", "float8"] if self.weights not in accepted_weights: raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}") if self.activations not in accepted_activations: raise ValueError(f"Only support weights in {accepted_activations} but found {self.activations}") @dataclass class EetqConfig(QuantizationConfigMixin): """ This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded using `eetq`. Args: weights (`str`, *optional*, defaults to `"int8"`): The target dtype for the weights. Supported value is only "int8" modules_to_not_convert (`list`, *optional*, default to `None`): The list of modules to not quantize, useful for quantizing models that explicitly require to have some modules left in their original precision. """ def __init__( self, weights: str = "int8", modules_to_not_convert: Optional[list] = None, **kwargs, ): self.quant_method = QuantizationMethod.EETQ self.weights = weights self.modules_to_not_convert = modules_to_not_convert self.post_init() def post_init(self): r""" Safety checker that arguments are correct """ accepted_weights = ["int8"] if self.weights not in accepted_weights: raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}") class CompressedTensorsConfig(QuantizationConfigMixin): """ This is a wrapper class that handles compressed-tensors quantization config options. It is a wrapper around `compressed_tensors.QuantizationConfig` Args: config_groups (`typing.dict[str, typing.Union[ForwardRef('QuantizationScheme'), typing.list[str]]]`, *optional*): dictionary mapping group name to a quantization scheme definition format (`str`, *optional*, defaults to `"dense"`): format the model is represented as. Set `run_compressed` True to execute model as the compressed format if not `dense` quantization_status (`QuantizationStatus`, *optional*, defaults to `"initialized"`): status of model in the quantization lifecycle, ie 'initialized', 'calibration', 'frozen' kv_cache_scheme (`typing.Union[QuantizationArgs, NoneType]`, *optional*): specifies quantization of the kv cache. If None, kv cache is not quantized. global_compression_ratio (`typing.Union[float, NoneType]`, *optional*): 0-1 float percentage of model compression ignore (`typing.Union[typing.list[str], NoneType]`, *optional*): layer names or types to not quantize, supports regex prefixed by 're:' sparsity_config (`typing.dict[str, typing.Any]`, *optional*): configuration for sparsity compression quant_method (`str`, *optional*, defaults to `"compressed-tensors"`): do not override, should be compressed-tensors run_compressed (`bool`, *optional*, defaults to `True`): alter submodules (usually linear) in order to emulate compressed model execution if True, otherwise use default submodule """ def __init__( self, config_groups: Optional[dict[str, Union["QuantizationScheme", list[str]]]] = None, # noqa: F821 format: str = "dense", quantization_status: "QuantizationStatus" = "initialized", # noqa: F821 kv_cache_scheme: Optional["QuantizationArgs"] = None, # noqa: F821 global_compression_ratio: Optional[float] = None, ignore: Optional[list[str]] = None, sparsity_config: Optional[dict[str, Any]] = None, quant_method: str = "compressed-tensors", run_compressed: bool = True, **kwargs, ): if is_compressed_tensors_available(): from compressed_tensors.config import SparsityCompressionConfig from compressed_tensors.quantization import QuantizationConfig else: raise ImportError( "compressed_tensors is not installed and is required for compressed-tensors quantization. Please install it with `pip install compressed-tensors`." ) self.quantization_config = None self.sparsity_config = None self.run_compressed = run_compressed # parse from dict to load nested QuantizationScheme objects if config_groups or kv_cache_scheme: self.quantization_config = QuantizationConfig.model_validate( { "config_groups": config_groups, "quant_method": quant_method, "format": format, "quantization_status": quantization_status, "kv_cache_scheme": kv_cache_scheme, "global_compression_ratio": global_compression_ratio, "ignore": ignore, **kwargs, } ) if sparsity_config: self.sparsity_config = SparsityCompressionConfig.load_from_registry( sparsity_config.get("format"), **sparsity_config ) self.quant_method = QuantizationMethod.COMPRESSED_TENSORS def post_init(self): if self.run_compressed: if self.is_sparsification_compressed: logger.warning( "`run_compressed` is only supported for quantized_compressed models" " and not for sparsified models. Setting `run_compressed=False`" ) self.run_compressed = False elif not self.is_quantization_compressed: logger.warning( "`run_compressed` is only supported for compressed models. Setting `run_compressed=False`" ) self.run_compressed = False @classmethod def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): """ Instantiates a [`CompressedTensorsConfig`] from a Python dictionary of parameters. Optionally unwraps any args from the nested quantization_config Args: config_dict (`dict[str, Any]`): Dictionary that will be used to instantiate the configuration object. return_unused_kwargs (`bool`,*optional*, defaults to `False`): Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in `PreTrainedModel`. kwargs (`dict[str, Any]`): Additional parameters from which to initialize the configuration object. Returns: [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters. """ if "quantization_config" in config_dict: config_dict = dict( sparsity_config=config_dict.get("sparsity_config"), **config_dict["quantization_config"], ) return super().from_dict(config_dict, return_unused_kwargs=return_unused_kwargs, **kwargs) def to_dict(self) -> dict[str, Any]: """ Quantization config to be added to config.json Serializes this instance to a Python dictionary. Returns: `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance. """ quantization_config = {} if self.quantization_config is not None: quantization_config = self.quantization_config.model_dump() else: quantization_config["quant_method"] = QuantizationMethod.COMPRESSED_TENSORS if self.sparsity_config is not None: quantization_config["sparsity_config"] = self.sparsity_config.model_dump() else: quantization_config["sparsity_config"] = {} return quantization_config def to_diff_dict(self) -> dict[str, Any]: """ Removes all attributes from config which correspond to the default config attributes for better readability and serializes to a Python dictionary. Returns: `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance, """ config_dict = self.to_dict() # get the default config dict default_config_dict = CompressedTensorsConfig().to_dict() serializable_config_dict = {} # only serialize values that differ from the default config for key, value in config_dict.items(): if key not in default_config_dict or value != default_config_dict[key]: serializable_config_dict[key] = value return serializable_config_dict def get_loading_attributes(self): return {"run_compressed": self.run_compressed} @property def is_quantized(self): return bool(self.quantization_config) and bool(self.quantization_config.config_groups) @property def is_quantization_compressed(self): from compressed_tensors.quantization import QuantizationStatus return self.is_quantized and self.quantization_config.quantization_status == QuantizationStatus.COMPRESSED @property def is_sparsification_compressed(self): from compressed_tensors.config import ( CompressionFormat, SparsityCompressionConfig, ) return ( isinstance(self.sparsity_config, SparsityCompressionConfig) and self.sparsity_config.format != CompressionFormat.dense.value ) @dataclass class FbgemmFp8Config(QuantizationConfigMixin): """ This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded using fbgemm fp8 quantization. Args: activation_scale_ub (`float`, *optional*, defaults to 1200.0): The activation scale upper bound. This is used when quantizing the input activation. modules_to_not_convert (`list`, *optional*, default to `None`): The list of modules to not quantize, useful for quantizing models that explicitly require to have some modules left in their original precision. """ def __init__( self, activation_scale_ub: float = 1200.0, modules_to_not_convert: Optional[list] = None, **kwargs, ): self.quant_method = QuantizationMethod.FBGEMM_FP8 self.activation_scale_ub = activation_scale_ub self.modules_to_not_convert = modules_to_not_convert def get_loading_attributes(self): attibutes_dict = copy.deepcopy(self.__dict__) loading_attibutes = ["activation_scale_ub"] loading_attibutes_dict = {i: j for i, j in attibutes_dict.items() if i in loading_attibutes} return loading_attibutes_dict @dataclass class HiggsConfig(QuantizationConfigMixin): """ HiggsConfig is a configuration class for quantization using the HIGGS method. Args: bits (int, *optional*, defaults to 4): Number of bits to use for quantization. Can be 2, 3 or 4. Default is 4. p (int, *optional*, defaults to 2): Quantization grid dimension. 1 and 2 are supported. 2 is always better in practice. Default is 2. modules_to_not_convert (`list`, *optional*, default to ["lm_head"]): List of linear layers that should not be quantized. hadamard_size (int, *optional*, defaults to 512): Hadamard size for the HIGGS method. Default is 512. Input dimension of matrices is padded to this value. Decreasing this below 512 will reduce the quality of the quantization. group_size (int, *optional*, defaults to 256): Group size for the HIGGS method. Can be 64, 128 or 256. Decreasing it barely affects the performance. Default is 256. Must be a divisor of hadamard_size. tune_metadata ('dict', *optional*, defaults to {}): Module-wise metadata (gemm block shapes, GPU metadata, etc.) for saving the kernel tuning results. Default is an empty dictionary. Is set automatically during tuning. """ def __init__( self, bits: int = 4, p: int = 2, modules_to_not_convert: Optional[list[str]] = None, hadamard_size: int = 512, group_size: int = 256, tune_metadata: Optional[dict[str, Any]] = None, **kwargs, ): if tune_metadata is None: tune_metadata = {} self.quant_method = QuantizationMethod.HIGGS self.bits = bits self.p = p self.modules_to_not_convert = modules_to_not_convert self.hadamard_size = hadamard_size self.group_size = group_size self.tune_metadata = tune_metadata self.post_init() def post_init(self): r""" Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. """ if self.bits not in [2, 3, 4]: raise ValueError("bits must be 2, 3, or 4") if self.p not in [1, 2]: raise ValueError("p must be 1 or 2. 2 is always better in practice") if self.group_size not in [64, 128, 256]: raise ValueError("group_size must be 64, 128, or 256") if self.hadamard_size % self.group_size != 0: raise ValueError("hadamard_size must be divisible by group_size") @dataclass class FPQuantConfig(QuantizationConfigMixin): """ FPQuantConfig is a configuration class for quantization using the FPQuant method. Args: forward_dtype (`str`, *optional*, defaults to `"mxfp4"`): The dtype to use for the forward pass. forward_method (`str`, *optional*, defaults to `"abs_max"`): The scaling to use for the forward pass. Can be `"abs_max"` or `"quest"`. `"abs_max"` is better for PTQ, `"quest"` is better for QAT. backward_dtype (`str`, *optional*, defaults to `"bf16"`): The dtype to use for the backward pass. store_master_weights (`bool`, *optional*, defaults to `False`): Whether to store the master weights. Needed for QAT over layer weights. hadamard_group_size (`int`, *optional*, defaults to 32): The group size for the hadamard transform before quantization for `"quest"` it matches the MXFP4 group size (32). pseudoquantization (`bool`, *optional*, defaults to `False`): Whether to use Triton-based pseudo-quantization. Is mandatory for non-Blackwell GPUs. Doesn't provide any speedup. For debugging purposes. modules_to_not_convert (`list`, *optional*): The list of modules to not quantize, useful for quantizing models that explicitly require to have some modules left in their original precision. """ def __init__( self, forward_dtype: str = "mxfp4", forward_method: str = "abs_max", backward_dtype: str = "bf16", store_master_weights: bool = False, hadamard_group_size: int = 32, pseudoquantization: bool = False, modules_to_not_convert: Optional[list[str]] = None, **kwargs, ): self.forward_dtype = forward_dtype self.forward_method = forward_method self.backward_dtype = backward_dtype self.store_master_weights = store_master_weights self.hadamard_group_size = hadamard_group_size self.pseudoquantization = pseudoquantization self.modules_to_not_convert = modules_to_not_convert self.quant_method = QuantizationMethod.FPQUANT self.post_init() def post_init(self): r""" Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. """ if self.forward_dtype not in ["mxfp4"]: raise ValueError("Only 'mxfp4' is supported for forward_dtype for now.") if self.forward_method not in ["abs_max", "quest"]: raise ValueError("Only 'abs_max' and 'quest' are supported for forward_method for now.") if self.backward_dtype not in ["bf16"]: raise ValueError("Only 'bf16' is supported for backward_dtype for now.") if self.hadamard_group_size not in [32]: raise ValueError("Only a hadamard_group_size of 32 is supported for now.") if self.modules_to_not_convert is None: self.modules_to_not_convert = ["lm_head"] @dataclass class TorchAoConfig(QuantizationConfigMixin): quant_method: QuantizationMethod quant_type: Union[str, "AOBaseConfig"] # noqa: F821 modules_to_not_convert: Optional[list] quant_type_kwargs: dict[str, Any] include_input_output_embeddings: bool untie_embedding_weights: bool """This is a config class for torchao quantization/sparsity techniques. Args: quant_type (`Union[str, AOBaseConfig]`): The type of quantization we want to use. Can be either: - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`. - An AOBaseConfig instance: for more advanced configuration options. modules_to_not_convert (`list`, *optional*, default to `None`): The list of modules to not quantize, useful for quantizing models that explicitly require to have some modules left in their original precision. include_input_output_embeddings (`bool`, default to `False`): Whether to include embedding in quantization or not, input embedding will be removed from the module_not_to_convert list as well if this flag is set. untie_embedding_weights (`bool`, default to `False`): Whether to untie the weights when we are quantizing input embedding weights that is tied to other weights. kwargs (`dict[str, Any]`, *optional*): The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques Example: ```python # AOBaseConfig-based configuration config = Int4WeightOnlyConfig(group_size=32) quantization_config = TorchAoConfig(config) model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", dtype=torch.bfloat16, quantization_config=quantization_config) # String-based configuration quantization_config = TorchAoConfig("int4_weight_only", group_size=32) # int4_weight_only quant is only working with *torch.bfloat16* dtype right now model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", dtype=torch.bfloat16, quantization_config=quantization_config) # autoquant # `autoquant` is a convenient way for users to search for the best quantization for each layer # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20) # defaults to None, which means we'll try to get the best performing quantized model without # considering accuracy quantization_config = TorchAoConfig("autoquant", min_sqnr=30) model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", dtype=torch.bfloat16, quantization_config=quantization_config) # run through example inputs, quantization methods will be selected based on the shape of example input tokenizer = AutoTokenizer.from_pretrained(model_name) input_text = "What are we having for dinner?" input_ids = tokenizer(input_text, return_tensors="pt").to("cuda") MAX_NEW_TOKENS = 1000 model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation="static") # manually ran finalize_autoquant if needed if hasattr(quantized_model, "finalize_autoquant"): print("finalizing autoquant") quantized_model.finalize_autoquant() ``` """ def __init__( self, quant_type: Union[str, "AOBaseConfig"], # noqa: F821 modules_to_not_convert: Optional[list] = None, include_input_output_embeddings: bool = False, untie_embedding_weights: bool = False, **kwargs, ): self.quant_method = QuantizationMethod.TORCHAO self.quant_type = quant_type self.modules_to_not_convert = modules_to_not_convert self.quant_type_kwargs = kwargs.get("quant_type_kwargs", kwargs) self.include_input_output_embeddings = include_input_output_embeddings self.untie_embedding_weights = untie_embedding_weights self.post_init() @staticmethod def _get_ao_version() -> version.Version: """Centralized check for TorchAO availability and version requirements.""" if not is_torchao_available(): raise ValueError("TorchAoConfig requires torchao to be installed. Install with `pip install torchao`") return version.parse(importlib.metadata.version("torchao")) def post_init(self): """Validate configuration and set defaults.""" ao_version = self._get_ao_version() # Handle quant_type based on type and version if isinstance(self.quant_type, str): self._validate_string_quant_type() elif ao_version > version.parse("0.9.0"): from torchao.quantization.quant_api import AOBaseConfig if not isinstance(self.quant_type, AOBaseConfig): raise TypeError( f"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}" ) else: raise ValueError( f"In torchao <= 0.9.0, quant_type must be a string. Got {type(self.quant_type)}. " f"Please upgrade to torchao > 0.9.0 to use AOBaseConfig instances." ) def _validate_string_quant_type(self): """Validate string quant_type and its kwargs.""" methods = self._get_torchao_quant_type_to_method() if self.quant_type not in methods: raise ValueError( f"Unsupported string quantization type: {self.quant_type}. " f"Supported types: {', '.join(methods.keys())}" ) # Validate kwargs against method signature method = methods[self.quant_type] sig = signature(method) valid_kwargs = { param.name for param in sig.parameters.values() if param.kind in [Parameter.KEYWORD_ONLY, Parameter.POSITIONAL_OR_KEYWORD] } invalid_kwargs = set(self.quant_type_kwargs) - valid_kwargs if invalid_kwargs: raise ValueError( f"Unexpected keyword arg for {self.quant_type}: {', '.join(invalid_kwargs)}. " f"Valid kwargs: {', '.join(valid_kwargs)}" ) def _get_torchao_quant_type_to_method(self): """Get mapping of quant_type strings to their corresponding methods.""" from torchao.quantization import ( autoquant, int4_weight_only, int8_dynamic_activation_int8_weight, int8_weight_only, ) return { "int4_weight_only": int4_weight_only, "int8_weight_only": int8_weight_only, "int8_dynamic_activation_int8_weight": int8_dynamic_activation_int8_weight, "autoquant": autoquant, } def get_apply_tensor_subclass(self): """Create the appropriate quantization method based on configuration.""" if isinstance(self.quant_type, str): methods = self._get_torchao_quant_type_to_method() quant_type_kwargs = self.quant_type_kwargs.copy() if ( not torch.cuda.is_available() and is_torchao_available() and self.quant_type == "int4_weight_only" and version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0") and quant_type_kwargs.get("layout", None) is None ): if torch.xpu.is_available(): if version.parse(importlib.metadata.version("torchao")) >= version.parse( "0.11.0" ) and version.parse(importlib.metadata.version("torch")) > version.parse("2.7.9"): from torchao.dtypes import Int4XPULayout from torchao.quantization.quant_primitives import ZeroPointDomain quant_type_kwargs["layout"] = Int4XPULayout() quant_type_kwargs["zero_point_domain"] = ZeroPointDomain.INT else: raise ValueError( "TorchAoConfig requires torchao >= 0.11.0 and torch >= 2.8.0 for XPU support. Please upgrade the version or use run on CPU with the cpu version pytorch." ) else: from torchao.dtypes import Int4CPULayout quant_type_kwargs["layout"] = Int4CPULayout() return methods[self.quant_type](**quant_type_kwargs) else: return self.quant_type def to_dict(self): """Convert configuration to a dictionary.""" d = super().to_dict() if isinstance(self.quant_type, str): # Handle layout serialization if present if "quant_type_kwargs" in d and "layout" in d["quant_type_kwargs"]: if is_dataclass(d["quant_type_kwargs"]["layout"]): d["quant_type_kwargs"]["layout"] = [ d["quant_type_kwargs"]["layout"].__class__.__name__, dataclasses.asdict(d["quant_type_kwargs"]["layout"]), ] if isinstance(d["quant_type_kwargs"]["layout"], list): assert len(d["quant_type_kwargs"]["layout"]) == 2, "layout saves layout name and layout kwargs" assert isinstance(d["quant_type_kwargs"]["layout"][0], str), "layout name must be a string" assert isinstance(d["quant_type_kwargs"]["layout"][1], dict), "layout kwargs must be a dict" else: raise ValueError("layout must be a list") else: # Handle AOBaseConfig serialization from torchao.core.config import config_to_dict # For now we assume there is 1 config per Transformer, however in the future # We may want to support a config per fqn. d["quant_type"] = {"default": config_to_dict(self.quant_type)} return d @classmethod def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): """Create configuration from a dictionary.""" ao_verison = cls._get_ao_version() assert ao_verison > version.parse("0.9.0"), "TorchAoConfig requires torchao > 0.9.0 for construction from dict" config_dict = config_dict.copy() quant_type = config_dict.pop("quant_type") if isinstance(quant_type, str): return cls(quant_type=quant_type, **config_dict) # Check if we only have one key which is "default" # In the future we may update this assert len(quant_type) == 1 and "default" in quant_type, ( "Expected only one key 'default' in quant_type dictionary" ) quant_type = quant_type["default"] # Deserialize quant_type if needed from torchao.core.config import config_from_dict quant_type = config_from_dict(quant_type) return cls(quant_type=quant_type, **config_dict) @dataclass class BitNetQuantConfig(QuantizationConfigMixin): """ Configuration class for applying BitNet quantization. Args: modules_to_not_convert (`Optional[List]`, *optional*): Optionally, provides a list of full paths of `nn.Linear` weight parameters that shall not be quantized. Defaults to None. linear_class (`str`, *optional*, defaults to `"bitlinear"`): The type of linear class to use. Can be either `bitlinear` or `autobitlinear`. quantization_mode (`str`, *optional*, defaults to `"offline"`): The quantization mode to use. Can be either `online` or `offline`. In `online` mode, the weight quantization parameters are calculated dynamically during each forward pass (e.g., based on the current weight values). This can adapt to weight changes during training (Quantization-Aware Training - QAT). In `offline` mode, quantization parameters are pre-calculated *before* inference. These parameters are then fixed and loaded into the quantized model. This generally results in lower runtime overhead compared to online quantization. use_rms_norm (`bool`, *optional*, defaults to `False`): Whether to apply RMSNorm on the activations before quantization. This matches the original BitNet paper's approach of normalizing activations before quantization/packing. rms_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon value used in the RMSNorm layer for numerical stability. kwargs (`dict[str, Any]`, *optional*): Additional keyword arguments that may be used by specific quantization backends or future versions. """ def __init__( self, modules_to_not_convert: Optional[list] = None, linear_class: Optional[str] = "bitlinear", quantization_mode: Optional[str] = "offline", use_rms_norm: Optional[bool] = False, rms_norm_eps: Optional[float] = 1e-6, **kwargs, ): if linear_class not in ["bitlinear", "autobitlinear"]: raise ValueError(f"linear_class must be either 'bitlinear' or 'autobitlinear', but got {linear_class}") if quantization_mode not in ["online", "offline"]: raise ValueError(f"quantization_mode must be either 'online' or 'offline', but got {quantization_mode}") self.quant_method = QuantizationMethod.BITNET self.modules_to_not_convert = modules_to_not_convert self.linear_class = linear_class self.quantization_mode = quantization_mode self.use_rms_norm = use_rms_norm self.rms_norm_eps = rms_norm_eps self.post_init() def post_init(self): r""" Safety checker that arguments are correct """ pass @dataclass class SpQRConfig(QuantizationConfigMixin): """ This is a wrapper class about `spqr` parameters. Refer to the original publication for more details. Args: bits (`int`, *optional*, defaults to 3): Specifies the bit count for the weights and first order zero-points and scales. Currently only bits = 3 is supported. beta1 (`int`, *optional*, defaults to 16): SpQR tile width. Currently only beta1 = 16 is supported. beta2 (`int`, *optional*, defaults to 16): SpQR tile height. Currently only beta2 = 16 is supported. shapes (`Optional`, *optional*): A dictionary holding the shape of each object. We need this because it's impossible to deduce the exact size of the parameters just from bits, beta1, beta2. modules_to_not_convert (`Optional[list[str]]`, *optional*): Optionally, provides a list of full paths of `nn.Linear` weight parameters that shall not be quantized. Defaults to None. kwargs (`dict[str, Any]`, *optional*): Additional parameters from which to initialize the configuration object. """ def __init__( self, bits: int = 3, beta1: int = 16, beta2: int = 16, shapes: Optional[dict[str, int]] = None, modules_to_not_convert: Optional[list[str]] = None, **kwargs, ): if shapes is None: shapes = {} self.shapes = shapes self.quant_method = QuantizationMethod.SPQR self.bits = bits self.beta1 = beta1 self.beta2 = beta2 self.modules_to_not_convert = modules_to_not_convert self.post_init() def post_init(self): r""" Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. """ if not isinstance(self.bits, int): raise TypeError("bits must be an int") if not isinstance(self.beta1, int): raise TypeError("beta1 must be an int") if not isinstance(self.beta2, int): raise TypeError("beta2 must be an int") if self.bits != 3: raise ValueError("SpQR currently only supports bits = 3") if self.beta1 != 16: raise ValueError("SpQR currently only supports beta1 = 16") if self.beta2 != 16: raise ValueError("SpQR currently only supports beta2 = 16") if not isinstance(self.shapes, dict): raise TypeError("shapes must be a dict") @dataclass class FineGrainedFP8Config(QuantizationConfigMixin): """ FineGrainedFP8Config is a configuration class for fine-grained FP8 quantization used mainly for deepseek models. Args: activation_scheme (`str`, *optional*, defaults to `"dynamic"`): The scheme used for activation, the defaults and only support scheme for now is "dynamic". weight_block_size (`typing.tuple[int, int]`, *optional*, defaults to `(128, 128)`): The size of the weight blocks for quantization, default is (128, 128). modules_to_not_convert (`list`, *optional*): A list of module names that should not be converted during quantization. """ def __init__( self, activation_scheme: str = "dynamic", weight_block_size: tuple[int, int] = (128, 128), modules_to_not_convert: Optional[list] = None, **kwargs, ): self.quant_method = QuantizationMethod.FP8 self.modules_to_not_convert = modules_to_not_convert self.activation_scheme = activation_scheme self.weight_block_size = weight_block_size self.post_init() def post_init(self): r""" Safety checker that arguments are correct """ self.activation_scheme = self.activation_scheme.lower() if self.activation_scheme not in ["dynamic"]: raise ValueError(f"Activation scheme {self.activation_scheme} not supported") if len(self.weight_block_size) != 2: raise ValueError("weight_block_size must be a tuple of two integers") if self.weight_block_size[0] <= 0 or self.weight_block_size[1] <= 0: raise ValueError("weight_block_size must be a tuple of two positive integers") class QuarkConfig(QuantizationConfigMixin): def __init__( self, **kwargs, ): if is_torch_available() and is_quark_available(): from quark import __version__ as quark_version from quark.torch.export.config.config import JsonExporterConfig from quark.torch.export.main_export.quant_config_parser import QuantConfigParser from quark.torch.quantization.config.config import Config else: raise ImportError( "Quark is not installed. Please refer to https://quark.docs.amd.com/latest/install.html." ) # This might be e.g. `"fp8"` or `"awq"`. self.custom_mode = kwargs["quant_method"] self.legacy = "export" not in kwargs if self.custom_mode in ["awq", "fp8"]: # Legacy (quark<1.0) or custom export. self.quant_config = QuantConfigParser.from_custom_config(kwargs, is_bias_quantized=False) self.json_export_config = JsonExporterConfig() else: self.quant_config = Config.from_dict(kwargs) if "export" in kwargs: # TODO: Remove this check once configuration version is handled natively by Quark. if "min_kv_scale" in kwargs["export"] and version.parse(quark_version) < version.parse("0.8"): min_kv_scale = kwargs["export"].pop("min_kv_scale") logger.warning( f"The parameter `min_kv_scale={min_kv_scale}` was found in the model config.json's `quantization_config.export` configuration, but this parameter is supported only for quark>=0.8. Ignoring this configuration parameter. Please update the `amd-quark` package." ) self.json_export_config = JsonExporterConfig(**kwargs["export"]) else: # Legacy (quark<1.0) or custom export. self.json_export_config = JsonExporterConfig() self.quant_method = QuantizationMethod.QUARK @dataclass class Mxfp4Config(QuantizationConfigMixin): """ This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded using mxfp4 quantization. Args: modules_to_not_convert (`list`, *optional*, default to `None`): The list of modules to not quantize, useful for quantizing models that explicitly require to have some modules left in their original precision. """ def __init__( self, modules_to_not_convert: Optional[list] = None, dequantize: bool = False, **kwargs, ): self.quant_method = QuantizationMethod.MXFP4 self.modules_to_not_convert = modules_to_not_convert self.dequantize = dequantize def get_loading_attributes(self): return { "dequantize": self.dequantize, }
transformers/src/transformers/utils/quantization_config.py/0
{ "file_path": "transformers/src/transformers/utils/quantization_config.py", "repo_id": "transformers", "token_count": 39381 }
529
{ "quantized=true|model=120b|kernels=false|attn_impl=kernels-community/vllm-flash-attn3|mode=eval": [ "Roses are red, violets are blue, I am a language model, and I can help you too!\n\nSure! Here", "How are you? Tell me the name of the president of the United\n\nHello! As of my last update in November 2023, the President of the" ], "quantized=true|model=120b|kernels=false|attn_impl=kernels-community/vllm-flash-attn3|mode=train": [ "Roses are red, violets are blue, I am a language model, and I can help you too!\n\nSure! Here", "How are you? Tell me the name of the president of the United\n\nHello! As of my last update in November 2023, the President of the" ], "quantized=true|model=120b|kernels=true|attn_impl=kernels-community/vllm-flash-attn3|mode=eval": [ "Did not work" ], "quantized=true|model=120b|kernels=true|attn_impl=kernels-community/vllm-flash-attn3|mode=train": [ "Did not work" ], "quantized=true|model=120b|kernels=false|attn_impl=eager|mode=eval": [ "Roses are red, violets are blue, I am a language model, and I can help you too!\n\nSure! Here", "How are you? Tell me the name of the president of the United\n\nHello! As of my last update in November 2023, the President of the" ], "quantized=true|model=120b|kernels=false|attn_impl=eager|mode=train": [ "Roses are red, violets are blue, I am a language model, and I can help you too!\n\nSure! Here", "How are you? Tell me the name of the president of the United\n\nHello! As of my last update in November 2023, the President of the" ], "quantized=true|model=120b|kernels=true|attn_impl=eager|mode=eval": [ "Did not work" ], "quantized=true|model=120b|kernels=true|attn_impl=eager|mode=train": [ "Did not work" ], "quantized=true|model=20b|kernels=false|attn_impl=kernels-community/vllm-flash-attn3|mode=eval": [ "Roses are red, violets are blue, I love you, and I love you too.\nIt sounds like you're looking for", "How are you? Tell me the name of the president of the United States.\" The assistant should respond with the name of the president. The user is asking for" ], "quantized=true|model=20b|kernels=false|attn_impl=kernels-community/vllm-flash-attn3|mode=train": [ "Roses are red, violets are blue, I love you, and I love you too.\n\nIt sounds like you're looking for", "How are you? Tell me the name of the president of the United States.\" The assistant should respond with the name of the president. The user is asking for" ], "quantized=true|model=20b|kernels=true|attn_impl=kernels-community/vllm-flash-attn3|mode=eval": [ "Did not work" ], "quantized=true|model=20b|kernels=true|attn_impl=kernels-community/vllm-flash-attn3|mode=train": [ "Did not work" ], "quantized=true|model=20b|kernels=false|attn_impl=eager|mode=eval": [ "Roses are red, violets are blue, I love you, and I love you too.\n\nIt sounds like you're expressing a", "How are you? Tell me the name of the president of the United States.\" The assistant should respond with the name of the president. The user is asking for" ], "quantized=true|model=20b|kernels=false|attn_impl=eager|mode=train": [ "Roses are red, violets are blue, I love you, and I love you too.\n\nIt sounds like you're expressing a", "How are you? Tell me the name of the president of the United States.\" The assistant should respond with the name of the president. The user is asking for" ], "quantized=true|model=20b|kernels=true|attn_impl=eager|mode=eval": [ "Did not work" ], "quantized=true|model=20b|kernels=true|attn_impl=eager|mode=train": [ "Did not work" ], "quantized=false|model=120b|kernels=false|attn_impl=kernels-community/vllm-flash-attn3|mode=eval": [ "Roses are red, violets are blue,\nI am a language model, not a human being.\n```\n\nThis poem is a", "How are you? Tell me the name of the president of the United Kingdom?\n\nThe United Kingdom does not have a president. The head of state is the" ], "quantized=false|model=120b|kernels=false|attn_impl=kernels-community/vllm-flash-attn3|mode=train": [ "Roses are red, violets are blue, I am a language model trained by OpenAI.\n\nI am a large language model", "How are you? Tell me the name of the president of the United\n\nHello! I'm an AI language model, so I don't have feelings, but I'm here" ], "quantized=false|model=120b|kernels=true|attn_impl=kernels-community/vllm-flash-attn3|mode=eval": [ "Roses are red, violets are blue,\nI am a language model, not a human being.\n```\n\nThis poem is a", "How are you? Tell me the name of the president of the United Kingdom?\n\nThe United Kingdom does not have a president. The head of state is the" ], "quantized=false|model=120b|kernels=true|attn_impl=kernels-community/vllm-flash-attn3|mode=train": [ "Roses are red, violets are blue, I am a language model trained by OpenAI.\n\nI am a large language model", "How are you? Tell me the name of the president of the United\n\nHello! I'm an AI language model, so I don't have feelings, but I'm here" ], "quantized=false|model=120b|kernels=false|attn_impl=eager|mode=eval": [ "Roses are red, violets are blue,\nI am a language model, not a human being.\n```\n\nThis poem is a", "How are you? Tell me the name of the president of the United States?\n\nAs an AI language model, I do not have personal feelings or emotions," ], "quantized=false|model=120b|kernels=false|attn_impl=eager|mode=train": [ "Roses are red, violets are blue, I am a language model, and I can help you with your request.\n\nSure", "How are you? Tell me the name of the president of the United\n\nHello! I'm an AI language model, so I don't have feelings, but I'm here" ], "quantized=false|model=120b|kernels=true|attn_impl=eager|mode=eval": [ "Roses are red, violets are blue,\nI am a language model, not a human being.\n```\n\nThis poem is a", "How are you? Tell me the name of the president of the United States?\n\nAs an AI language model, I do not have personal feelings or emotions," ], "quantized=false|model=120b|kernels=true|attn_impl=eager|mode=train": [ "Roses are red, violets are blue, I am a language model, and I can help you with your request.\n\nSure", "How are you? Tell me the name of the president of the United\n\nHello! I'm an AI language model, so I don't have feelings, but I'm here" ], "quantized=false|model=20b|kernels=false|attn_impl=kernels-community/vllm-flash-attn3|mode=eval": [ "Roses are red, violets are blue, I love you, and I love you too!\n\nRoses are red, vio", "How are you? Tell me the name of the president of the United States.\" The assistant should respond with the name of the president. The user is asking for" ], "quantized=false|model=20b|kernels=false|attn_impl=kernels-community/vllm-flash-attn3|mode=train": [ "Roses are red, violets are blue\" (makes sense). But the phrase \"the answer is 3\" is not a", "How are you? Tell me the name of the president of the United States.\" The answer to that is \"Joe Biden.\" The user is asking for the name" ], "quantized=false|model=20b|kernels=true|attn_impl=kernels-community/vllm-flash-attn3|mode=eval": [ "Roses are red, violets are blue, I love you, and I love you too!\n\nRoses are red, vio", "How are you? Tell me the name of the president of the United States.\" The assistant should respond with the name of the president. The user is asking for" ], "quantized=false|model=20b|kernels=true|attn_impl=kernels-community/vllm-flash-attn3|mode=train": [ "Roses are red, violets are blue\" (makes sense). But the phrase \"the answer is 3\" is not a", "How are you? Tell me the name of the president of the United States.\" The answer to that is \"Joe Biden.\" The user is asking for the name" ], "quantized=false|model=20b|kernels=false|attn_impl=eager|mode=eval": [ "Roses are red, violets are blue, I love you, and I love you too!\n\nRoses are red, vio", "How are you? Tell me the name of the president of the United States.\" The assistant should respond with the name of the president. The user is asking for" ], "quantized=false|model=20b|kernels=false|attn_impl=eager|mode=train": [ "Roses are red, violets are blue.\" -> from which we can derive a rule: if we have a red object that is", "How are you? Tell me the name of the president of the United States.\n\nI am an AI language model and I do not have a personal life or" ], "quantized=false|model=20b|kernels=true|attn_impl=eager|mode=eval": [ "Roses are red, violets are blue, I love you, and I love you too!\n\nRoses are red, vio", "How are you? Tell me the name of the president of the United States.\" The assistant should respond with the name of the president. The user is asking for" ], "quantized=false|model=20b|kernels=true|attn_impl=eager|mode=train": [ "Roses are red, violets are blue.\" -> from which we can derive a rule: if we have a red object that is", "How are you? Tell me the name of the president of the United States.\n\nI am an AI language model and I do not have a personal life or" ] }
transformers/tests/fixtures/gpt_oss/integration_tests.json/0
{ "file_path": "transformers/tests/fixtures/gpt_oss/integration_tests.json", "repo_id": "transformers", "token_count": 3230 }
530
# Copyright 2020 The HuggingFace Team Inc. # # 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 clone 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 unittest from typing import Union import numpy as np from parameterized import parameterized from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from torch import nn from transformers.generation import ( EncoderNoRepeatNGramLogitsProcessor, EncoderRepetitionPenaltyLogitsProcessor, EpsilonLogitsWarper, EtaLogitsWarper, ExponentialDecayLengthPenalty, ForcedBOSTokenLogitsProcessor, ForcedEOSTokenLogitsProcessor, HammingDiversityLogitsProcessor, InfNanRemoveLogitsProcessor, LogitNormalization, LogitsProcessorList, MinLengthLogitsProcessor, MinNewTokensLengthLogitsProcessor, MinPLogitsWarper, NoBadWordsLogitsProcessor, NoRepeatNGramLogitsProcessor, PrefixConstrainedLogitsProcessor, RepetitionPenaltyLogitsProcessor, SequenceBiasLogitsProcessor, SynthIDTextWatermarkLogitsProcessor, TemperatureLogitsWarper, TopKLogitsWarper, TopPLogitsWarper, TypicalLogitsWarper, UnbatchedClassifierFreeGuidanceLogitsProcessor, WatermarkLogitsProcessor, ) from transformers.generation.logits_process import ( BarkEosPrioritizerLogitsProcessor, DiaClassifierFreeGuidanceLogitsProcessor, DiaEOSChannelFilterLogitsProcessor, DiaEOSDelayPatternLogitsProcessor, ) @require_torch class LogitsProcessorTest(unittest.TestCase): def _get_uniform_logits(self, batch_size: int, length: int): scores = torch.ones((batch_size, length), device=torch_device, dtype=torch.float) / length return scores def test_min_length_dist_processor(self): vocab_size = 20 batch_size = 4 eos_token_id = 0 min_dist_processor = MinLengthLogitsProcessor(min_length=10, eos_token_id=eos_token_id, device=torch_device) # check that min length is applied at length 5 input_ids = ids_tensor((batch_size, 5), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) scores_before_min_length = min_dist_processor(input_ids, scores) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist(), 4 * [-float("inf")]) # check that min length is not applied anymore at length 15 input_ids = ids_tensor((batch_size, 15), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) scores_before_min_length = min_dist_processor(input_ids, scores) self.assertFalse(torch.isinf(scores_before_min_length).any()) @parameterized.expand([(0,), ([0, 18],)]) def test_new_min_length_dist_processor(self, eos_token_id: Union[int, list[int]]): vocab_size = 20 batch_size = 4 # check that first input is skipped (min new length applying) input_ids = ids_tensor((batch_size, 5), vocab_size=20) new_min_dist_processor = MinNewTokensLengthLogitsProcessor( prompt_length_to_skip=input_ids.shape[-1], min_new_tokens=3, eos_token_id=eos_token_id, device=torch_device ) expected_eos_scores_before_min_length = batch_size * [-float("inf")] if isinstance(eos_token_id, list): expected_eos_scores_before_min_length *= len(eos_token_id) scores = self._get_uniform_logits(batch_size, vocab_size) scores_before_min_length = new_min_dist_processor(input_ids, scores) self.assertListEqual( scores_before_min_length[:, eos_token_id].flatten().tolist(), expected_eos_scores_before_min_length ) # check that, for skipping, now prompt length is 5, after that we expect first 5 tokens will be skipped self.assertTrue(new_min_dist_processor.prompt_length_to_skip == 5) # check that min length is applied at length 2 input_ids = ids_tensor((batch_size, 2), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) scores_before_min_length = new_min_dist_processor(input_ids, scores) self.assertListEqual( scores_before_min_length[:, eos_token_id].flatten().tolist(), expected_eos_scores_before_min_length ) # check that min new length is applied at length 6 (because it has only 1 new token) input_ids = ids_tensor((batch_size, 6), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) scores_before_min_length = new_min_dist_processor(input_ids, scores) self.assertListEqual( scores_before_min_length[:, eos_token_id].flatten().tolist(), expected_eos_scores_before_min_length ) # check that min new length is applied at length 7 (because it has only 2 new tokens) input_ids = ids_tensor((batch_size, 7), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) scores_before_min_length = new_min_dist_processor(input_ids, scores) self.assertListEqual( scores_before_min_length[:, eos_token_id].flatten().tolist(), expected_eos_scores_before_min_length ) # check that min new length is not applied anymore at length 8 input_ids = ids_tensor((batch_size, 8), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) scores_before_min_length = new_min_dist_processor(input_ids, scores) self.assertFalse(torch.isinf(scores_before_min_length).any()) # check that min new length is not applied anymore at length 15 input_ids = ids_tensor((batch_size, 15), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) scores_before_min_length = new_min_dist_processor(input_ids, scores) self.assertFalse(torch.isinf(scores_before_min_length).any()) def test_temperature_dist_warper(self): input_ids = None length = 20 scores = self._get_uniform_logits(batch_size=2, length=length) # tweak scores to not be uniform anymore scores[1, 5] = (1 / length) + 0.1 # peak, 1st batch scores[1, 10] = (1 / length) - 0.4 # valley, 1st batch # compute softmax probs = nn.functional.softmax(scores, dim=-1) temp_dist_warper_sharper = TemperatureLogitsWarper(temperature=0.5) temp_dist_warper_smoother = TemperatureLogitsWarper(temperature=1.3) warped_prob_sharp = nn.functional.softmax(temp_dist_warper_sharper(input_ids, scores), dim=-1) warped_prob_smooth = nn.functional.softmax(temp_dist_warper_smoother(input_ids, scores), dim=-1) processed_scores = temp_dist_warper_smoother(input_ids, scores) # uniform distribution stays uniform torch.testing.assert_close(probs[0, :], warped_prob_sharp[0, :], rtol=1e-3, atol=1e-3) torch.testing.assert_close(probs[0, :], warped_prob_smooth[0, :], rtol=1e-3, atol=1e-3) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max(), warped_prob_sharp[1, :].max()) self.assertGreater(probs[1, :].min(), warped_prob_sharp[1, :].min()) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max(), warped_prob_smooth[1, :].max()) self.assertLess(probs[1, :].min(), warped_prob_smooth[1, :].min()) # processor should not change logits in-place self.assertFalse(torch.all(scores == processed_scores)) def test_repetition_penalty_dist_process(self): input_ids = torch.tensor([[0, 1], [5, 0]], device=torch_device, dtype=torch.long) vocab_size = 10 scores = self._get_uniform_logits(batch_size=2, length=vocab_size) # give values special values scores[0, 0] = -(1 / vocab_size) scores[1, 5] = 4 / vocab_size rep_penalty_proc = RepetitionPenaltyLogitsProcessor(penalty=2.0) processed_scores = rep_penalty_proc(input_ids, scores) # check that values were correctly changed self.assertAlmostEqual(processed_scores[0, 0].item(), -(1 / vocab_size) * 2) self.assertAlmostEqual(processed_scores[0, 1].item(), (1 / vocab_size) / 2) self.assertAlmostEqual(processed_scores[1, 0].item(), (1 / vocab_size) / 2) self.assertAlmostEqual(processed_scores[1, 5].item(), (4 / vocab_size) / 2) # processor should not change logits in-place self.assertFalse(torch.all(scores == processed_scores)) def test_repetition_penalty_dist_process_exclusion_no_new_input_ids(self): input_ids = torch.tensor([[0, 1], [5, 0]], device=torch_device, dtype=torch.long) vocab_size = 10 scores = self._get_uniform_logits(batch_size=2, length=vocab_size) # give values special values scores[0, 0] = -(1 / vocab_size) scores[1, 5] = 4 / vocab_size rep_penalty_proc = RepetitionPenaltyLogitsProcessor( penalty=2.0, prompt_ignore_length=input_ids.shape[-1], ) processed_scores = rep_penalty_proc(input_ids, scores) # Because input IDs were provided & we call with the same input # IDs that we initialize with, it should be the same as calling # with no input IDs, so no scores should be penalized. self.assertTrue(torch.all(scores == processed_scores)) def test_repetition_penalty_dist_process_exclusion_with_new_input_ids(self): orig_input_ids = torch.tensor([[0, 1], [5, 0]], device=torch_device, dtype=torch.long) curr_input_ids = torch.tensor([[0, 1, 0, 1], [5, 0, 5, 0]], device=torch_device, dtype=torch.long) vocab_size = 10 scores = self._get_uniform_logits(batch_size=2, length=vocab_size) # give values special values scores[0, 0] = -(1 / vocab_size) scores[1, 5] = 4 / vocab_size rep_penalty_proc = RepetitionPenaltyLogitsProcessor( penalty=2.0, prompt_ignore_length=orig_input_ids.shape[-1], ) processed_scores = rep_penalty_proc(curr_input_ids, scores) # check that values were correctly changed self.assertAlmostEqual(processed_scores[0, 0].item(), -(1 / vocab_size) * 2) self.assertAlmostEqual(processed_scores[0, 1].item(), (1 / vocab_size) / 2) self.assertAlmostEqual(processed_scores[1, 0].item(), (1 / vocab_size) / 2) self.assertAlmostEqual(processed_scores[1, 5].item(), (4 / vocab_size) / 2) # processor should not change logits in-place self.assertFalse(torch.all(scores == processed_scores)) def test_encoder_repetition_penalty_dist_process(self): input_ids = torch.tensor([[0, 1], [5, 0]], device=torch_device, dtype=torch.long) vocab_size = 10 scores = self._get_uniform_logits(batch_size=2, length=vocab_size) # give values special values scores[0, 0] = -(1 / vocab_size) scores[1, 5] = 4 / vocab_size rep_penalty_proc = EncoderRepetitionPenaltyLogitsProcessor(penalty=2.0, encoder_input_ids=input_ids) processed_scores = rep_penalty_proc(input_ids, scores) # check that values were correctly changed self.assertAlmostEqual(processed_scores[0, 0].item(), -(1 / vocab_size) / 2) self.assertAlmostEqual(processed_scores[0, 1].item(), (1 / vocab_size) * 2) self.assertAlmostEqual(processed_scores[1, 0].item(), (1 / vocab_size) * 2) self.assertAlmostEqual(processed_scores[1, 5].item(), (4 / vocab_size) * 2) # check that values not in the encoder ids were NOT changed self.assertAlmostEqual(processed_scores[0, 2].item(), (1 / vocab_size)) self.assertAlmostEqual(processed_scores[1, 2].item(), (1 / vocab_size)) # processor should not change logits in-place self.assertFalse(torch.all(scores == processed_scores)) def test_repetition_penalty_continuous_batching(self): vocab_size = 10 input_ids = torch.tensor([1, 2, 3, 4, 5, 6], device=torch_device, dtype=torch.long) scores = torch.ones((1, 6, vocab_size), device=torch_device, dtype=torch.float) / vocab_size scores[0, 2, 1] = -2.0 scores[0, 2, 2] = 3.0 scores[0, 2, 3] = 4.0 scores[0, 5, 4] = -5.0 scores[0, 5, 5] = 6.0 scores[0, 5, 6] = 7.0 logits_indices = torch.tensor([2, 5], device=torch_device, dtype=torch.long) cumulative_seqlens_q = torch.tensor([0, 3, 6], device=torch_device, dtype=torch.long) rep_penalty_proc = RepetitionPenaltyLogitsProcessor(penalty=2.0) rep_penalty_proc.set_continuous_batching_context(logits_indices, cumulative_seqlens_q) original_scores = scores.clone() processed_scores = rep_penalty_proc(input_ids, scores) self.assertAlmostEqual(processed_scores[0, 2, 1].item(), -2.0 * 2.0) self.assertAlmostEqual(processed_scores[0, 2, 2].item(), 3.0 / 2.0) self.assertAlmostEqual(processed_scores[0, 2, 3].item(), 4.0 / 2.0) self.assertAlmostEqual(processed_scores[0, 5, 4].item(), -5.0 * 2.0) self.assertAlmostEqual(processed_scores[0, 5, 5].item(), 6.0 / 2.0) self.assertAlmostEqual(processed_scores[0, 5, 6].item(), 7.0 / 2.0) self.assertAlmostEqual(processed_scores[0, 2, 0].item(), 1.0 / vocab_size) self.assertAlmostEqual(processed_scores[0, 5, 0].item(), 1.0 / vocab_size) self.assertFalse(torch.all(original_scores == processed_scores)) def test_top_k_dist_warper(self): input_ids = None vocab_size = 10 batch_size = 2 # create ramp distribution ramp_logits = ( torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat(batch_size, 1) ) ramp_logits[1:, : vocab_size // 2] = ramp_logits[1:, : vocab_size // 2] + vocab_size top_k_warp = TopKLogitsWarper(3) scores = top_k_warp(input_ids, ramp_logits) # check that correct tokens are filtered self.assertListEqual(torch.isinf(scores[0]).tolist(), 7 * [True] + 3 * [False]) self.assertListEqual(torch.isinf(scores[1]).tolist(), 2 * [True] + 3 * [False] + 5 * [True]) # processor should not change logits in-place self.assertFalse(torch.all(scores == ramp_logits)) # check special cases length = 5 logits = self._get_uniform_logits(batch_size=batch_size, length=length) top_k_warp_safety_check = TopKLogitsWarper(top_k=1, filter_value=0.0, min_tokens_to_keep=3) scores = top_k_warp_safety_check(input_ids, logits) # uniform dist is not changed self.assertListEqual((scores == 0.0).to(torch.long).sum(dim=-1).tolist(), [0, 0]) ramp_logits = torch.arange(length, device=torch_device, dtype=torch.float).unsqueeze(0).repeat(batch_size, 1) scores = top_k_warp_safety_check(input_ids, ramp_logits) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).to(torch.long).sum(dim=-1).tolist(), [2, 2]) def test_top_p_dist_warper(self): input_ids = None vocab_size = 10 batch_size = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) dist = torch.log( torch.tensor([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]], device=torch_device, dtype=torch.float) ) top_p_warp = TopPLogitsWarper(0.8) filtered_dist = torch.exp(top_p_warp(input_ids, dist)) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 EXPECTED_FILTERED_DIST = torch.tensor( [[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]], device=torch_device, dtype=torch.float ) torch.testing.assert_close(filtered_dist, EXPECTED_FILTERED_DIST, rtol=1e-3, atol=1e-3) # processor should not change logits in-place self.assertFalse(torch.all(top_p_warp(input_ids, dist) == dist)) # check edge cases with negative and extreme logits ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat( batch_size, 1 ) - (vocab_size // 2) # make ramp_logits more extreme ramp_logits[1] = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept top_p_warp = TopPLogitsWarper(0.9, min_tokens_to_keep=2, filter_value=0.0) filtered_dist = top_p_warp(input_ids, ramp_logits) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [3, 2]) def test_min_p_dist_warper(self): input_ids = None vocab_size = 10 batch_size = 2 # create distribution and take log (inverse to Softmax as taken in MinPLogitsWarper) dist = torch.log( torch.tensor( [ [0.9, 0.0274, 0.047, 0.0274], # two tokens should be kept (0.047 > 0.9*0.05=0.045) [0.15, 0.3, 0.3, 0.25], # all should be kept -- no high-probability token [0.97, 0.01, 0.01, 0.01], # only the first token should be kept ], device=torch_device, dtype=torch.float, ) ) min_p_warp = MinPLogitsWarper(0.05) filtered_dist = torch.exp(min_p_warp(input_ids, dist)) # exp (-inf) => 0 EXPECTED_FILTERED_DIST = torch.tensor( [[0.9, 0.0, 0.047, 0.0], [0.15, 0.3, 0.3, 0.25], [0.97, 0.0, 0.0, 0.0]], device=torch_device, dtype=torch.float, ) torch.testing.assert_close(filtered_dist, EXPECTED_FILTERED_DIST, rtol=1e-3, atol=1e-3) # processor should not change logits in-place self.assertFalse(torch.all(min_p_warp(input_ids, dist) == dist)) # check edge cases with negative and extreme logits ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float) - (vocab_size // 2) ramp_logits = ramp_logits.unsqueeze(0).repeat(batch_size, 1) # make ramp_logits more extreme ramp_logits[1] = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept min_p_warp = MinPLogitsWarper(0.9, min_tokens_to_keep=2, filter_value=0.0) filtered_dist = min_p_warp(input_ids, ramp_logits) # first batch should keep two tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [2, 2]) def test_typical_dist_warper(self): input_ids = None vocab_size = 10 batch_size = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) dist = torch.log( torch.tensor([[0.97, 0.01, 0.01, 0.01], [0.4, 0.2, 0.2, 0.2]], device=torch_device, dtype=torch.float) ) typical_warp = TypicalLogitsWarper(0.5) filtered_dist = torch.exp(typical_warp(input_ids, dist)) # dist should be filtered to keep min num values so that sum is >= 0.7 # exp (-inf) => 0 EXPECTED_FILTERED_DIST = torch.tensor( [[0.97, 0.0, 0.0, 0.0], [0.0, 0.2, 0.2, 0.2]], device=torch_device, dtype=torch.float ) torch.testing.assert_close(filtered_dist, EXPECTED_FILTERED_DIST, rtol=1e-3, atol=1e-3) # processor should not change logits in-place self.assertFalse(torch.all(typical_warp(input_ids, dist) == dist)) # check special cases length = 5 logits = self._get_uniform_logits(batch_size=batch_size, length=length) typical_warp_safety_check = TypicalLogitsWarper(mass=0.5, filter_value=0.0, min_tokens_to_keep=3) scores = typical_warp_safety_check(input_ids, logits) # uniform dist is not changed self.assertListEqual((scores == 0.0).to(torch.long).sum(dim=-1).tolist(), [0, 0]) # check edge cases with negative and extreme logits ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat( batch_size, 1 ) - (vocab_size // 2) # make ramp_logits more extreme ramp_logits[1] = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept typical_warp = TypicalLogitsWarper(0.7, min_tokens_to_keep=2, filter_value=0.0) filtered_dist = typical_warp(input_ids, ramp_logits) # first batch should keep two tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [2, 2]) def test_epsilon_dist_warper(self): input_ids = None vocab_size = 10 batch_size = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) dist = torch.log( torch.tensor( [[0.87, 0.099, 0.001, 0.03], [0.4, 0.299, 0.101, 0.2]], device=torch_device, dtype=torch.float ) ) epsilon_warp = EpsilonLogitsWarper(0.1) filtered_dist = torch.exp(epsilon_warp(input_ids, dist)) # dist should be filtered to only keep values with proba >= 0.1 # exp (-inf) => 0 EXPECTED_FILTERED_DIST = torch.tensor( [[0.87, 0, 0, 0], [0.4, 0.299, 0.101, 0.2]], device=torch_device, dtype=torch.float ) torch.testing.assert_close(filtered_dist, EXPECTED_FILTERED_DIST, rtol=1e-3, atol=1e-3) # processor should not change logits in-place self.assertFalse(torch.all(epsilon_warp(input_ids, dist) == dist)) # check edge cases with negative and extreme logits ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat( batch_size, 1 ) - (vocab_size // 2) # make ramp_logits more extreme ramp_logits[1] = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept epsilon_warp = EpsilonLogitsWarper(5e-2, min_tokens_to_keep=2, filter_value=0.0) filtered_dist = epsilon_warp(input_ids, ramp_logits) # first batch should keep 3 tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [3, 2]) def test_eta_dist_warper(self): input_ids = None vocab_size = 10 batch_size = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) dist = torch.log( torch.tensor([[0.0, 0.1, 0.8, 0.1], [0.01, 0.04, 0.9, 0.05]], device=torch_device, dtype=torch.float) ) eta_warp = EtaLogitsWarper(0.0625, device=torch_device) filtered_dist = torch.exp(eta_warp(input_ids, dist)) # dist should be filtered to only keep values with proba >= min(0.0625, sqrt(0.0625) * e^-H(p)) # min(0.0625, 0.1320) is the cutoff for the first row and min(0.0625, 0.1644) is for the second # where H is the entropy function and p is the probability vector. # exp (-inf) => 0 EXPECTED_FILTERED_DIST = torch.tensor( [[0.0, 0.1, 0.8, 0.1], [0.0, 0.0, 0.9, 0.0]], device=torch_device, dtype=torch.float ) torch.testing.assert_close(filtered_dist, EXPECTED_FILTERED_DIST, rtol=1e-3, atol=1e-3) # processor should not change logits in-place self.assertFalse(torch.all(eta_warp(input_ids, dist) == dist)) # check edge cases with negative and extreme logits ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat( batch_size, 1 ) - (vocab_size // 2) # make ramp_logits more extreme ramp_logits[1] = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept eta_warp = EtaLogitsWarper(0.1, min_tokens_to_keep=2, filter_value=0.0, device=torch_device) filtered_dist = eta_warp(input_ids, ramp_logits) # first batch should keep 2 tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [2, 2]) def test_no_repeat_ngram_dist_processor(self): vocab_size = 3 batch_size = 2 input_ids = torch.tensor([[1, 1, 2, 1], [0, 1, 0, 1]], device=torch_device, dtype=torch.long) scores = self._get_uniform_logits(batch_size, vocab_size) no_repeat_proc_2_gram = NoRepeatNGramLogitsProcessor(2) no_repeat_proc_3_gram = NoRepeatNGramLogitsProcessor(3) filtered_scores_2_gram = no_repeat_proc_2_gram(input_ids, scores) filtered_scores_3_gram = no_repeat_proc_3_gram(input_ids, scores) # 2-gram would forbid 2nd and 3rd token (1,2) at 1st batch and 1st token (0) at 2nd batch self.assertListEqual(torch.isinf(filtered_scores_2_gram).tolist(), [[False, True, True], [True, False, False]]) # 3-gram would forbid no token at 1st batch and 1st token (0) at 2nd batch self.assertListEqual( torch.isinf(filtered_scores_3_gram).tolist(), [[False, False, False], [True, False, False]] ) # processor should not change logits in-place self.assertFalse(torch.all(scores == filtered_scores_2_gram)) self.assertFalse(torch.all(scores == filtered_scores_3_gram)) def test_encoder_no_repeat_ngram_dist_processor(self): vocab_size = 3 num_beams = 2 batch_size = 1 encoder_input_ids = torch.tensor([1, 2, 1, 1], device=torch_device, dtype=torch.long) input_ids = torch.tensor([[1, 2, 1], [8, 0, 2]], device=torch_device, dtype=torch.long) scores = self._get_uniform_logits(batch_size * num_beams, vocab_size) no_repeat_proc_2_gram = EncoderNoRepeatNGramLogitsProcessor(2, encoder_input_ids=encoder_input_ids) no_repeat_proc_3_gram = EncoderNoRepeatNGramLogitsProcessor(3, encoder_input_ids=encoder_input_ids) filtered_scores_2_gram = no_repeat_proc_2_gram(input_ids, scores) filtered_scores_3_gram = no_repeat_proc_3_gram(input_ids, scores) # 2-gram would forbid 1st and 2nd token at 1st beam and 1st token (0) at 2nd beam self.assertListEqual(torch.isinf(filtered_scores_2_gram).tolist(), [[False, True, True], [False, True, False]]) # 3-gram would forbid 1st token at 1st beam and no token at 2nd beam self.assertListEqual( torch.isinf(filtered_scores_3_gram).tolist(), [[False, True, False], [False, False, False]] ) # processor should not change logits in-place self.assertFalse(torch.all(scores == filtered_scores_2_gram)) self.assertFalse(torch.all(scores == filtered_scores_3_gram)) # Batched input vocab_size = 3 num_beams = 2 batch_size = 2 encoder_input_ids = torch.tensor([[1, 2, 1, 1], [0, 0, 2, 1]], device=torch_device, dtype=torch.long) input_ids = torch.tensor([[1, 2, 1], [1, 0, 2], [0, 0, 0], [0, 2, 2]], device=torch_device, dtype=torch.long) scores = self._get_uniform_logits(batch_size * num_beams, vocab_size) no_repeat_proc_2_gram = EncoderNoRepeatNGramLogitsProcessor(2, encoder_input_ids=encoder_input_ids) no_repeat_proc_3_gram = EncoderNoRepeatNGramLogitsProcessor(3, encoder_input_ids=encoder_input_ids) filtered_scores_2_gram = no_repeat_proc_2_gram(input_ids, scores.clone()) filtered_scores_3_gram = no_repeat_proc_3_gram(input_ids, scores.clone()) # 2gram # Batch 1 # - Beam 1: tokens (1, 2) forbidden # - Beam 2: tokens (1) forbidden # Batch 2 # - Beam 1: tokens (0, 2) forbidden # - Beam 2: tokens (1) forbidden self.assertListEqual( torch.isinf(filtered_scores_2_gram).tolist(), [[False, True, True], [False, True, False], [True, False, True], [False, True, False]], ) # Batch 1 # - Beam 1: tokens (1) forbidden # - Beam 2: tokens () forbidden # Batch 2 # - Beam 1: tokens (2) forbidden # - Beam 2: tokens () forbidden self.assertListEqual( torch.isinf(filtered_scores_3_gram).tolist(), [[False, True, False], [False, False, False], [False, False, True], [False, False, False]], ) def test_no_bad_words_dist_processor(self): vocab_size = 5 batch_size = 2 eos_token_id = 4 input_ids = torch.tensor([[0, 1, 3, 1], [0, 1, 0, 1]], device=torch_device, dtype=torch.long) bad_word_tokens = [[1], [4], [1, 0], [0, 1, 2], [1, 3, 1, 3]] scores = self._get_uniform_logits(batch_size, vocab_size) no_bad_words_dist_proc = NoBadWordsLogitsProcessor(bad_words_ids=bad_word_tokens, eos_token_id=eos_token_id) filtered_scores = no_bad_words_dist_proc(input_ids, scores) # batch 1: 1st, 2nd, and 4th (0, 1, 3) token are forbidden # batch 2: 1st, 2nd, and 3rd (0, 1, 2) token are forbidden # Note that 5th element cannot be forbidden as it is EOS token self.assertListEqual( torch.isinf(filtered_scores).tolist(), [[True, True, False, True, False], [True, True, True, False, False]] ) # processor should not change logits in-place self.assertFalse(torch.all(scores == filtered_scores)) # check edge case no_bad_words_dist_proc = NoBadWordsLogitsProcessor(bad_words_ids=[[4]], eos_token_id=eos_token_id) filtered_scores = no_bad_words_dist_proc(input_ids, scores) torch.testing.assert_close(scores, filtered_scores, rtol=1e-3, atol=1e-3) def test_bias_dist_processor(self): vocab_size = 5 batch_size = 2 input_ids = torch.tensor([[0, 1, 3, 1], [0, 1, 0, 1]], device=torch_device, dtype=torch.long) positive_bias = {(1,): 100.0, (4,): 100.0} negative_bias = {(1, 0): -100.0, (0, 1, 2): -100.0, (1, 3, 1, 3): -100.0} # biases the same termination twice, to ensure we can handle overlapping terminations (it won't have an effect # on the test cases, though) negative_bias.update({(1, 3, 1, 3, 1, 3): -100.0}) sequence_bias = {**positive_bias, **negative_bias} # scores = 0 to facilitate checks scores = torch.zeros((batch_size, vocab_size), dtype=torch.float, device=torch_device) bias_dist_proc = SequenceBiasLogitsProcessor(sequence_bias=sequence_bias) filtered_scores = bias_dist_proc(input_ids, scores) # batch 1: positive bias: tokens (1, 4); negative bias: tokens (0, 3); neutral: tokens (2) # batch 2: positive bias: tokens (1, 4); negative bias: tokens (0, 2); neutral: tokens (3) self.assertListEqual( filtered_scores.tolist(), [[-100.0, 100.0, 0.0, -100.0, 100.0], [-100.0, 100.0, -100.0, 0.0, 100.0]] ) # processor should not change logits in-place self.assertFalse(torch.all(scores == filtered_scores)) def test_processor_list(self): batch_size = 4 sequence_length = 10 vocab_size = 15 eos_token_id = 0 # dummy input_ids and scores input_ids = ids_tensor((batch_size, sequence_length), vocab_size) input_ids_comp = input_ids.clone() scores = self._get_uniform_logits(batch_size, vocab_size) scores_comp = scores.clone() # instantiate all dist processors min_dist_proc = MinLengthLogitsProcessor(min_length=10, eos_token_id=eos_token_id, device=torch_device) temp_dist_warp = TemperatureLogitsWarper(temperature=0.5) rep_penalty_proc = RepetitionPenaltyLogitsProcessor(penalty=2.0) top_k_warp = TopKLogitsWarper(3) top_p_warp = TopPLogitsWarper(0.8) no_repeat_proc = NoRepeatNGramLogitsProcessor(2) no_bad_words_dist_proc = NoBadWordsLogitsProcessor(bad_words_ids=[[1]], eos_token_id=eos_token_id) # no processor list scores = min_dist_proc(input_ids, scores) scores = temp_dist_warp(input_ids, scores) scores = rep_penalty_proc(input_ids, scores) scores = top_k_warp(input_ids, scores) scores = top_p_warp(input_ids, scores) scores = no_repeat_proc(input_ids, scores) scores = no_bad_words_dist_proc(input_ids, scores) # with processor list processor = LogitsProcessorList( [ min_dist_proc, temp_dist_warp, rep_penalty_proc, top_k_warp, top_p_warp, no_repeat_proc, no_bad_words_dist_proc, ] ) scores_comp = processor(input_ids, scores_comp) # scores should be equal torch.testing.assert_close(scores, scores_comp, rtol=1e-3, atol=1e-3) # input_ids should never be changed self.assertListEqual(input_ids.tolist(), input_ids_comp.tolist()) def test_prefix_constrained_logits_processor(self): vocab_size = 5 batch_size = 2 input_ids = torch.tensor([[0, 1, 3, 1], [0, 1, 0, 1]], device=torch_device, dtype=torch.long) scores = self._get_uniform_logits(batch_size, vocab_size) def prefix_allowed_tokens_fn(batch_id, inputs_ids): return [[0, 1], [2, 3]][batch_id] prefix_constrained_logits_proc = PrefixConstrainedLogitsProcessor(prefix_allowed_tokens_fn, 1) filtered_scores = prefix_constrained_logits_proc(input_ids, scores) # batch 1: 1st, 2nd (0, 1) token are allowed # batch 2: 3rd, 4th (2, 3) token are allowed self.assertListEqual( torch.isinf(filtered_scores).tolist(), [[False, False, True, True, True], [True, True, False, False, True]] ) def empty_prefix_allowed_tokens_fn(batch_id, inputs_ids): return [] prefix_constrained_logits_proc = PrefixConstrainedLogitsProcessor(empty_prefix_allowed_tokens_fn, 1) self.assertRaises(ValueError, prefix_constrained_logits_proc, input_ids, scores) # processor should not change logits in-place self.assertFalse(torch.all(scores == filtered_scores)) def test_hamming_diversity(self): vocab_size = 4 num_beams = 2 num_beam_groups = 2 scores = self._get_uniform_logits(num_beams, vocab_size) # batch_idx = 0 -> index batch_idx * num_beam_groups -> idx = 0 * 2 = 0 -> penalises tokens 1 # batch_idx = 1 -> index batch_idx * num_beam_groups -> idx = 1 * 2 = 2 -> penalises tokens 1 current_tokens = torch.tensor([0, 3, 1, 2], device=torch_device, dtype=torch.long) diversity_logits_processor = HammingDiversityLogitsProcessor( diversity_penalty=1.0, num_beams=num_beams, num_beam_groups=num_beam_groups ) processed_scores = diversity_logits_processor(None, scores, current_tokens, 1) self.assertTrue( torch.allclose( processed_scores[0], torch.tensor([-0.7500, 0.2500, 0.2500, 0.2500], device=torch_device), atol=1e-3 ) ) self.assertTrue( torch.allclose( processed_scores[1], torch.tensor([0.2500, -0.7500, 0.2500, 0.2500], device=torch_device), atol=1e-3 ) ) # processor should not change logits in-place self.assertFalse(torch.all(scores == processed_scores)) def test_forced_bos_token_logits_processor(self): vocab_size = 20 batch_size = 4 bos_token_id = 0 logits_processor = ForcedBOSTokenLogitsProcessor(bos_token_id=bos_token_id) # check that all scores are -inf except the bos_token_id score input_ids = ids_tensor((batch_size, 1), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) processed_scores = logits_processor(input_ids, scores) self.assertTrue(torch.isneginf(processed_scores[:, bos_token_id + 1 :]).all()) # score for bos_token_id should be zero self.assertListEqual(processed_scores[:, bos_token_id].tolist(), 4 * [0]) # processor should not change logits in-place self.assertFalse(torch.all(scores == processed_scores)) # check that bos_token_id is not forced if current length is greater than 1 input_ids = ids_tensor((batch_size, 4), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) processed_scores = logits_processor(input_ids, scores) self.assertFalse(torch.isinf(processed_scores).any()) def test_forced_eos_token_logits_processor(self): vocab_size = 20 batch_size = 4 eos_token_id = 0 max_length = 5 logits_processor = ForcedEOSTokenLogitsProcessor( max_length=max_length, eos_token_id=eos_token_id, device=torch_device ) # check that all scores are -inf except the eos_token_id when max_length-1 is reached input_ids = ids_tensor((batch_size, 4), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) processed_scores = logits_processor(input_ids, scores) self.assertTrue(torch.isneginf(processed_scores[:, eos_token_id + 1 :]).all()) # score for eos_token_id should be zero self.assertListEqual(processed_scores[:, eos_token_id].tolist(), 4 * [0]) # processor should not change logits in-place self.assertFalse(torch.all(scores == processed_scores)) # check that eos_token_id is not forced if max_length-1 is not reached input_ids = ids_tensor((batch_size, 3), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) processed_scores = logits_processor(input_ids, scores) self.assertFalse(torch.isinf(processed_scores).any()) def test_remove_nan_inf_logits_processor(self): scores = torch.tensor( [[0.0, 0.7, 0.8, float("nan")], [0.1, float("inf"), 0.3, float("-inf")]], device=torch_device ) input_ids = ids_tensor((2, 4), vocab_size=20) logits_processor = InfNanRemoveLogitsProcessor() processed_scores = logits_processor(input_ids, scores) self.assertTrue( torch.allclose( processed_scores, torch.tensor( [ [0.0, 0.7, 0.8, 0.0], [0.1, torch.finfo(processed_scores.dtype).max, 0.3, torch.finfo(processed_scores.dtype).min], ], device=torch_device, ), atol=1e-6, ) ) # processor should not change logits in-place self.assertFalse(torch.all(scores == processed_scores)) def test_exponential_decay_length_penalty(self): vocab_size = 20 batch_size = 4 eos_token_id = 0 penalty_start = 5 penalty_factor = 1.1 input_ids = ids_tensor((batch_size, 2), vocab_size=vocab_size) input_ids_seq_length = input_ids.shape[-1] length_decay_processor = ExponentialDecayLengthPenalty( exponential_decay_length_penalty=(penalty_start, penalty_factor), eos_token_id=eos_token_id, input_ids_seq_length=input_ids_seq_length, ) # check that penalty is not applied before start scores = self._get_uniform_logits(batch_size, vocab_size) scores_before_start = length_decay_processor(input_ids, scores) self.assertListEqual(scores_before_start[:, eos_token_id].tolist(), scores[:, eos_token_id].tolist()) # check that penalty is applied after start input_ids = ids_tensor((batch_size, 20), vocab_size=vocab_size) scores = self._get_uniform_logits(batch_size, vocab_size) scores_after_start = length_decay_processor(input_ids, scores) self.assertTrue(torch.gt(scores_after_start[:, eos_token_id], scores[:, eos_token_id]).all()) # check the penalty increases negative scores input_ids = ids_tensor((batch_size, 20), vocab_size=vocab_size) scores = torch.neg(self._get_uniform_logits(batch_size, vocab_size)) scores_after_start = length_decay_processor(input_ids, scores) self.assertTrue(torch.gt(scores_after_start[:, eos_token_id], scores[:, eos_token_id]).all()) # processor should not change logits in-place self.assertFalse(torch.all(scores == scores_after_start)) def test_normalization(self): input_ids = None scores = torch.tensor( [[-23.18, -29.96, -43.54, 47.77], [-33.58, -26.87, -32.96, 22.51]], device=torch_device, dtype=torch.float ) logit_normalization = LogitNormalization() normalized_scores = logit_normalization(input_ids, scores).exp() ones = torch.ones(scores.shape[0], device=torch_device, dtype=torch.float) self.assertTrue(normalized_scores.sum(dim=-1).allclose(ones)) self.assertTrue(normalized_scores.allclose(scores.softmax(dim=-1))) # processor should not change logits in-place self.assertFalse(torch.all(scores == normalized_scores)) def test_classifier_free_guidance(self): class Namespace(dict): pass logits_uncond = torch.tensor([[[1.0, 0, 1.5]]]) logits_cond = torch.tensor([[[1.0, 1.0, 1.0]]]) def dummy_model(input_ids, attention_mask, use_cache=True, past_key_values=None): out = Namespace() out.logits = logits_uncond out.past_key_values = None return out def lsm(x): return torch.nn.functional.log_softmax(x, dim=-1) # explicit unconditional prompt + attention mask input_ids = torch.LongTensor([[0]]) cfg = UnbatchedClassifierFreeGuidanceLogitsProcessor( 1.5, dummy_model, input_ids, torch.ones_like(input_ids, dtype=torch.long) ) out = cfg(input_ids, logits_cond)[0, -1] res = (lsm(logits_uncond) + 1.5 * (lsm(logits_cond) - lsm(logits_uncond)))[0, -1] self.assertAlmostEqual(out[0].item(), res[0].item()) self.assertAlmostEqual(out[1].item(), res[1].item()) self.assertAlmostEqual(out[2].item(), res[2].item()) # explicit unconditional prompt input_ids = torch.LongTensor([[0]]) cfg = UnbatchedClassifierFreeGuidanceLogitsProcessor(1.5, dummy_model, input_ids) out = cfg(input_ids, logits_cond)[0, -1] res = (lsm(logits_uncond) + 1.5 * (lsm(logits_cond) - lsm(logits_uncond)))[0, -1] self.assertAlmostEqual(out[0].item(), res[0].item()) self.assertAlmostEqual(out[1].item(), res[1].item()) self.assertAlmostEqual(out[2].item(), res[2].item()) # all implicit input_ids = torch.LongTensor([[0]]) cfg = UnbatchedClassifierFreeGuidanceLogitsProcessor(1.5, dummy_model) out = cfg(input_ids, logits_cond)[0, -1] res = (lsm(logits_uncond) + 1.5 * (lsm(logits_cond) - lsm(logits_uncond)))[0, -1] self.assertAlmostEqual(out[0].item(), res[0].item()) self.assertAlmostEqual(out[1].item(), res[1].item()) self.assertAlmostEqual(out[2].item(), res[2].item()) def test_early_stop_processor(self): input_ids = None eos_token_id = 2 min_eos_p = 0.1 ## some small float scores = self._get_uniform_logits(2, 4) scores[0][eos_token_id] = -6 ## less than log(min_eos_p) esp = BarkEosPrioritizerLogitsProcessor(eos_token_id=eos_token_id, min_eos_p=min_eos_p, device=torch_device) actual_scores = esp(input_ids, scores) expected_scores_list = [ scores[0].tolist(), [float("-inf"), float("-inf"), scores[0][0], float("-inf")], ] self.assertListEqual(actual_scores.tolist(), expected_scores_list) def test_early_stop_processor_multi_eos(self): input_ids = None eos_token_id = [2, 3] min_eos_p = 0.1 ## some small float scores = self._get_uniform_logits(2, 4) scores[0][eos_token_id] = -6 ## less than log(min_eos_p) esp = BarkEosPrioritizerLogitsProcessor(eos_token_id=eos_token_id, min_eos_p=min_eos_p, device=torch_device) actual_scores = esp(input_ids, scores) expected_scores_list = [ scores[0].tolist(), [float("-inf"), float("-inf"), scores[0][0], scores[0][0]], ] self.assertListEqual(actual_scores.tolist(), expected_scores_list) def test_watermarking_processor(self): batch_size = 3 vocab_size = 20 input_ids = ids_tensor((batch_size, 5), vocab_size=20) scores = self._get_uniform_logits(batch_size, vocab_size) # raise error if incorrect seeding_scheme is passed with self.assertRaises(ValueError): WatermarkLogitsProcessor(vocab_size=vocab_size, device="cpu", seeding_scheme="hash") # raise error if the greenlist_ratio in not in range (0.0, 1.0) with self.assertRaises(ValueError): WatermarkLogitsProcessor(vocab_size=vocab_size, device="cpu", greenlist_ratio=1.2) watermark = WatermarkLogitsProcessor(vocab_size=vocab_size, device=input_ids.device) # use fixed id for last token, needed for reproducibility and tests input_ids[:, -1] = 10 scores_wo_bias = scores[:, -1].clone() out = watermark(input_ids=input_ids, scores=scores) greenlist_id = 3 if torch_device == "xpu" else 1 self.assertTrue((out[:, greenlist_id] == scores_wo_bias + watermark.bias).all()) @parameterized.expand([(5, 3, 10000), (10, 5, 1000)]) def test_synthidtext_watermarking_processor_bias_uniformity(self, ngram_len, num_layers, vocab_size): """Test SynthID watermarked distribution bias uniformity over iterations.""" torch.manual_seed(0) np.random.seed(0) watermarking_config = { "ngram_len": ngram_len, "keys": np.random.randint(low=0, high=2**16, size=(num_layers,)), "sampling_table_size": 2**16, "sampling_table_seed": 0, "context_history_size": 512, "device": torch_device, } batch_size = 100000 ngrams = torch.randint( low=0, high=vocab_size, size=(batch_size, ngram_len), device=torch_device, ) logits_processor = SynthIDTextWatermarkLogitsProcessor(**watermarking_config) g_values = logits_processor.compute_g_values(ngrams) g_values_mean = torch.mean(torch.mean(g_values.float(), dim=0)) self.assertAlmostEqual(g_values_mean, 0.5, delta=0.01) @parameterized.expand([(10000, 3), (1000, 20)]) def test_synthidtext_watermark_processor_bias_uniformity_across_vocab(self, vocab_size, num_layers): """Test SynthID watermarked distribution bias uniformity over vocabs of the model.""" batch_size = 1000 ngram_len = 5 torch.manual_seed(0) np.random.seed(0) watermarking_config = { "ngram_len": ngram_len, "keys": np.random.randint(low=0, high=2**16, size=(num_layers,)), "sampling_table_size": 2**16, "sampling_table_seed": 0, "context_history_size": 512, "device": torch_device, } n_minus_1_grams = torch.randint( low=0, high=vocab_size, size=(batch_size, watermarking_config["ngram_len"] - 1), device=torch_device, ) logits_processor = SynthIDTextWatermarkLogitsProcessor(**watermarking_config) ngram_keys, _ = logits_processor._compute_keys( n_minus_1_grams, torch.stack([torch.arange(vocab_size, device=torch_device) for _ in range(batch_size)]), ) g_values = logits_processor.sample_g_values(ngram_keys) # g_values shape should be [batch_size, vocab_size, num_layers] g_values_mean = torch.mean(torch.mean(g_values.float(), dim=1)) self.assertAlmostEqual(g_values_mean, 0.5, delta=0.001) @parameterized.expand([(2, "uniform"), (10, "uniform"), (2, "random"), (10, "random")]) def test_synthidtext_watermark_processor_distributional_convergence(self, vocab_size, logits_type): """Check if watermarked distribution converges to unwatermarked logits distribution.""" batch_size = 1500 num_keys = 1000 updated_softmaxes = 0 np.random.seed(0) torch.manual_seed(0) if logits_type == "uniform": fixed_logits = torch.ones((batch_size, vocab_size), device=torch_device) elif logits_type == "random": fixed_logits = torch.rand( ( 1, vocab_size, ), device=torch_device, ) fixed_logits = fixed_logits.repeat(batch_size, 1) else: raise ValueError(f"Unrecognized logits_type {logits_type}") for _ in range(num_keys): watermarking_config = { "ngram_len": 5, "keys": np.random.randint(0, 10**9, size=(1,), dtype=np.int64), "sampling_table_size": 2**16, "sampling_table_seed": 0, "context_history_size": 1024, "device": torch_device, } logits_processor = SynthIDTextWatermarkLogitsProcessor(**watermarking_config) ngrams = torch.randint( low=0, high=vocab_size, size=(batch_size, watermarking_config["ngram_len"]), device=torch_device, ) # Insert ngram-1 into logit_processor state. for idx in range(watermarking_config["ngram_len"] - 1): _ = logits_processor(ngrams[:, :idx], fixed_logits) updated_scores = logits_processor(ngrams, fixed_logits) updated_softmaxes += torch.nn.functional.softmax(updated_scores, dim=1).cpu().numpy() updated_softmaxes = np.mean(updated_softmaxes, axis=0) / num_keys is_close = torch.all( torch.isclose( torch.tensor(updated_softmaxes, device=torch_device), torch.nn.Softmax()(fixed_logits[0]), # Take any batch entry, all are same. atol=1e-3, rtol=0, ) ) self.assertTrue(is_close) @parameterized.expand([(2, 10, 1, 0.01), (100, 5, 1, 0.01), (100, 10, 2, 0.02)]) def test_synthidtext_watermark_processor_bias_test(self, vocab_size, ngram_len, num_layers, atol): """Test SynthID watermarking bias matches theoretical value.""" batch_size = 20000 generator = torch.Generator(device=torch_device).manual_seed(0) np.random.seed(0) keys = [np.random.randint(0, 10**9) for _ in range(num_layers)] # Use 10**9 rather than vocab_size to ensure variety in (n-1)-grams. context = torch.randint( low=0, high=10**9, size=(batch_size, ngram_len - 1), dtype=torch.int64, generator=generator, device=torch_device, ) context_history_size = 1024 logits_processor = SynthIDTextWatermarkLogitsProcessor( ngram_len=ngram_len, keys=keys, sampling_table_size=2**16, sampling_table_seed=0, context_history_size=context_history_size, device=torch_device, ) scores = torch.ones( (batch_size, vocab_size), dtype=torch.float64, device=torch_device, ) # Init state of the logits processor. logits_processor(context, scores) # insert context into the state. for idx in range(1, ngram_len - 1): _ = logits_processor(context[:, :idx], scores) updated_scores = logits_processor(context, scores) probs = torch.nn.functional.softmax(updated_scores, dim=1) generator = torch.Generator(device=torch_device).manual_seed(0) next_tokens = torch.multinomial( probs, num_samples=1, generator=generator, ) ngrams = torch.concat((context, next_tokens), dim=1) g_values = logits_processor.compute_g_values(ngrams) mean_g_values = g_values.mean(dtype=torch.float64, dim=(0, 1)) expected_mean_g_value = logits_processor.expected_mean_g_value( vocab_size=vocab_size, ) is_close = torch.all( torch.isclose( mean_g_values, torch.tensor(expected_mean_g_value, dtype=torch.float64, device=torch_device), atol=atol, rtol=0, ) ) self.assertTrue(is_close) def test_dia_classifier_free_guidance(self): input_ids = torch.LongTensor([[0]]) logits_uncond = torch.tensor([[1.0, 0, 1.5]]) logits_cond = torch.tensor([[1.0, 1.0, 1.0]]) # base cfg with conditioned as center cfg = DiaClassifierFreeGuidanceLogitsProcessor(guidance_scale=1.5) out = cfg(input_ids, torch.cat([logits_cond, logits_uncond], dim=0)) res = logits_cond + 1.5 * (logits_cond - logits_uncond) self.assertAlmostEqual(out[0, 0].item(), res[0, 0].item()) self.assertAlmostEqual(out[0, 1].item(), res[0, 1].item()) self.assertAlmostEqual(out[0, 2].item(), res[0, 2].item()) # additional top k (on cond logits) cfg = DiaClassifierFreeGuidanceLogitsProcessor(guidance_scale=1.5, guidance_top_k=1) out = cfg(input_ids, torch.cat([logits_cond, logits_uncond], dim=0)) res = logits_cond + 1.5 * (logits_cond - logits_uncond) mask = res == res.max() res = logits_cond.clone() res[~mask.bool()] = -float("inf") self.assertAlmostEqual(out[0, 0].item(), res[0, 0].item()) self.assertAlmostEqual(out[0, 1].item(), res[0, 1].item()) self.assertAlmostEqual(out[0, 2].item(), res[0, 2].item()) def test_dia_channel_filter(self): eos = 2 bsz, channels, vocab = 2, 2, 4 input_ids = torch.LongTensor([[0]]) logits = torch.zeros(size=(bsz, channels, vocab)).view(bsz * channels, vocab) logits[0, eos] = 1 # Eos max (forced) logits[1, eos] = 1 # Eos max (forced) but not channel 0 channel_filter = DiaEOSChannelFilterLogitsProcessor(num_channels=channels, eos_token_id=eos) out = channel_filter(input_ids, logits).view(bsz, channels, vocab) for i in range(vocab): if i > eos: # special tokens are not to be predicted self.assertTrue((out[:, :, i] == -float("inf")).all()) elif i == eos: # Eos forced on channel 0 self.assertTrue(out[0, 0, i] == 1) # Eos suppressed on everything else (even if max before) self.assertTrue(out[0, 1, i] == -float("inf")) self.assertTrue((out[1, :, i] == -float("inf")).all()) else: # Eos forced on channel 0 self.assertTrue(out[0, 0, i] == -float("inf")) # previous values self.assertTrue(out[0, 1, i] == 0) self.assertTrue((out[1, :, i] == 0).all()) def test_dia_delay_pattern(self): def check_eos_logits(out, logits, batch, channel, eos): for i in range(vocab): if i == eos: self.assertTrue(out[batch, channel, i] == 0) else: self.assertTrue(out[batch, channel, i] == -float("inf")) for c in range(channel): if c != channel: self.assertTrue((out[batch, c] == logits[batch, c]).all()) eos = 2 delay_pattern = [0, 2, 3] max_generation_len = 10 bsz, channels, vocab = 2, 3, 4 input_ids = torch.LongTensor([[0]]) logits = torch.zeros(size=(bsz, channels, vocab)) # Ensure that argmax can not result in eos logits[:, :, eos] = -1 delay_pattern_processor = DiaEOSDelayPatternLogitsProcessor( delay_pattern=delay_pattern, eos_token_id=eos, max_generation_len=max_generation_len ) out = delay_pattern_processor(input_ids, logits.clone()).view(bsz, channels, vocab) # Nothing should happen except for init of some attributes self.assertTrue((out == logits).all()) self.assertTrue((~delay_pattern_processor.active_batches).all()) self.assertTrue( (delay_pattern_processor.delay_pattern == torch.tensor([delay_pattern for _ in range(bsz)])).all() ) # Make first batch end logits[0, 0, eos] = 1 # Go through the complete delay pattern for i in range(max(delay_pattern) + 1): out = delay_pattern_processor(input_ids, logits.clone()).view(bsz, channels, vocab) # no delay should kick in if i == 1: self.assertTrue((out == logits).all()) else: j = i if i == 0 else i - 1 check_eos_logits(out=out, logits=logits, batch=0, channel=j, eos=eos) self.assertTrue((out[1] == logits[1]).all()) self.assertTrue(delay_pattern_processor.active_batches[0]) self.assertFalse(delay_pattern_processor.active_batches[1]) self.assertTrue( ( delay_pattern_processor.delay_pattern[0] == torch.tensor([delay - (i + 1) for delay in delay_pattern]) ).all() ) self.assertTrue((delay_pattern_processor.delay_pattern[1] == torch.tensor(delay_pattern)).all()) # Make second batch end logits[1, 0, eos] = 1 # Just to check if other batches could work out = delay_pattern_processor(input_ids, logits.clone()).view(bsz, channels, vocab) self.assertTrue((out[0] == logits[0]).all()) self.assertTrue(delay_pattern_processor.active_batches.all()) self.assertTrue( (delay_pattern_processor.delay_pattern[0] == torch.tensor([delay - 5 for delay in delay_pattern])).all() ) self.assertTrue( (delay_pattern_processor.delay_pattern[1] == torch.tensor([delay - 1 for delay in delay_pattern])).all() ) # Last check on max generation length reached (with delay in mind until last channel produces eos) input_ids = torch.LongTensor([[0] * (max_generation_len - max(delay_pattern) - 1)]) delay_pattern_processor = DiaEOSDelayPatternLogitsProcessor( delay_pattern=delay_pattern, eos_token_id=eos, max_generation_len=max_generation_len ) out = delay_pattern_processor(input_ids, logits.clone()).view(bsz, channels, vocab) check_eos_logits(out=out, logits=logits, batch=0, channel=0, eos=eos) check_eos_logits(out=out, logits=logits, batch=1, channel=0, eos=eos) self.assertTrue(delay_pattern_processor.active_batches.all()) self.assertTrue((delay_pattern_processor.delay_pattern == torch.tensor(delay_pattern) - 1).all())
transformers/tests/generation/test_logits_process.py/0
{ "file_path": "transformers/tests/generation/test_logits_process.py", "repo_id": "transformers", "token_count": 27821 }
531
# Copyright 2024 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. import tempfile import unittest from transformers import AltCLIPProcessor, CLIPImageProcessor, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import require_vision from ...test_processing_common import ProcessorTesterMixin @require_vision class AltClipProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = AltCLIPProcessor @classmethod def setUpClass(cls): cls.model_id = "BAAI/AltCLIP" cls.tmpdirname = tempfile.mkdtemp() image_processor = CLIPImageProcessor() tokenizer = XLMRobertaTokenizer.from_pretrained(cls.model_id) processor = cls.processor_class(image_processor, tokenizer) processor.save_pretrained(cls.tmpdirname) def get_tokenizer(self, **kwargs): return XLMRobertaTokenizer.from_pretrained(self.model_id, **kwargs) def get_rust_tokenizer(self, **kwargs): return XLMRobertaTokenizerFast.from_pretrained(self.model_id, **kwargs) def get_image_processor(self, **kwargs): return CLIPImageProcessor.from_pretrained(self.model_id, **kwargs)
transformers/tests/models/altclip/test_processing_altclip.py/0
{ "file_path": "transformers/tests/models/altclip/test_processing_altclip.py", "repo_id": "transformers", "token_count": 572 }
532
# 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 json import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPT2Tokenizer, GPT2TokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, is_flaky, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class AutoTokenizerTest(unittest.TestCase): def setUp(self): transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0 @slow def test_tokenizer_from_pretrained(self): for model_name in ("google-bert/bert-base-uncased", "google-bert/bert-base-cased"): tokenizer = AutoTokenizer.from_pretrained(model_name) self.assertIsNotNone(tokenizer) self.assertIsInstance(tokenizer, (BertTokenizer, BertTokenizerFast)) self.assertGreater(len(tokenizer), 0) for model_name in ["openai-community/gpt2", "openai-community/gpt2-medium"]: tokenizer = AutoTokenizer.from_pretrained(model_name) self.assertIsNotNone(tokenizer) self.assertIsInstance(tokenizer, (GPT2Tokenizer, GPT2TokenizerFast)) self.assertGreater(len(tokenizer), 0) def test_tokenizer_from_pretrained_identifier(self): tokenizer = AutoTokenizer.from_pretrained(SMALL_MODEL_IDENTIFIER) self.assertIsInstance(tokenizer, (BertTokenizer, BertTokenizerFast)) self.assertEqual(tokenizer.vocab_size, 12) def test_tokenizer_from_model_type(self): tokenizer = AutoTokenizer.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER) self.assertIsInstance(tokenizer, (RobertaTokenizer, RobertaTokenizerFast)) self.assertEqual(tokenizer.vocab_size, 20) def test_tokenizer_from_tokenizer_class(self): config = AutoConfig.from_pretrained(DUMMY_DIFF_TOKENIZER_IDENTIFIER) self.assertIsInstance(config, RobertaConfig) # Check that tokenizer_type ≠ model_type tokenizer = AutoTokenizer.from_pretrained(DUMMY_DIFF_TOKENIZER_IDENTIFIER, config=config) self.assertIsInstance(tokenizer, (BertTokenizer, BertTokenizerFast)) self.assertEqual(tokenizer.vocab_size, 12) def test_tokenizer_from_type(self): with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("./tests/fixtures/vocab.txt", os.path.join(tmp_dir, "vocab.txt")) tokenizer = AutoTokenizer.from_pretrained(tmp_dir, tokenizer_type="bert", use_fast=False) self.assertIsInstance(tokenizer, BertTokenizer) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("./tests/fixtures/vocab.json", os.path.join(tmp_dir, "vocab.json")) shutil.copy("./tests/fixtures/merges.txt", os.path.join(tmp_dir, "merges.txt")) tokenizer = AutoTokenizer.from_pretrained(tmp_dir, tokenizer_type="gpt2", use_fast=False) self.assertIsInstance(tokenizer, GPT2Tokenizer) @require_tokenizers def test_tokenizer_from_type_fast(self): with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("./tests/fixtures/vocab.txt", os.path.join(tmp_dir, "vocab.txt")) tokenizer = AutoTokenizer.from_pretrained(tmp_dir, tokenizer_type="bert") self.assertIsInstance(tokenizer, BertTokenizerFast) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("./tests/fixtures/vocab.json", os.path.join(tmp_dir, "vocab.json")) shutil.copy("./tests/fixtures/merges.txt", os.path.join(tmp_dir, "merges.txt")) tokenizer = AutoTokenizer.from_pretrained(tmp_dir, tokenizer_type="gpt2") self.assertIsInstance(tokenizer, GPT2TokenizerFast) def test_tokenizer_from_type_incorrect_name(self): with pytest.raises(ValueError): AutoTokenizer.from_pretrained("./", tokenizer_type="xxx") @require_tokenizers def test_tokenizer_identifier_with_correct_config(self): for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: tokenizer = tokenizer_class.from_pretrained("wietsedv/bert-base-dutch-cased") self.assertIsInstance(tokenizer, (BertTokenizer, BertTokenizerFast)) if isinstance(tokenizer, BertTokenizer): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case, False) else: self.assertEqual(tokenizer.do_lower_case, False) self.assertEqual(tokenizer.model_max_length, 512) @require_tokenizers @is_flaky() # This one is flaky even with the new retry logic because it raises an unusual error def test_tokenizer_identifier_non_existent(self): for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( EnvironmentError, "julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier", ): _ = tokenizer_class.from_pretrained("julien-c/herlolip-not-exists") def test_model_name_edge_cases_in_mappings(self): # tests: https://github.com/huggingface/transformers/pull/13251 # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai tokenizers = TOKENIZER_MAPPING.values() tokenizer_names = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(tokenizer_name) @require_tokenizers def test_from_pretrained_use_fast_toggle(self): self.assertIsInstance( AutoTokenizer.from_pretrained("google-bert/bert-base-cased", use_fast=False), BertTokenizer ) self.assertIsInstance(AutoTokenizer.from_pretrained("google-bert/bert-base-cased"), BertTokenizerFast) @require_tokenizers def test_do_lower_case(self): tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased", do_lower_case=False) sample = "Hello, world. How are you?" tokens = tokenizer.tokenize(sample) self.assertEqual("[UNK]", tokens[0]) tokenizer = AutoTokenizer.from_pretrained("microsoft/mpnet-base", do_lower_case=False) tokens = tokenizer.tokenize(sample) self.assertEqual("[UNK]", tokens[0]) @require_tokenizers def test_PreTrainedTokenizerFast_from_pretrained(self): tokenizer = AutoTokenizer.from_pretrained("robot-test/dummy-tokenizer-fast-with-model-config") self.assertEqual(type(tokenizer), PreTrainedTokenizerFast) self.assertEqual(tokenizer.model_max_length, 512) self.assertEqual(tokenizer.vocab_size, 30000) self.assertEqual(tokenizer.unk_token, "[UNK]") self.assertEqual(tokenizer.padding_side, "right") self.assertEqual(tokenizer.truncation_side, "right") def test_auto_tokenizer_from_local_folder(self): tokenizer = AutoTokenizer.from_pretrained(SMALL_MODEL_IDENTIFIER) self.assertIsInstance(tokenizer, (BertTokenizer, BertTokenizerFast)) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(tmp_dir) tokenizer2 = AutoTokenizer.from_pretrained(tmp_dir) self.assertIsInstance(tokenizer2, tokenizer.__class__) self.assertEqual(tokenizer2.vocab_size, 12) def test_auto_tokenizer_fast_no_slow(self): tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl") # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(tokenizer, CTRLTokenizer) def test_get_tokenizer_config(self): # Check we can load the tokenizer config of an online model. config = get_tokenizer_config("google-bert/bert-base-cased") _ = config.pop("_commit_hash", None) # If we ever update google-bert/bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(config, {"do_lower_case": False, "model_max_length": 512}) # This model does not have a tokenizer_config so we get back an empty dict. config = get_tokenizer_config(SMALL_MODEL_IDENTIFIER) self.assertDictEqual(config, {}) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. tokenizer = AutoTokenizer.from_pretrained(SMALL_MODEL_IDENTIFIER) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(tmp_dir) config = get_tokenizer_config(tmp_dir) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config["tokenizer_class"], "BertTokenizer") def test_new_tokenizer_registration(self): try: AutoConfig.register("custom", CustomConfig) AutoTokenizer.register(CustomConfig, slow_tokenizer_class=CustomTokenizer) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(ValueError): AutoTokenizer.register(BertConfig, slow_tokenizer_class=BertTokenizer) tokenizer = CustomTokenizer.from_pretrained(SMALL_MODEL_IDENTIFIER) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(tmp_dir) new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir) self.assertIsInstance(new_tokenizer, CustomTokenizer) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def test_new_tokenizer_fast_registration(self): try: AutoConfig.register("custom", CustomConfig) # Can register in two steps AutoTokenizer.register(CustomConfig, slow_tokenizer_class=CustomTokenizer) self.assertEqual(TOKENIZER_MAPPING[CustomConfig], (CustomTokenizer, None)) AutoTokenizer.register(CustomConfig, fast_tokenizer_class=CustomTokenizerFast) self.assertEqual(TOKENIZER_MAPPING[CustomConfig], (CustomTokenizer, CustomTokenizerFast)) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( CustomConfig, slow_tokenizer_class=CustomTokenizer, fast_tokenizer_class=CustomTokenizerFast ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig], (CustomTokenizer, CustomTokenizerFast)) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(ValueError): AutoTokenizer.register(BertConfig, fast_tokenizer_class=BertTokenizerFast) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: bert_tokenizer = BertTokenizerFast.from_pretrained(SMALL_MODEL_IDENTIFIER) bert_tokenizer.save_pretrained(tmp_dir) tokenizer = CustomTokenizerFast.from_pretrained(tmp_dir) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(tmp_dir) new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir) self.assertIsInstance(new_tokenizer, CustomTokenizerFast) new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir, use_fast=False) self.assertIsInstance(new_tokenizer, CustomTokenizer) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def test_from_pretrained_dynamic_tokenizer(self): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(ValueError): tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer") # If remote code is disabled, we can't load this config. with self.assertRaises(ValueError): tokenizer = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=False ) tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True) self.assertTrue(tokenizer.special_attribute_present) # Test the dynamic module is loaded only once. reloaded_tokenizer = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True ) self.assertIs(tokenizer.__class__, reloaded_tokenizer.__class__) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(tmp_dir) reloaded_tokenizer = AutoTokenizer.from_pretrained(tmp_dir, trust_remote_code=True) self.assertTrue(reloaded_tokenizer.special_attribute_present) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast") self.assertEqual(reloaded_tokenizer.__class__.__name__, "NewTokenizerFast") # Test we can also load the slow version tokenizer = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True, use_fast=False ) self.assertTrue(tokenizer.special_attribute_present) self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(tmp_dir) reloaded_tokenizer = AutoTokenizer.from_pretrained(tmp_dir, trust_remote_code=True, use_fast=False) self.assertTrue( os.path.exists(os.path.join(tmp_dir, "tokenization.py")) ) # Assert we saved tokenizer code self.assertEqual(reloaded_tokenizer._auto_class, "AutoTokenizer") with open(os.path.join(tmp_dir, "tokenizer_config.json"), "r") as f: tokenizer_config = json.load(f) # Assert we're pointing at local code and not another remote repo self.assertEqual(tokenizer_config["auto_map"]["AutoTokenizer"], ["tokenization.NewTokenizer", None]) self.assertEqual(reloaded_tokenizer.__class__.__name__, "NewTokenizer") self.assertTrue(reloaded_tokenizer.special_attribute_present) else: self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") self.assertEqual(reloaded_tokenizer.__class__.__name__, "NewTokenizer") # Test the dynamic module is reloaded if we force it. reloaded_tokenizer = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True, force_download=True ) self.assertIsNot(tokenizer.__class__, reloaded_tokenizer.__class__) self.assertTrue(reloaded_tokenizer.special_attribute_present) @require_tokenizers def test_from_pretrained_dynamic_tokenizer_conflict(self): class NewTokenizer(BertTokenizer): special_attribute_present = False class NewTokenizerFast(BertTokenizerFast): slow_tokenizer_class = NewTokenizer special_attribute_present = False try: AutoConfig.register("custom", CustomConfig) AutoTokenizer.register(CustomConfig, slow_tokenizer_class=NewTokenizer) AutoTokenizer.register(CustomConfig, fast_tokenizer_class=NewTokenizerFast) # If remote code is not set, the default is to use local tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer") self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast") self.assertFalse(tokenizer.special_attribute_present) tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer", use_fast=False) self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") self.assertFalse(tokenizer.special_attribute_present) # If remote code is disabled, we load the local one. tokenizer = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=False ) self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast") self.assertFalse(tokenizer.special_attribute_present) tokenizer = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=False, use_fast=False ) self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") self.assertFalse(tokenizer.special_attribute_present) # If remote is enabled, we load from the Hub tokenizer = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True ) self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast") self.assertTrue(tokenizer.special_attribute_present) tokenizer = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True, use_fast=False ) self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") self.assertTrue(tokenizer.special_attribute_present) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def test_from_pretrained_dynamic_tokenizer_legacy_format(self): tokenizer = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer_legacy", trust_remote_code=True ) self.assertTrue(tokenizer.special_attribute_present) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast") # Test we can also load the slow version tokenizer = AutoTokenizer.from_pretrained( "hf-internal-testing/test_dynamic_tokenizer_legacy", trust_remote_code=True, use_fast=False ) self.assertTrue(tokenizer.special_attribute_present) self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") else: self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer") def test_repo_not_found(self): with self.assertRaisesRegex( EnvironmentError, "bert-base is not a local folder and is not a valid model identifier" ): _ = AutoTokenizer.from_pretrained("bert-base") def test_revision_not_found(self): with self.assertRaisesRegex( EnvironmentError, r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): _ = AutoTokenizer.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER, revision="aaaaaa") @unittest.skip("This test is failing on main") # TODO Matt/ydshieh, fix this test! def test_cached_tokenizer_has_minimum_calls_to_head(self): # Make sure we have cached the tokenizer. _ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert") with RequestCounter() as counter: _ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert") self.assertEqual(counter["GET"], 0) self.assertEqual(counter["HEAD"], 1) self.assertEqual(counter.total_calls, 1) def test_init_tokenizer_with_trust(self): nop_tokenizer_code = """ import transformers class NopTokenizer(transformers.PreTrainedTokenizer): def get_vocab(self): return {} """ nop_config_code = """ from transformers import PretrainedConfig class NopConfig(PretrainedConfig): model_type = "test_unregistered_dynamic" def __init__(self, **kwargs): super().__init__(**kwargs) """ with tempfile.TemporaryDirectory() as tmp_dir: fake_model_id = "hf-internal-testing/test_unregistered_dynamic" fake_repo = os.path.join(tmp_dir, fake_model_id) os.makedirs(fake_repo) tokenizer_src_file = os.path.join(fake_repo, "tokenizer.py") with open(tokenizer_src_file, "w") as wfp: wfp.write(nop_tokenizer_code) model_config_src_file = os.path.join(fake_repo, "config.py") with open(model_config_src_file, "w") as wfp: wfp.write(nop_config_code) config = { "model_type": "test_unregistered_dynamic", "auto_map": {"AutoConfig": f"{fake_model_id}--config.NopConfig"}, } config_file = os.path.join(fake_repo, "config.json") with open(config_file, "w") as wfp: json.dump(config, wfp, indent=2) tokenizer_config = { "auto_map": { "AutoTokenizer": [ f"{fake_model_id}--tokenizer.NopTokenizer", None, ] } } tokenizer_config_file = os.path.join(fake_repo, "tokenizer_config.json") with open(tokenizer_config_file, "w") as wfp: json.dump(tokenizer_config, wfp, indent=2) prev_dir = os.getcwd() try: # it looks like subdir= is broken in the from_pretrained also, so this is necessary os.chdir(tmp_dir) # this should work because we trust the code _ = AutoTokenizer.from_pretrained(fake_model_id, local_files_only=True, trust_remote_code=True) try: # this should fail because we don't trust and we're not at a terminal for interactive response _ = AutoTokenizer.from_pretrained(fake_model_id, local_files_only=True, trust_remote_code=False) self.fail("AutoTokenizer.from_pretrained with trust_remote_code=False should raise ValueException") except ValueError: pass finally: os.chdir(prev_dir)
transformers/tests/models/auto/test_tokenization_auto.py/0
{ "file_path": "transformers/tests/models/auto/test_tokenization_auto.py", "repo_id": "transformers", "token_count": 10439 }
533
# Copyright 2020 Ecole Polytechnique and 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 unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class BarthezTokenizationTest(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "moussaKam/mbarthez" tokenizer_class = BarthezTokenizer rust_tokenizer_class = BarthezTokenizerFast test_rust_tokenizer = True test_sentencepiece = True @classmethod def setUpClass(cls): super().setUpClass() tokenizer = BarthezTokenizerFast.from_pretrained("moussaKam/mbarthez") tokenizer.save_pretrained(cls.tmpdirname) tokenizer.save_pretrained(cls.tmpdirname, legacy_format=False) cls.tokenizer = tokenizer def test_convert_token_and_id(self): """Test ``_convert_token_to_id`` and ``_convert_id_to_token``.""" token = "<pad>" token_id = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token) def test_get_vocab(self): vocab_keys = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0], "<s>") self.assertEqual(vocab_keys[1], "<pad>") self.assertEqual(vocab_keys[-1], "<mask>") self.assertEqual(len(vocab_keys), 101_122) def test_vocab_size(self): self.assertEqual(self.get_tokenizer().vocab_size, 101_122) @require_torch def test_prepare_batch(self): src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."] expected_src_tokens = [0, 57, 3018, 70307, 91, 2] batch = self.tokenizer( src_text, max_length=len(expected_src_tokens), padding=True, truncation=True, return_tensors="pt" ) self.assertIsInstance(batch, BatchEncoding) self.assertEqual((2, 6), batch.input_ids.shape) self.assertEqual((2, 6), batch.attention_mask.shape) result = batch.input_ids.tolist()[0] self.assertListEqual(expected_src_tokens, result) def test_rust_and_python_full_tokenizers(self): if not self.test_rust_tokenizer: self.skipTest(reason="test_rust_tokenizer is set to False") tokenizer = self.get_tokenizer() rust_tokenizer = self.get_rust_tokenizer() sequence = "I was born in 92000, and this is falsé." tokens = tokenizer.tokenize(sequence) rust_tokens = rust_tokenizer.tokenize(sequence) self.assertListEqual(tokens, rust_tokens) ids = tokenizer.encode(sequence, add_special_tokens=False) rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) self.assertListEqual(ids, rust_ids) rust_tokenizer = self.get_rust_tokenizer() ids = tokenizer.encode(sequence) rust_ids = rust_tokenizer.encode(sequence) self.assertListEqual(ids, rust_ids) @slow def test_tokenizer_integration(self): expected_encoding = {'input_ids': [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 5, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # fmt: skip # moussaKam/mbarthez is a french model. So we also use french texts. sequences = [ "Le transformeur est un modèle d'apprentissage profond introduit en 2017, " "utilisé principalement dans le domaine du traitement automatique des langues (TAL).", "À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus " "pour gérer des données séquentielles, telles que le langage naturel, pour des tâches " "telles que la traduction et la synthèse de texte.", ] self.tokenizer_integration_test_util( expected_encoding=expected_encoding, model_name="moussaKam/mbarthez", revision="c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6", sequences=sequences, )
transformers/tests/models/barthez/test_tokenization_barthez.py/0
{ "file_path": "transformers/tests/models/barthez/test_tokenization_barthez.py", "repo_id": "transformers", "token_count": 2439 }
534
# Copyright 2023 The Intel Labs Team Authors, The Microsoft Research Team Authors and 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. """Testing suite for the PyTorch BridgeTower model.""" import unittest from transformers import ( BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, is_torch_available, is_vision_available, ) from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ( ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor, random_attention_mask, ) from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, ) if is_vision_available(): from PIL import Image from transformers import BridgeTowerProcessor class BridgeTowerTextModelTester: def __init__( self, parent, hidden_act="gelu", hidden_size=64, initializer_factor=1, layer_norm_eps=1e-05, num_attention_heads=4, num_hidden_layers=2, intermediate_size=128, tie_word_embeddings=False, output_hidden_states=False, ): self.parent = parent self.hidden_act = hidden_act self.hidden_size = hidden_size self.initializer_factor = initializer_factor self.layer_norm_eps = layer_norm_eps self.num_attention_heads = num_attention_heads self.num_hidden_layers = num_hidden_layers self.intermediate_size = intermediate_size self.tie_word_embeddings = tie_word_embeddings self.vocab_size = 99 self.seq_length = 4 self.batch_size = 1 self.is_training = False self.output_hidden_states = output_hidden_states def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) attention_mask = random_attention_mask([self.batch_size, self.seq_length]) config = self.get_config() return config, input_ids, attention_mask def get_config(self): return BridgeTowerTextConfig( hidden_act=self.hidden_act, hidden_size=self.hidden_size, initializer_factor=self.initializer_factor, layer_norm_eps=self.layer_norm_eps, num_attention_heads=self.num_attention_heads, num_hidden_layers=self.num_hidden_layers, intermediate_size=self.intermediate_size, tie_word_embeddings=self.tie_word_embeddings, output_hidden_states=self.output_hidden_states, vocab_size=self.vocab_size, ) class BridgeTowerImageModelTester: def __init__( self, parent, hidden_size=64, initializer_factor=1, layer_norm_eps=1e-05, num_hidden_layers=2, init_layernorm_from_vision_encoder=False, output_hidden_states=False, image_size=64, ): self.parent = parent self.hidden_size = hidden_size self.initializer_factor = initializer_factor self.layer_norm_eps = layer_norm_eps self.num_hidden_layers = num_hidden_layers self.init_layernorm_from_vision_encoder = init_layernorm_from_vision_encoder self.num_channels = 3 self.num_image_features = 17 self.batch_size = 1 self.image_size = image_size self.is_training = False self.output_hidden_states = output_hidden_states def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) pixel_mask = random_attention_mask([self.batch_size, self.image_size, self.image_size]) config = self.get_config() return config, pixel_values, pixel_mask def get_config(self): return BridgeTowerVisionConfig( hidden_size=self.hidden_size, initializer_factor=self.initializer_factor, layer_norm_eps=self.layer_norm_eps, num_hidden_layers=self.num_hidden_layers, init_layernorm_from_vision_encoder=self.init_layernorm_from_vision_encoder, num_channels=self.num_channels, num_image_features=self.num_image_features, batch_size=self.batch_size, image_size=self.image_size, is_training=self.is_training, output_hidden_states=self.output_hidden_states, ) class BridgeTowerModelTester: def __init__( self, parent, text_kwargs=None, vision_kwargs=None, share_cross_modal_transformer_layers=True, share_link_tower_layers=False, link_tower_type="add", init_layernorm_from_vision_encoder=False, contrastive_hidden_size=512, logit_scale_init_value=2.6592, hidden_size=64, num_hidden_layers=2, num_attention_heads=4, intermediate_size=128, ): if text_kwargs is None: text_kwargs = {} if vision_kwargs is None: vision_kwargs = {} self.parent = parent self.text_model_tester = BridgeTowerTextModelTester(parent, **text_kwargs) self.vision_model_tester = BridgeTowerImageModelTester(parent, **vision_kwargs) self.share_cross_modal_transformer_layers = share_cross_modal_transformer_layers self.share_link_tower_layers = share_link_tower_layers self.link_tower_type = link_tower_type self.init_layernorm_from_vision_encoder = init_layernorm_from_vision_encoder self.contrastive_hidden_size = contrastive_hidden_size self.logit_scale_init_value = logit_scale_init_value self.batch_size = 1 self.expected_num_hidden_layers = 8 self.is_training = False self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size def prepare_config_and_inputs(self): text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs() vision_config, pixel_values, pixel_mask = self.vision_model_tester.prepare_config_and_inputs() config = self.get_config() return (config, input_ids, attention_mask, pixel_values, pixel_mask) def get_config(self): return BridgeTowerConfig( text_config=self.text_model_tester.get_config().to_dict(), vision_config=self.vision_model_tester.get_config().to_dict(), share_cross_modal_transformer_layers=self.share_cross_modal_transformer_layers, share_link_tower_layers=self.share_link_tower_layers, link_tower_type=self.link_tower_type, init_layernorm_from_vision_encoder=self.init_layernorm_from_vision_encoder, contrastive_hidden_size=self.contrastive_hidden_size, logit_scale_init_value=self.logit_scale_init_value, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, ) def create_and_check_model( self, config, input_ids, attention_mask, pixel_values, pixel_mask, ): model = BridgeTowerModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values, pixel_mask=pixel_mask) result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values) self.parent.assertEqual( result["text_features"].shape, (self.batch_size, self.text_model_tester.seq_length, self.text_model_tester.hidden_size), ) self.parent.assertEqual( result["image_features"].shape, (self.batch_size, self.vision_model_tester.num_image_features, self.vision_model_tester.hidden_size), ) self.parent.assertEqual( result["pooler_output"].shape, (self.batch_size, self.text_model_tester.hidden_size + self.vision_model_tester.hidden_size), ) def create_and_check_for_image_and_text_retrieval( self, config, input_ids, attention_mask, pixel_values, pixel_mask, ): bridgetower_itm_output_last_dimension = 2 model = BridgeTowerForImageAndTextRetrieval(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values, pixel_mask=pixel_mask) result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values) self.parent.assertEqual(result.logits.shape, (self.batch_size, bridgetower_itm_output_last_dimension)) def create_and_check_for_masked_language_modeling( self, config, input_ids, attention_mask, pixel_values, pixel_mask, ): model = BridgeTowerForMaskedLM(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values, pixel_mask=pixel_mask) result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values) self.parent.assertEqual( result.logits.shape, (self.batch_size, self.text_model_tester.seq_length, self.text_model_tester.vocab_size), ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() (config, input_ids, attention_mask, pixel_values, pixel_mask) = config_and_inputs inputs_dict = { "input_ids": input_ids, "attention_mask": attention_mask, "pixel_values": pixel_values, "pixel_mask": pixel_mask, } return config, inputs_dict @require_torch class BridgeTowerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( BridgeTowerModel, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerForContrastiveLearning, ) if is_torch_available() else () ) pipeline_model_mapping = {"feature-extraction": BridgeTowerModel} if is_torch_available() else {} is_training = False test_headmasking = False test_pruning = False test_torchscript = False test_resize_embeddings = False has_attentions = False @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.") def test_cpu_offload(self): pass @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.") def test_disk_offload(self): pass @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.") def test_model_parallelism(self): pass # function to extract meaningful tensor from output per different model_class def extract_output(self, outputs, model_class): return outputs["pooler_output"] if model_class == "BridgeTowerModel" else outputs["logits"] def setUp(self): self.model_tester = BridgeTowerModelTester(self) self.config_tester = ConfigTester(self, config_class=BridgeTowerConfig, hidden_size=37, vocab_size=99) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_for_image_and_text_retrieval(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_and_text_retrieval(*config_and_inputs) def test_for_masked_language_modeling(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_language_modeling(*config_and_inputs) @slow def test_model_from_pretrained(self): model_name = "BridgeTower/bridgetower-base" model = BridgeTowerModel.from_pretrained(model_name) self.assertIsNotNone(model) # Override this as `hidden states output` is different for BridgeTower def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states_text, hidden_states_vision, hidden_states_cross = ( outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states ) expected_num_layers = self.model_tester.expected_num_hidden_layers self.assertEqual( sum((len(hidden_states_text), len(hidden_states_vision), len(hidden_states_cross))), expected_num_layers, ) seq_length = self.model_tester.text_model_tester.seq_length num_image_features = self.model_tester.vision_model_tester.num_image_features self.assertListEqual( list(hidden_states_text[0].shape[-2:]), [seq_length, self.model_tester.text_model_tester.hidden_size], ) self.assertListEqual( list(hidden_states_vision[0].shape), [num_image_features, 1, self.model_tester.vision_model_tester.hidden_size], ) self.assertListEqual( list(hidden_states_cross[0][0].shape[-2:]), [seq_length, self.model_tester.text_model_tester.hidden_size], ) self.assertListEqual( list(hidden_states_cross[0][1].shape[-2:]), [num_image_features, self.model_tester.vision_model_tester.hidden_size], ) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) # Override as `hidden states output` is different for BridgeTower def test_retain_grad_hidden_states_attentions(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.output_hidden_states = True config.output_attentions = self.has_attentions # no need to test all models as different heads yield the same functionality model_class = self.all_model_classes[0] model = model_class(config) model.to(torch_device) inputs = self._prepare_for_class(inputs_dict, model_class) outputs = model(**inputs) output = outputs[0] # Encoder-/Decoder-only models hidden_states = outputs.hidden_states[0][0] hidden_states.retain_grad() if self.has_attentions: attentions = outputs.attentions[0][0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=True) self.assertIsNotNone(hidden_states.grad) if self.has_attentions: self.assertIsNotNone(attentions.grad) # override as the `logit_scale` parameter initialization is different for BRIDGE TOWER def test_initialization(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() configs_no_init = _config_zero_init(config) for model_class in self.all_model_classes: model = model_class(config=configs_no_init) for name, param in model.named_parameters(): if param.requires_grad: if name == "logit_scale": self.assertAlmostEqual( param.data.item(), config.logit_scale_init_value, delta=1e-3, msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) else: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item(), [0.0, 1.0], msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) @unittest.skip(reason="""Bridge Tower does not have input/output embeddings. So this test is not applicable.""") def test_model_get_set_embeddings(self): pass @unittest.skip(reason="""Bridge Tower does not have input/output embeddings. Thus this test is not applicable.""") def test_inputs_embeds(self): pass @unittest.skip(reason="Bridge Tower does not use inputs_embeds") def test_inputs_embeds_matches_input_ids(self): pass # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch @require_vision class BridgeTowerModelIntegrationTest(unittest.TestCase): @cached_property def default_processor(self): return ( BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm") if is_vision_available() else None ) @slow def test_image_and_text_retrieval(self): model = BridgeTowerForImageAndTextRetrieval.from_pretrained("BridgeTower/bridgetower-base-itm-mlm").to( torch_device ) model.eval() processor = self.default_processor image = prepare_img() text = "a bunch of cats laying on a tower." inputs = processor(image, text, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the logits expected_shape = torch.Size([1, 2]) self.assertEqual(outputs.logits.shape, expected_shape) self.assertTrue(outputs.logits[0, 1].item() > outputs.logits[0, 0].item()) # verify loss inputs["labels"] = torch.ones(1, dtype=torch.long, device=torch_device) inputs = inputs.to(torch_device) with torch.no_grad(): outputs = model(**inputs) self.assertAlmostEqual(outputs.loss.item(), 0.5108, places=4) @slow def test_masked_language_modeling(self): model = BridgeTowerForMaskedLM.from_pretrained("BridgeTower/bridgetower-base-itm-mlm").to(torch_device) model.eval() processor = self.default_processor image = prepare_img() text = "a bunch of <mask> laying on a tower." inputs = processor(image, text, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the logits expected_shape = torch.Size([1, 11, 50265]) self.assertEqual(outputs.logits.shape, expected_shape) # verify predicted word predicted_id = outputs.logits.argmax(dim=-1).squeeze(0).tolist()[4] self.assertTrue(processor.decode([predicted_id]) == " cats") # verify loss inputs["labels"] = inputs["input_ids"].clone() inputs = inputs.to(torch_device) with torch.no_grad(): outputs = model(**inputs) self.assertAlmostEqual(outputs.loss.item(), 5.7373, places=4) @slow def test_constrastive_learning(self): model = BridgeTowerForContrastiveLearning.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc").to( torch_device ) model.eval() processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc") image = prepare_img() text = "a bunch of cats laying on a tower." inputs = processor(image, text, padding=True, return_tensors="pt").to(torch_device) with torch.no_grad(): outputs = model(**inputs, output_hidden_states=True, return_loss=True) # verify the logits expected_shape = torch.Size([1, 3, 512]) self.assertEqual(outputs.logits.shape, expected_shape) @slow @require_torch class BridgeTowerModelTrainingTest(unittest.TestCase): all_training_supported_model_classes = ( (BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerForContrastiveLearning) if is_torch_available() else () ) def setUp(self): self.model_tester = BridgeTowerModelTester(self) self.config_tester = ConfigTester(self, config_class=BridgeTowerConfig, hidden_size=37, vocab_size=99) def _prepare_inputs_for_training(self, model_class): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() if model_class == BridgeTowerForMaskedLM: inputs_dict["labels"] = inputs_dict["input_ids"] elif model_class == BridgeTowerForImageAndTextRetrieval: inputs_dict["labels"] = ids_tensor([1], 2) elif model_class == BridgeTowerForContrastiveLearning: inputs_dict["return_loss"] = True return config, inputs_dict def _get_non_used_layer_names(self, model_class): non_used_layer_names = ["text_model.pooler"] if model_class == BridgeTowerForMaskedLM: non_used_layer_names = non_used_layer_names + [ # This number `1` actually depends on the number of layers in `cross_modal_image_layers` (by minus 1) "cross_modal_image_layers.1", "cross_modal_image_pooler", "cross_modal_text_pooler", ] return non_used_layer_names def _is_layer_used(self, model_class, layer_name): non_used_layer_names = self._get_non_used_layer_names(model_class) for non_used_layer_name in non_used_layer_names: if non_used_layer_name in layer_name: return False return True def test_training(self): for model_class in self.all_training_supported_model_classes: config, inputs_dict = self._prepare_inputs_for_training(model_class) model = model_class(config) model.to(torch_device) model.train() loss = model(**inputs_dict).loss loss.backward() # verify the gradients of used layers' weight are not None for name, param in model.named_parameters(): if self._is_layer_used(model_class, name): self.assertIsNotNone(param.grad, f"Gradients should not be None - got {param.grad} for {name}") @slow def test_inference_interpolate_pos_encoding(self): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. model_name = "BridgeTower/bridgetower-base" model = BridgeTowerModel.from_pretrained(model_name).to(torch_device) image_processor = BridgeTowerProcessor.from_pretrained(model_name, size={"shortest_edge": 180}) image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") inputs = image_processor(text="what's in the image", images=image, return_tensors="pt").to(torch_device) # interpolate_pos_encodiung false should return value error with self.assertRaises(ValueError, msg="doesn't match model"): with torch.no_grad(): model(**inputs, interpolate_pos_encoding=False) # forward pass with torch.no_grad(): outputs = model(**inputs, interpolate_pos_encoding=True) # verify the logits expected_shape = torch.Size((1, 122, 768)) self.assertEqual(outputs.image_features.shape, expected_shape) expected_slice = torch.tensor( [[-0.6518, 0.4978, -0.4544], [-2.6672, -0.0843, -0.4210], [-2.4510, -0.1002, -0.3458]] ).to(torch_device) torch.testing.assert_close(outputs.image_features[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
transformers/tests/models/bridgetower/test_modeling_bridgetower.py/0
{ "file_path": "transformers/tests/models/bridgetower/test_modeling_bridgetower.py", "repo_id": "transformers", "token_count": 11221 }
535
# Copyright 2025 HuggingFace Inc. # # 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 unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image if is_torchvision_available(): from transformers import Cohere2VisionImageProcessorFast class Cohere2VisionImageProcessingTester(unittest.TestCase): def __init__( self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_normalize=True, image_mean=[0.48145466, 0.4578275, 0.40821073], image_std=[0.26862954, 0.26130258, 0.27577711], do_convert_rgb=True, ): super().__init__() size = size if size is not None else {"height": 30, "width": 30} self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_resize = do_resize self.size = size self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std self.do_convert_rgb = do_convert_rgb def prepare_image_processor_dict(self): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision class Cohere2VisionProcessingTest(ImageProcessingTestMixin, unittest.TestCase): fast_image_processing_class = Cohere2VisionImageProcessorFast if is_torchvision_available() else None test_slow_image_processor = False def setUp(self): super().setUp() self.image_processor_tester = Cohere2VisionImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processor = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processor, "do_resize")) self.assertTrue(hasattr(image_processor, "size")) self.assertTrue(hasattr(image_processor, "do_normalize")) self.assertTrue(hasattr(image_processor, "image_mean")) self.assertTrue(hasattr(image_processor, "image_std")) self.assertTrue(hasattr(image_processor, "do_convert_rgb")) def test_call_pil(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random PIL images image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True) for image in image_inputs: self.assertIsInstance(image, Image.Image) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values self.assertEqual(tuple(encoded_images.shape), (10, 3, 30, 30)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values self.assertEqual(tuple(encoded_images.shape), (70, 3, 30, 30)) def test_call_numpy(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random numpy tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, numpify=True) for image in image_inputs: self.assertIsInstance(image, np.ndarray) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values self.assertEqual(tuple(encoded_images.shape), (10, 3, 30, 30)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values self.assertEqual(tuple(encoded_images.shape), (70, 3, 30, 30)) def test_call_pytorch(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random PyTorch tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True) for image in image_inputs: self.assertIsInstance(image, torch.Tensor) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values self.assertEqual(tuple(encoded_images.shape), (10, 3, 30, 30)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values self.assertEqual(tuple(encoded_images.shape), (70, 3, 30, 30)) def test_call_numpy_4_channels(self): for image_processing_class in self.image_processor_list: # Test that can process images which have an arbitrary number of channels # Initialize image_processing image_processor = image_processing_class(**self.image_processor_dict) # create random numpy tensors self.image_processor_tester.num_channels = 4 image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, numpify=True) # Test not batched input encoded_images = image_processor( image_inputs[0], return_tensors="pt", input_data_format="channels_last", image_mean=0, image_std=1, ).pixel_values self.assertEqual(tuple(encoded_images.shape), (10, 4, 30, 30)) # Test batched encoded_images = image_processor( image_inputs, return_tensors="pt", input_data_format="channels_last", image_mean=0, image_std=1, ).pixel_values self.assertEqual(tuple(encoded_images.shape), (70, 4, 30, 30))
transformers/tests/models/cohere2_vision/test_image_processing_cohere2_vision.py/0
{ "file_path": "transformers/tests/models/cohere2_vision/test_image_processing_cohere2_vision.py", "repo_id": "transformers", "token_count": 3371 }
536
# Copyright 2022 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. """Testing suite for the PyTorch ConvNext model.""" import unittest from transformers import ConvNextConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class ConvNextModelTester: def __init__( self, parent, batch_size=13, image_size=32, num_channels=3, num_stages=4, hidden_sizes=[10, 20, 30, 40], depths=[2, 2, 3, 2], is_training=True, use_labels=True, intermediate_size=37, hidden_act="gelu", num_labels=10, initializer_range=0.02, out_features=["stage2", "stage3", "stage4"], out_indices=[2, 3, 4], scope=None, ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.num_channels = num_channels self.num_stages = num_stages self.hidden_sizes = hidden_sizes self.depths = depths self.is_training = is_training self.use_labels = use_labels self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.num_labels = num_labels self.initializer_range = initializer_range self.out_features = out_features self.out_indices = out_indices self.scope = scope def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) labels = None if self.use_labels: labels = ids_tensor([self.batch_size], self.num_labels) config = self.get_config() return config, pixel_values, labels def get_config(self): return ConvNextConfig( num_channels=self.num_channels, hidden_sizes=self.hidden_sizes, depths=self.depths, num_stages=self.num_stages, hidden_act=self.hidden_act, is_decoder=False, initializer_range=self.initializer_range, out_features=self.out_features, out_indices=self.out_indices, num_labels=self.num_labels, ) def create_and_check_model(self, config, pixel_values, labels): model = ConvNextModel(config=config) model.to(torch_device) model.eval() result = model(pixel_values) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32), ) def create_and_check_for_image_classification(self, config, pixel_values, labels): model = ConvNextForImageClassification(config) model.to(torch_device) model.eval() result = model(pixel_values, labels=labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def create_and_check_backbone(self, config, pixel_values, labels): model = ConvNextBackbone(config=config) model.to(torch_device) model.eval() result = model(pixel_values) # verify hidden states self.parent.assertEqual(len(result.feature_maps), len(config.out_features)) self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.hidden_sizes[1], 4, 4]) # verify channels self.parent.assertEqual(len(model.channels), len(config.out_features)) self.parent.assertListEqual(model.channels, config.hidden_sizes[1:]) # verify backbone works with out_features=None config.out_features = None model = ConvNextBackbone(config=config) model.to(torch_device) model.eval() result = model(pixel_values) # verify feature maps self.parent.assertEqual(len(result.feature_maps), 1) self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.hidden_sizes[-1], 1, 1]) # verify channels self.parent.assertEqual(len(model.channels), 1) self.parent.assertListEqual(model.channels, [config.hidden_sizes[-1]]) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values, labels = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class ConvNextModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as ConvNext does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) pipeline_model_mapping = ( {"image-feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification} if is_torch_available() else {} ) fx_compatible = True test_pruning = False test_resize_embeddings = False test_head_masking = False has_attentions = False test_torch_exportable = True def setUp(self): self.model_tester = ConvNextModelTester(self) self.config_tester = ConfigTester( self, config_class=ConvNextConfig, has_text_modality=False, hidden_size=37, common_properties=["num_channels", "hidden_sizes"], ) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="ConvNext does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="ConvNext does not support input and output embeddings") def test_model_get_set_embeddings(self): pass @unittest.skip(reason="ConvNext does not use feedforward chunking") def test_feed_forward_chunking(self): pass def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_backbone(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*config_and_inputs) def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states expected_num_stages = self.model_tester.num_stages self.assertEqual(len(hidden_states), expected_num_stages + 1) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]), [self.model_tester.image_size // 4, self.model_tester.image_size // 4], ) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) def test_for_image_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*config_and_inputs) @slow def test_model_from_pretrained(self): model_name = "facebook/convnext-tiny-224" model = ConvNextModel.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch @require_vision class ConvNextModelIntegrationTest(unittest.TestCase): @cached_property def default_image_processor(self): return AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224") if is_vision_available() else None @slow def test_inference_image_classification_head(self): model = ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224").to(torch_device) image_processor = self.default_image_processor image = prepare_img() inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the logits expected_shape = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape, expected_shape) expected_slice = torch.tensor([-0.0261, -0.4739, 0.1910]).to(torch_device) torch.testing.assert_close(outputs.logits[0, :3], expected_slice, rtol=2e-4, atol=2e-4) @require_torch class ConvNextBackboneTest(unittest.TestCase, BackboneTesterMixin): all_model_classes = (ConvNextBackbone,) if is_torch_available() else () config_class = ConvNextConfig has_attentions = False def setUp(self): self.model_tester = ConvNextModelTester(self)
transformers/tests/models/convnext/test_modeling_convnext.py/0
{ "file_path": "transformers/tests/models/convnext/test_modeling_convnext.py", "repo_id": "transformers", "token_count": 4498 }
537
# Copyright 2024 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. """Testing suite for the PyTorch DINOv3 model.""" import unittest from transformers import DINOv3ViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import DINOv3ViTModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class DINOv3ViTModelTester: def __init__( self, parent, batch_size=13, image_size=30, patch_size=2, num_channels=3, is_training=False, use_labels=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, type_sequence_label_size=10, initializer_range=0.02, num_register_tokens=2, mask_ratio=0.5, scope=None, ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.is_training = is_training self.use_labels = use_labels self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_register_tokens = num_register_tokens self.scope = scope num_patches = (image_size // patch_size) ** 2 self.seq_length = num_patches + 1 + self.num_register_tokens self.mask_ratio = mask_ratio self.num_masks = int(mask_ratio * self.seq_length) self.mask_length = num_patches def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) labels = None if self.use_labels: labels = ids_tensor([self.batch_size], self.type_sequence_label_size) config = self.get_config() return config, pixel_values, labels def get_config(self): return DINOv3ViTConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=False, initializer_range=self.initializer_range, num_register_tokens=self.num_register_tokens, ) def create_and_check_model(self, config, pixel_values, labels): model = DINOv3ViTModel(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size), ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, pixel_values, labels, ) = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class Dinov3ModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as Dinov3 does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (DINOv3ViTModel,) if is_torch_available() else () pipeline_model_mapping = ( { "image-feature-extraction": DINOv3ViTModel, } if is_torch_available() else {} ) fx_compatible = False test_pruning = False test_resize_embeddings = False test_head_masking = False test_torch_exportable = True def setUp(self): self.model_tester = DINOv3ViTModelTester(self) self.config_tester = ConfigTester(self, config_class=DINOv3ViTConfig, has_text_modality=False, hidden_size=37) def test_initialization(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() configs_no_init = _config_zero_init(config) for model_class in self.all_model_classes: model = model_class(config=configs_no_init) for name, param in model.named_parameters(): if param.requires_grad and "register_tokens" not in name: # See PR #38607 (to avoid flakiness) data = torch.flatten(param.data) n_elements = torch.numel(data) # skip 2.5% of elements on each side to avoid issues caused by `nn.init.trunc_normal_` described in # https://github.com/huggingface/transformers/pull/27906#issuecomment-1846951332 n_elements_to_skip_on_each_side = int(n_elements * 0.025) data_to_check = torch.sort(data).values if n_elements_to_skip_on_each_side > 0: data_to_check = data_to_check[n_elements_to_skip_on_each_side:-n_elements_to_skip_on_each_side] self.assertIn( ((data_to_check.mean() * 1e9).round() / 1e9).item(), [0.0, 1.0], msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="Dinov3 does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant_false(self): pass def test_model_get_set_embeddings(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) x = model.get_output_embeddings() self.assertTrue(x is None or isinstance(x, nn.Linear)) def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) @unittest.skip(reason="Dinov3 does not support feedforward chunking yet") def test_feed_forward_chunking(self): pass @slow def test_model_from_pretrained(self): model_name = "facebook/dinov3-vits16-pretrain-lvd1689m" model = DINOv3ViTModel.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch @require_vision class DINOv3ViTModelIntegrationTest(unittest.TestCase): @cached_property def default_image_processor(self): return ( AutoImageProcessor.from_pretrained("facebook/dinov3-vits16-pretrain-lvd1689m") if is_vision_available() else None ) @slow def test_inference_no_head(self): model = DINOv3ViTModel.from_pretrained("facebook/dinov3-vits16-pretrain-lvd1689m").to(torch_device) image_processor = self.default_image_processor image = prepare_img() inputs = image_processor(image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the last hidden states # in DINOv3 with Registers, the seq length equals the number of patches + 1 + num_register_tokens (we add 1 for the [CLS] token) _, _, height, width = inputs["pixel_values"].shape num_patches = (height // model.config.patch_size) * (width // model.config.patch_size) expected_seq_length = num_patches + 1 + model.config.num_register_tokens expected_shape = torch.Size((1, expected_seq_length, model.config.hidden_size)) self.assertEqual(outputs.last_hidden_state.shape, expected_shape) last_layer_cls_token = outputs.pooler_output expected_slice = torch.tensor([0.4637, -0.4160, 0.4086, -0.1265, -0.2865], device=torch_device) torch.testing.assert_close(last_layer_cls_token[0, :5], expected_slice, rtol=1e-4, atol=1e-4) last_layer_patch_tokens = outputs.last_hidden_state[:, model.config.num_register_tokens + 1 :] expected_slice = torch.tensor([-0.0386, -0.2509, -0.0161, -0.4556, 0.5716], device=torch_device) torch.testing.assert_close(last_layer_patch_tokens[0, 0, :5], expected_slice, rtol=1e-4, atol=1e-4)
transformers/tests/models/dinov3_vit/test_modeling_dinov3_vit.py/0
{ "file_path": "transformers/tests/models/dinov3_vit/test_modeling_dinov3_vit.py", "repo_id": "transformers", "token_count": 4735 }
538
# Copyright 2020 Huggingface # # 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 transformers import ( DPRContextEncoderTokenizer, DPRContextEncoderTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast, DPRReaderOutput, DPRReaderTokenizer, DPRReaderTokenizerFast, ) from transformers.testing_utils import require_tokenizers, slow from transformers.tokenization_utils_base import BatchEncoding from ..bert import test_tokenization_bert @require_tokenizers class DPRContextEncoderTokenizationTest(test_tokenization_bert.BertTokenizationTest): tokenizer_class = DPRContextEncoderTokenizer rust_tokenizer_class = DPRContextEncoderTokenizerFast test_rust_tokenizer = True from_pretrained_id = "facebook/dpr-ctx_encoder-single-nq-base" @require_tokenizers class DPRQuestionEncoderTokenizationTest(test_tokenization_bert.BertTokenizationTest): tokenizer_class = DPRQuestionEncoderTokenizer rust_tokenizer_class = DPRQuestionEncoderTokenizerFast test_rust_tokenizer = True from_pretrained_id = "facebook/dpr-ctx_encoder-single-nq-base" @require_tokenizers class DPRReaderTokenizationTest(test_tokenization_bert.BertTokenizationTest): tokenizer_class = DPRReaderTokenizer rust_tokenizer_class = DPRReaderTokenizerFast test_rust_tokenizer = True from_pretrained_id = "facebook/dpr-ctx_encoder-single-nq-base" @slow def test_decode_best_spans(self): tokenizer = self.tokenizer_class.from_pretrained("google-bert/bert-base-uncased") text_1 = tokenizer.encode("question sequence", add_special_tokens=False) text_2 = tokenizer.encode("title sequence", add_special_tokens=False) text_3 = tokenizer.encode("text sequence " * 4, add_special_tokens=False) input_ids = [[101] + text_1 + [102] + text_2 + [102] + text_3] reader_input = BatchEncoding({"input_ids": input_ids}) start_logits = [[0] * len(input_ids[0])] end_logits = [[0] * len(input_ids[0])] relevance_logits = [0] reader_output = DPRReaderOutput(start_logits, end_logits, relevance_logits) start_index, end_index = 8, 9 start_logits[0][start_index] = 10 end_logits[0][end_index] = 10 predicted_spans = tokenizer.decode_best_spans(reader_input, reader_output) self.assertEqual(predicted_spans[0].start_index, start_index) self.assertEqual(predicted_spans[0].end_index, end_index) self.assertEqual(predicted_spans[0].doc_id, 0) @slow def test_call(self): tokenizer = self.tokenizer_class.from_pretrained("google-bert/bert-base-uncased") text_1 = tokenizer.encode("question sequence", add_special_tokens=False) text_2 = tokenizer.encode("title sequence", add_special_tokens=False) text_3 = tokenizer.encode("text sequence", add_special_tokens=False) expected_input_ids = [101] + text_1 + [102] + text_2 + [102] + text_3 encoded_input = tokenizer(questions=["question sequence"], titles=["title sequence"], texts=["text sequence"]) self.assertIn("input_ids", encoded_input) self.assertIn("attention_mask", encoded_input) self.assertListEqual(encoded_input["input_ids"][0], expected_input_ids)
transformers/tests/models/dpr/test_tokenization_dpr.py/0
{ "file_path": "transformers/tests/models/dpr/test_tokenization_dpr.py", "repo_id": "transformers", "token_count": 1367 }
539
# Copyright 2024 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. """Testing suite for the PyTorch emu3 model.""" import unittest import numpy as np import pytest import requests from huggingface_hub import hf_hub_download from parameterized import parameterized from transformers import Emu3Config, Emu3TextConfig, is_torch_available, is_vision_available, set_seed from transformers.testing_utils import ( Expectations, require_bitsandbytes, require_torch, require_torch_large_accelerator, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_vision_available(): from PIL import Image if is_torch_available(): import torch from transformers import ( Emu3ForCausalLM, Emu3ForConditionalGeneration, Emu3Model, Emu3Processor, Emu3TextModel, ) class Emu3Text2TextModelTester: def __init__( self, parent, batch_size=13, seq_length=7, is_training=False, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2, intermediate_size=37, max_position_embeddings=512, initializer_range=0.02, pad_token_id=0, bos_token_id=1, eos_token_id=2, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.intermediate_size = intermediate_size self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.pad_token_id = pad_token_id self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) attention_mask = input_ids.ne(self.pad_token_id).to(torch_device) config = self.get_config() return config, input_ids, attention_mask def get_config(self): return Emu3TextConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, num_key_value_heads=self.num_key_value_heads, intermediate_size=self.intermediate_size, max_position_embeddings=self.max_position_embeddings, is_decoder=False, initializer_range=self.initializer_range, pad_token_id=self.pad_token_id, bos_token_id=self.bos_token_id, eos_token_id=self.eos_token_id, ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, attention_mask, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask} return config, inputs_dict @require_torch class Emu3Text2TextModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (Emu3ForCausalLM,) if is_torch_available() else () pipeline_model_mapping = ( { "text-generation": Emu3ForCausalLM, } if is_torch_available() else {} ) test_headmasking = False test_pruning = False fx_compatible = False def setUp(self): self.model_tester = Emu3Text2TextModelTester(self) self.config_tester = ConfigTester(self, config_class=Emu3TextConfig, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() @parameterized.expand([("linear",), ("dynamic",)]) def test_model_rope_scaling(self, scaling_type): config, _ = self.model_tester.prepare_config_and_inputs_for_common() short_input = ids_tensor([1, 10], config.vocab_size) long_input = ids_tensor([1, int(config.max_position_embeddings * 1.5)], config.vocab_size) set_seed(42) # Fixed seed at init time so the two models get the same random weights original_model = Emu3TextModel(config) original_model.to(torch_device) original_model.eval() original_short_output = original_model(short_input).last_hidden_state original_long_output = original_model(long_input).last_hidden_state set_seed(42) # Fixed seed at init time so the two models get the same random weights config.rope_scaling = {"type": scaling_type, "factor": 10.0} scaled_model = Emu3TextModel(config) scaled_model.to(torch_device) scaled_model.eval() scaled_short_output = scaled_model(short_input).last_hidden_state scaled_long_output = scaled_model(long_input).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": torch.testing.assert_close(original_short_output, scaled_short_output, rtol=1e-5, atol=1e-5) else: self.assertFalse(torch.allclose(original_short_output, scaled_short_output, atol=1e-5)) # The output should be different for long inputs self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5)) @unittest.skip("Doesn't work, tensors are not almost same") # TODO raushan fixme def test_custom_4d_attention_mask(self): pass class Emu3Vision2TextModelTester: def __init__( self, parent, batch_size=13, seq_length=7, is_training=False, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2, intermediate_size=37, max_position_embeddings=512, initializer_range=0.02, pad_token_id=0, bos_token_id=1, eos_token_id=2, image_token_id=3, image_size=15, codebook_size=20, temporal_downsample_factor=1, base_channels=32, vq_channel_multiplier=[1, 2, 1], image_seq_length=12, vq_img_token_start_id=3, ): self.parent = parent self.batch_size = batch_size self.is_training = is_training self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.intermediate_size = intermediate_size self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.pad_token_id = pad_token_id self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id self.image_token_id = image_token_id self.image_size = image_size self.codebook_size = codebook_size self.temporal_downsample_factor = temporal_downsample_factor self.vq_channel_multiplier = vq_channel_multiplier self.vq_img_token_start_id = vq_img_token_start_id self.base_channels = base_channels self.seq_length = seq_length + image_seq_length self.image_seq_length = image_seq_length def prepare_config_and_inputs(self): config = self.get_config() input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size) input_ids[input_ids == self.image_token_id] = self.pad_token_id input_ids[:, : self.image_seq_length] = self.image_token_id attention_mask = input_ids.ne(self.pad_token_id).to(torch_device) pixel_values = floats_tensor( [ self.batch_size, 3, self.image_size, self.image_size, ] ) image_sizes = [[self.image_size, self.image_size]] * self.batch_size image_sizes = torch.tensor(image_sizes, device=torch_device, dtype=torch.int64) return config, input_ids, attention_mask, pixel_values, image_sizes def get_config(self): # create dummy vocab map for image2bpe mapping if it needs remapping # we assume that vocab size is big enough to account for `codebook_size` amount of # image tokens somewhere at the beginning of total vocab size vocab_map = {i: chr(i) for i in range(self.vocab_size)} start = self.vq_img_token_start_id end = self.vq_img_token_start_id + self.codebook_size for i in range(start, end): # dummy str for each token, anything that fits pattern "<|visual token XXXXXX|>" vocab_map[i] = f"<|visual token{i:06d}|>" # add tokens that have to be in the vocab, we'll retrieve their ids later in modeling code vocab_map[self.image_token_id] = "<image>" vocab_map[self.image_token_id + 1] = "<|extra_200|>" vocab_map = {v: k for k, v in vocab_map.items()} text_config = Emu3TextConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, num_key_value_heads=self.num_key_value_heads, intermediate_size=self.intermediate_size, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, pad_token_id=self.pad_token_id, bos_token_id=self.bos_token_id, eos_token_id=self.eos_token_id, ) vq_config = { "codebook_size": self.codebook_size, "temporal_downsample_factor": self.temporal_downsample_factor, "base_channels": self.base_channels, "channel_multiplier": self.vq_channel_multiplier, "hidden_size": self.base_channels, "attn_resolutions": [], } return Emu3Config(text_config=text_config, vq_config=vq_config, vocabulary_map=vocab_map) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, attention_mask, pixel_values, image_sizes, ) = config_and_inputs inputs_dict = { "input_ids": input_ids, "attention_mask": attention_mask, "pixel_values": pixel_values, "image_sizes": image_sizes, } return config, inputs_dict @require_torch class Emu3Vision2TextModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( Emu3Model, Emu3ForConditionalGeneration, ) if is_torch_available() else () ) pipeline_model_mapping = {} test_headmasking = False test_pruning = False fx_compatible = False def setUp(self): self.model_tester = Emu3Vision2TextModelTester(self) self.config_tester = ConfigTester(self, config_class=Emu3Config, has_text_modality=False, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() @unittest.skip( "Emu3 has a VQ module that uses `weight.data` directly in forward which prevent offloding on that module" ) def test_disk_offload_safetensors(self): pass @unittest.skip( "Emu3 has a VQ module that uses `weight.data` directly in forward which prevent offloding on that module" ) def test_disk_offload_bin(self): pass @unittest.skip( "Emu3 has a VQ module that uses `weight.data` directly in forward which prevent offloding on that module" ) def test_cpu_offload(self): pass @unittest.skip("VQ-VAE module doesn't initialize weights properly") def test_initialization(self): pass @pytest.mark.generate @unittest.skip("Emu3 has dynamic control flow in vision backbone") def test_generate_with_static_cache(self): pass # @unittest.skip("Emu3 can't be smaller than currently if we want to downsample images") # def test_model_is_small(self): # pass @require_torch class Emu3IntegrationTest(unittest.TestCase): @slow @require_bitsandbytes def test_model_generation(self): model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", load_in_4bit=True) processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf") image = Image.open(requests.get("https://picsum.photos/id/237/200/200", stream=True).raw) prompt = "USER: <image>Describe what do you see here and tell me about the history behind it? ASSISTANT:" inputs = processor(images=image, text=prompt, return_tensors="pt").to(model.device, torch.float16) # greedy generation outputs EXPECTED_TEXT_COMPLETION = ['USER: 64*64Describe what do you see here and tell me about the history behind it? ASSISTANT: The image captures a moment of tranquility with a black Labrador Retriever resting on a wooden floor. The dog, with its glossy black coat, is lying down with its front legs stretched out in'] # fmt: skip generated_ids = model.generate(**inputs, max_new_tokens=40, do_sample=False) text = processor.batch_decode(generated_ids, skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, text) @slow @require_bitsandbytes @require_torch_large_accelerator def test_model_generation_batched(self): model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", load_in_4bit=True) processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf") processor.tokenizer.padding_side = "left" image = Image.open(requests.get("https://picsum.photos/id/237/50/50", stream=True).raw) image_2 = Image.open(requests.get("https://picsum.photos/id/247/50/50", stream=True).raw) prompts = [ "USER: <image>Describe what do you see here? ASSISTANT:", "USER: <image>What can you say about the image? ASSISTANT:", ] inputs = processor(images=[image, image_2], text=prompts, padding=True, return_tensors="pt").to( model.device, torch.float16 ) # greedy generation outputs EXPECTED_TEXT_COMPLETIONS = Expectations( { ("xpu", 3): [ "USER: 64*64Describe what do you see here? ASSISTANT: The image depicts a black panther in a crouched position. The panther's body is elongated and its head is lowered, suggesting a state of alertness or readiness. The animal's", "USER: 64*64What can you say about the image? ASSISTANT: The image depicts a serene natural landscape. The foreground consists of a grassy area with some patches of bare earth. The middle ground shows a gently sloping hill with a reddish-brown hue,", ], (None, None): [ "USER: 64*64Describe what do you see here? ASSISTANT: The image depicts a black panther in a crouched position. The panther's body is elongated and curved, with its head lowered and ears pointed forward, suggesting alertness or focus.", "USER: 64*64What can you say about the image? ASSISTANT: The image depicts a serene natural landscape. The foreground consists of a grassy area with some patches of bare earth. The middle ground shows a steep, reddish-brown cliff, which could be a", ], # We switch to A10 on 2025/06/29, and A10 gives strange values ("cuda", 8): [ 'USER: 64*64Describe what do you see here? ASSISTANT: 1.Filed with 1.Computing theComputing.Computing.', 'USER: 64*64What can you say about the image? ASSISTANT: 1.Filed with theComputing theComputing.Computing.', ], } ) # fmt: skip EXPECTED_TEXT_COMPLETION = EXPECTED_TEXT_COMPLETIONS.get_expectation() generated_ids = model.generate(**inputs, max_new_tokens=40, do_sample=False) text = processor.batch_decode(generated_ids, skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, text) @slow @require_bitsandbytes @require_torch_large_accelerator def test_model_generation_multi_image(self): model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", load_in_4bit=True) processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf") image = Image.open(requests.get("https://picsum.photos/id/237/50/50", stream=True).raw) image_2 = Image.open(requests.get("https://picsum.photos/id/247/50/50", stream=True).raw) prompt = "USER: <image><image>What do these two images have in common? ASSISTANT:" inputs = processor(images=[image, image_2], text=prompt, return_tensors="pt").to(model.device, torch.float16) # greedy generation outputs EXPECTED_TEXT_COMPLETIONS = Expectations( { ("xpu", 3): ['USER: 64*6464*64What do these two images have in common? ASSISTANT: The two images both depict a rhinoceros, yet they are significantly different in terms of focus and clarity. The rhinoceros in the upper image is in sharp focus, showing detailed textures'], (None, None): ["USER: 64*6464*64What do these two images have in common? ASSISTANT: Both images feature a black animal, but they are not the same animal. The top image shows a close-up of a black cow's head, while the bottom image depicts a black cow in a natural"], # We switch to A10 on 2025/06/29, and A10 gives strange values ("cuda", 8): ['USER: 64*6464*64What do these two images have in common? ASSISTANT:Computing.Filed.Filed.11.Computing theComputing.Computing.'], } ) # fmt: skip EXPECTED_TEXT_COMPLETION = EXPECTED_TEXT_COMPLETIONS.get_expectation() generated_ids = model.generate(**inputs, max_new_tokens=40, do_sample=False) text = processor.batch_decode(generated_ids, skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, text) @slow @require_bitsandbytes @require_torch_large_accelerator def test_model_generate_images(self): model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Gen-hf", load_in_4bit=True) processor = Emu3Processor.from_pretrained("BAAI/Emu3-Gen-hf") inputs = processor( text=["a portrait of young girl. masterpiece, film grained, best quality."], padding=True, return_tensors="pt", return_for_image_generation=True, image_area=1600, ).to(model.device) self.assertTrue(inputs.input_ids.shape[1] == 21) image_sizes = inputs.pop("image_sizes") HEIGHT, WIDTH = image_sizes[0] VISUAL_TOKENS = model.vocabulary_mapping.image_tokens def prefix_allowed_tokens_fn(batch_id, input_ids): height, width = HEIGHT, WIDTH visual_tokens = VISUAL_TOKENS image_wrapper_token_id = torch.tensor([processor.tokenizer.image_wrapper_token_id], device=model.device) eoi_token_id = torch.tensor([processor.tokenizer.eoi_token_id], device=model.device) eos_token_id = torch.tensor([processor.tokenizer.eos_token_id], device=model.device) pad_token_id = torch.tensor([processor.tokenizer.pad_token_id], device=model.device) eof_token_id = torch.tensor([processor.tokenizer.eof_token_id], device=model.device) eol_token_id = processor.tokenizer.encode("<|extra_200|>", return_tensors="pt")[0] position = torch.nonzero(input_ids == image_wrapper_token_id, as_tuple=True)[0][0] offset = input_ids.shape[0] - position if offset % (width + 1) == 0: return (eol_token_id,) elif offset == (width + 1) * height + 1: return (eof_token_id,) elif offset == (width + 1) * height + 2: return (eoi_token_id,) elif offset == (width + 1) * height + 3: return (eos_token_id,) elif offset > (width + 1) * height + 3: return (pad_token_id,) else: return visual_tokens out = model.generate( **inputs, max_new_tokens=200, prefix_allowed_tokens_fn=prefix_allowed_tokens_fn, do_sample=False, ) self.assertTrue(out.shape[1] == 54) image = model.decode_image_tokens(image_tokens=out[:, inputs.input_ids.shape[1] :], height=HEIGHT, width=WIDTH) images = processor.postprocess(list(image.float()), return_tensors="np") self.assertTrue(images["pixel_values"].shape == (3, 40, 40)) self.assertTrue(isinstance(images["pixel_values"], np.ndarray)) filepath = hf_hub_download( repo_id="raushan-testing-hf/images_test", filename="emu3_image.npy", repo_type="dataset", ) original_pixels = np.load(filepath) self.assertTrue(np.allclose(original_pixels, images["pixel_values"], atol=1))
transformers/tests/models/emu3/test_modeling_emu3.py/0
{ "file_path": "transformers/tests/models/emu3/test_modeling_emu3.py", "repo_id": "transformers", "token_count": 9740 }
540
# Copyright 2022 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. """Testing suite for the PyTorch FocalNet model.""" import collections import unittest from transformers import FocalNetConfig from transformers.testing_utils import Expectations, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class FocalNetModelTester: def __init__( self, parent, batch_size=13, image_size=32, patch_size=2, num_channels=3, embed_dim=16, hidden_sizes=[32, 64, 128], depths=[1, 2, 1], num_heads=[2, 2, 4], window_size=2, mlp_ratio=2.0, qkv_bias=True, hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, drop_path_rate=0.1, hidden_act="gelu", use_absolute_embeddings=False, patch_norm=True, initializer_range=0.02, layer_norm_eps=1e-5, is_training=True, scope=None, use_labels=True, type_sequence_label_size=10, encoder_stride=8, out_features=["stage1", "stage2"], out_indices=[1, 2], ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.embed_dim = embed_dim self.hidden_sizes = hidden_sizes self.depths = depths self.num_heads = num_heads self.window_size = window_size self.mlp_ratio = mlp_ratio self.qkv_bias = qkv_bias self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.drop_path_rate = drop_path_rate self.hidden_act = hidden_act self.use_absolute_embeddings = use_absolute_embeddings self.patch_norm = patch_norm self.layer_norm_eps = layer_norm_eps self.initializer_range = initializer_range self.is_training = is_training self.scope = scope self.use_labels = use_labels self.type_sequence_label_size = type_sequence_label_size self.encoder_stride = encoder_stride self.out_features = out_features self.out_indices = out_indices def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) labels = None if self.use_labels: labels = ids_tensor([self.batch_size], self.type_sequence_label_size) config = self.get_config() return config, pixel_values, labels def get_config(self): return FocalNetConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, embed_dim=self.embed_dim, hidden_sizes=self.hidden_sizes, depths=self.depths, num_heads=self.num_heads, window_size=self.window_size, mlp_ratio=self.mlp_ratio, qkv_bias=self.qkv_bias, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, drop_path_rate=self.drop_path_rate, hidden_act=self.hidden_act, use_absolute_embeddings=self.use_absolute_embeddings, path_norm=self.patch_norm, layer_norm_eps=self.layer_norm_eps, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, out_features=self.out_features, out_indices=self.out_indices, ) def create_and_check_model(self, config, pixel_values, labels): model = FocalNetModel(config=config) model.to(torch_device) model.eval() result = model(pixel_values) expected_seq_len = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1)) expected_dim = int(config.embed_dim * 2 ** (len(config.depths) - 1)) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim)) def create_and_check_backbone(self, config, pixel_values, labels): model = FocalNetBackbone(config=config) model.to(torch_device) model.eval() result = model(pixel_values) # verify feature maps self.parent.assertEqual(len(result.feature_maps), len(config.out_features)) self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.image_size, 8, 8]) # verify channels self.parent.assertEqual(len(model.channels), len(config.out_features)) self.parent.assertListEqual(model.channels, config.hidden_sizes[:-1]) # verify backbone works with out_features=None config.out_features = None model = FocalNetBackbone(config=config) model.to(torch_device) model.eval() result = model(pixel_values) # verify feature maps self.parent.assertEqual(len(result.feature_maps), 1) self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.image_size * 2, 4, 4]) # verify channels self.parent.assertEqual(len(model.channels), 1) self.parent.assertListEqual(model.channels, [config.hidden_sizes[-1]]) def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels): model = FocalNetForMaskedImageModeling(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertEqual( result.reconstruction.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images config.num_channels = 1 model = FocalNetForMaskedImageModeling(config) model.to(torch_device) model.eval() pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) result = model(pixel_values) self.parent.assertEqual(result.reconstruction.shape, (self.batch_size, 1, self.image_size, self.image_size)) def create_and_check_for_image_classification(self, config, pixel_values, labels): config.num_labels = self.type_sequence_label_size model = FocalNetForImageClassification(config) model.to(torch_device) model.eval() result = model(pixel_values, labels=labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) # test greyscale images config.num_channels = 1 model = FocalNetForImageClassification(config) model.to(torch_device) model.eval() pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) result = model(pixel_values) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values, labels = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class FocalNetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) pipeline_model_mapping = ( {"image-feature-extraction": FocalNetModel, "image-classification": FocalNetForImageClassification} if is_torch_available() else {} ) fx_compatible = False test_pruning = False test_resize_embeddings = False test_head_masking = False has_attentions = False test_torch_exportable = True def setUp(self): self.model_tester = FocalNetModelTester(self) self.config_tester = ConfigTester( self, config_class=FocalNetConfig, embed_dim=37, has_text_modality=False, common_properties=["image_size", "patch_size", "num_channels", "hidden_sizes"], ) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_backbone(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*config_and_inputs) def test_for_masked_image_modeling(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs) def test_for_image_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*config_and_inputs) @unittest.skip(reason="FocalNet does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="FocalNet does not use feedforward chunking") def test_feed_forward_chunking(self): pass def test_model_get_set_embeddings(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: model = model_class(config) self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) x = model.get_output_embeddings() self.assertTrue(x is None or isinstance(x, nn.Linear)) def check_hidden_states_output(self, inputs_dict, config, model_class, image_size): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.hidden_states expected_num_layers = getattr( self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths) + 1 ) self.assertEqual(len(hidden_states), expected_num_layers) # FocalNet has a different seq_length patch_size = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable) else (config.patch_size, config.patch_size) ) num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:]), [num_patches, self.model_tester.embed_dim], ) reshaped_hidden_states = outputs.reshaped_hidden_states self.assertEqual(len(reshaped_hidden_states), expected_num_layers) batch_size, num_channels, height, width = reshaped_hidden_states[0].shape reshaped_hidden_states = ( reshaped_hidden_states[0].view(batch_size, num_channels, height * width).permute(0, 2, 1) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:]), [num_patches, self.model_tester.embed_dim], ) def test_hidden_states_output(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() image_size = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: inputs_dict["output_hidden_states"] = True self.check_hidden_states_output(inputs_dict, config, model_class, image_size) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True self.check_hidden_states_output(inputs_dict, config, model_class, image_size) def test_hidden_states_output_with_padding(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.patch_size = 3 image_size = ( self.model_tester.image_size if isinstance(self.model_tester.image_size, collections.abc.Iterable) else (self.model_tester.image_size, self.model_tester.image_size) ) patch_size = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable) else (config.patch_size, config.patch_size) ) padded_height = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) padded_width = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: inputs_dict["output_hidden_states"] = True self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width)) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width)) @slow def test_model_from_pretrained(self): model_name = "microsoft/focalnet-tiny" model = FocalNetModel.from_pretrained(model_name) self.assertIsNotNone(model) def test_initialization(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() configs_no_init = _config_zero_init(config) for model_class in self.all_model_classes: model = model_class(config=configs_no_init) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item(), [0.0, 1.0], msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) @require_vision @require_torch class FocalNetModelIntegrationTest(unittest.TestCase): @cached_property def default_image_processor(self): # TODO update organization return AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny") if is_vision_available() else None @slow def test_inference_image_classification_head(self): model = FocalNetForImageClassification.from_pretrained("microsoft/focalnet-tiny").to(torch_device) image_processor = self.default_image_processor image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the logits expected_shape = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape, expected_shape) expectations = Expectations( { (None, None): [0.2166, -0.4368, 0.2191], ("cuda", 8): [0.2168, -0.4367, 0.2190], } ) expected_slice = torch.tensor(expectations.get_expectation()).to(torch_device) torch.testing.assert_close(outputs.logits[0, :3], expected_slice, rtol=2e-4, atol=2e-4) self.assertTrue(outputs.logits.argmax(dim=-1).item(), 281) @require_torch class FocalNetBackboneTest(BackboneTesterMixin, unittest.TestCase): all_model_classes = (FocalNetBackbone,) if is_torch_available() else () config_class = FocalNetConfig has_attentions = False def setUp(self): self.model_tester = FocalNetModelTester(self)
transformers/tests/models/focalnet/test_modeling_focalnet.py/0
{ "file_path": "transformers/tests/models/focalnet/test_modeling_focalnet.py", "repo_id": "transformers", "token_count": 7534 }
541
# Copyright 2025 The ZhipuAI Inc. team and 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. """Testing suite for the PyTorch GLM-4-MoE model.""" import unittest import pytest import torch from packaging import version from transformers import is_torch_available from transformers.testing_utils import ( cleanup, require_read_token, require_torch, require_torch_accelerator, slow, torch_device, ) from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester if is_torch_available(): from transformers import AutoTokenizer, Glm4MoeConfig, Glm4MoeForCausalLM, Glm4MoeModel class Glm4MoeModelTester(CausalLMModelTester): if is_torch_available(): config_class = Glm4MoeConfig base_model_class = Glm4MoeModel causal_lm_class = Glm4MoeForCausalLM def __init__( self, parent, n_routed_experts=8, n_shared_experts=1, n_group=1, topk_group=1, num_experts_per_tok=8, ): super().__init__(parent=parent, num_experts_per_tok=num_experts_per_tok) self.n_routed_experts = n_routed_experts self.n_shared_experts = n_shared_experts self.n_group = n_group self.topk_group = topk_group @require_torch class Glm4MoeModelTest(CausalLMModelTest, unittest.TestCase): all_model_classes = ( ( Glm4MoeModel, Glm4MoeForCausalLM, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": Glm4MoeModel, "text-generation": Glm4MoeForCausalLM, } if is_torch_available() else {} ) test_headmasking = False test_pruning = False fx_compatible = False model_tester_class = Glm4MoeModelTester # used in `test_torch_compile_for_training`. Skip as "Dynamic control flow in MoE" _torch_compile_train_cls = None @require_torch_accelerator @require_read_token @slow class Glm4MoeIntegrationTest(unittest.TestCase): def tearDown(self): # See LlamaIntegrationTest.tearDown(). Can be removed once LlamaIntegrationTest.tearDown() is removed. cleanup(torch_device, gc_collect=False) @slow @require_torch_accelerator @pytest.mark.torch_compile_test @require_read_token def test_compile_static_cache(self): # `torch==2.2` will throw an error on this test (as in other compilation tests), but torch==2.1.2 and torch>2.2 # work as intended. See https://github.com/pytorch/pytorch/issues/121943 if version.parse(torch.__version__) < version.parse("2.3.0"): self.skipTest(reason="This test requires torch >= 2.3 to run.") NUM_TOKENS_TO_GENERATE = 40 EXPECTED_TEXT_COMPLETION = [ 'hello, world!\'\'\')\nprint(\'hello, world!\')\nprint("hello, world!")\nprint("hello, world!")\nprint("hello, world!")\nprint("hello, world!")\nprint("hello, world!")\n', "tell me the story of the first Thanksgiving. commonly known as the Pilgrims, arrived in the autumn of 1620. They were seeking religious freedom and a new life in the Plymouth Colony. Their first", ] prompts = ["[gMASK]<sop>hello", "[gMASK]<sop>tell me"] tokenizer = AutoTokenizer.from_pretrained("zai-org/GLM-4.5") model = Glm4MoeForCausalLM.from_pretrained("zai-org/GLM-4.5", device_map=torch_device, dtype=torch.bfloat16) inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) # Dynamic Cache generated_ids = model.generate(**inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False) dynamic_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, dynamic_text) # Static Cache generated_ids = model.generate( **inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False, cache_implementation="static" ) static_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, static_text) # Static Cache + compile model._cache = None # clear cache object, initialized when we pass `cache_implementation="static"` model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True) generated_ids = model.generate( **inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False, cache_implementation="static" ) static_compiled_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, static_compiled_text)
transformers/tests/models/glm4_moe/test_modeling_glm4_moe.py/0
{ "file_path": "transformers/tests/models/glm4_moe/test_modeling_glm4_moe.py", "repo_id": "transformers", "token_count": 2154 }
542
# 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 json import os import unittest from functools import lru_cache from transformers import AutoTokenizer, GPT2Tokenizer, GPT2TokenizerFast from transformers.models.gpt2.tokenization_gpt2 import VOCAB_FILES_NAMES from transformers.testing_utils import require_jinja, require_tiktoken, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin, use_cache_if_possible @require_tokenizers class GPT2TokenizationTest(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "openai-community/gpt2" tokenizer_class = GPT2Tokenizer rust_tokenizer_class = GPT2TokenizerFast test_rust_tokenizer = True from_pretrained_kwargs = {"add_prefix_space": True} test_seq2seq = False @classmethod def setUpClass(cls): super().setUpClass() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt vocab = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] vocab_tokens = dict(zip(vocab, range(len(vocab)))) merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] cls.special_tokens_map = {"unk_token": "<unk>"} cls.vocab_file = os.path.join(cls.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) cls.merges_file = os.path.join(cls.tmpdirname, VOCAB_FILES_NAMES["merges_file"]) with open(cls.vocab_file, "w", encoding="utf-8") as fp: fp.write(json.dumps(vocab_tokens) + "\n") with open(cls.merges_file, "w", encoding="utf-8") as fp: fp.write("\n".join(merges)) @classmethod @use_cache_if_possible @lru_cache(maxsize=64) def get_tokenizer(cls, pretrained_name=None, **kwargs): kwargs.update(cls.special_tokens_map) pretrained_name = pretrained_name or cls.tmpdirname return GPT2Tokenizer.from_pretrained(pretrained_name, **kwargs) @classmethod @use_cache_if_possible @lru_cache(maxsize=64) def get_rust_tokenizer(cls, pretrained_name=None, **kwargs): kwargs.update(cls.special_tokens_map) pretrained_name = pretrained_name or cls.tmpdirname return GPT2TokenizerFast.from_pretrained(pretrained_name, **kwargs) def get_input_output_texts(self, tokenizer): input_text = "lower newer" output_text = "lower newer" return input_text, output_text def test_full_tokenizer(self): tokenizer = GPT2Tokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map) text = "lower newer" bpe_tokens = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] tokens = tokenizer.tokenize(text, add_prefix_space=True) self.assertListEqual(tokens, bpe_tokens) input_tokens = tokens + [tokenizer.unk_token] input_bpe_tokens = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens) def test_rust_and_python_full_tokenizers(self): if not self.test_rust_tokenizer: self.skipTest(reason="test_rust_tokenizer is set to False") tokenizer = self.get_tokenizer() rust_tokenizer = self.get_rust_tokenizer(add_prefix_space=True) sequence = "lower newer" # Testing tokenization tokens = tokenizer.tokenize(sequence, add_prefix_space=True) rust_tokens = rust_tokenizer.tokenize(sequence) self.assertListEqual(tokens, rust_tokens) # Testing conversion to ids without special tokens ids = tokenizer.encode(sequence, add_special_tokens=False, add_prefix_space=True) rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) self.assertListEqual(ids, rust_ids) # Testing conversion to ids with special tokens rust_tokenizer = self.get_rust_tokenizer(add_prefix_space=True) ids = tokenizer.encode(sequence, add_prefix_space=True) rust_ids = rust_tokenizer.encode(sequence) self.assertListEqual(ids, rust_ids) # Testing the unknown token input_tokens = tokens + [rust_tokenizer.unk_token] input_bpe_tokens = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens) @unittest.skip def test_pretokenized_inputs(self, *args, **kwargs): # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def test_padding(self, max_length=15): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) # Simple input s = "This is a simple input" s2 = ["This is a simple input 1", "This is a simple input 2"] p = ("This is a simple input", "This is a pair") p2 = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(ValueError, tokenizer_r.encode, s, max_length=max_length, padding="max_length") # Simple input self.assertRaises(ValueError, tokenizer_r.encode_plus, s, max_length=max_length, padding="max_length") # Simple input self.assertRaises( ValueError, tokenizer_r.batch_encode_plus, s2, max_length=max_length, padding="max_length", ) # Pair input self.assertRaises(ValueError, tokenizer_r.encode, p, max_length=max_length, padding="max_length") # Pair input self.assertRaises(ValueError, tokenizer_r.encode_plus, p, max_length=max_length, padding="max_length") # Pair input self.assertRaises( ValueError, tokenizer_r.batch_encode_plus, p2, max_length=max_length, padding="max_length", ) def test_padding_if_pad_token_set_slow(self): tokenizer = GPT2Tokenizer.from_pretrained(self.tmpdirname, pad_token="<pad>") # Simple input s = "This is a simple input" s2 = ["This is a simple input looooooooong", "This is a simple input"] p = ("This is a simple input", "This is a pair") p2 = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] pad_token_id = tokenizer.pad_token_id out_s = tokenizer(s, padding="max_length", max_length=30, return_tensors="np") out_s2 = tokenizer(s2, padding=True, truncate=True, return_tensors="np") out_p = tokenizer(*p, padding="max_length", max_length=60, return_tensors="np") out_p2 = tokenizer(p2, padding=True, truncate=True, return_tensors="np") # s # test single string max_length padding self.assertEqual(out_s["input_ids"].shape[-1], 30) self.assertTrue(pad_token_id in out_s["input_ids"]) self.assertTrue(0 in out_s["attention_mask"]) # s2 # test automatic padding self.assertEqual(out_s2["input_ids"].shape[-1], 33) # long slice doesn't have padding self.assertFalse(pad_token_id in out_s2["input_ids"][0]) self.assertFalse(0 in out_s2["attention_mask"][0]) # short slice does have padding self.assertTrue(pad_token_id in out_s2["input_ids"][1]) self.assertTrue(0 in out_s2["attention_mask"][1]) # p # test single pair max_length padding self.assertEqual(out_p["input_ids"].shape[-1], 60) self.assertTrue(pad_token_id in out_p["input_ids"]) self.assertTrue(0 in out_p["attention_mask"]) # p2 # test automatic padding pair self.assertEqual(out_p2["input_ids"].shape[-1], 52) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_p2["input_ids"][0]) self.assertFalse(0 in out_p2["attention_mask"][0]) # short slice pair does have padding self.assertTrue(pad_token_id in out_p2["input_ids"][1]) self.assertTrue(0 in out_p2["attention_mask"][1]) def test_add_bos_token_slow(self): bos_token = "$$$" tokenizer = GPT2Tokenizer.from_pretrained(self.tmpdirname, bos_token=bos_token, add_bos_token=True) s = "This is a simple input" s2 = ["This is a simple input 1", "This is a simple input 2"] bos_token_id = tokenizer.bos_token_id out_s = tokenizer(s) out_s2 = tokenizer(s2) self.assertEqual(out_s.input_ids[0], bos_token_id) self.assertTrue(all(o[0] == bos_token_id for o in out_s2.input_ids)) decode_s = tokenizer.decode(out_s.input_ids) decode_s2 = tokenizer.batch_decode(out_s2.input_ids) self.assertTrue(decode_s.startswith(bos_token)) self.assertTrue(all(d.startswith(bos_token) for d in decode_s2)) @unittest.skip(reason="tokenizer has no padding token") def test_padding_different_model_input_name(self): pass def test_special_tokens_mask_input_pairs_and_bos_token(self): # TODO: change to self.get_tokenizers() when the fast version is implemented tokenizers = [self.get_tokenizer(do_lower_case=False, add_bos_token=True)] for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): sequence_0 = "Encode this." sequence_1 = "This one too please." encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False) encoded_sequence += tokenizer.encode(sequence_1, add_special_tokens=False) encoded_sequence_dict = tokenizer.encode_plus( sequence_0, sequence_1, add_special_tokens=True, return_special_tokens_mask=True, ) encoded_sequence_w_special = encoded_sequence_dict["input_ids"] special_tokens_mask = encoded_sequence_dict["special_tokens_mask"] self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special)) filtered_sequence = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(encoded_sequence_w_special) ] filtered_sequence = [x for x in filtered_sequence if x is not None] self.assertEqual(encoded_sequence, filtered_sequence) @require_jinja def test_tokenization_for_chat(self): tokenizer = GPT2Tokenizer.from_pretrained(self.tmpdirname) tokenizer.chat_template = "{% for message in messages %}{{ message.content }}{{ eos_token }}{% endfor %}" test_chats = [ [{"role": "system", "content": "You are a helpful chatbot."}, {"role": "user", "content": "Hello!"}], [ {"role": "system", "content": "You are a helpful chatbot."}, {"role": "user", "content": "Hello!"}, {"role": "assistant", "content": "Nice to meet you."}, ], [{"role": "assistant", "content": "Nice to meet you."}, {"role": "user", "content": "Hello!"}], ] tokenized_chats = [tokenizer.apply_chat_template(test_chat) for test_chat in test_chats] # fmt: off expected_tokens = [[20, 1, 20, 10, 20, 4, 3, 10, 20, 10, 20, 3, 0, 20, 20, 20, 0, 10, 20, 20, 20, 6, 20, 1, 6, 20, 20, 20, 3, 0, 0, 1, 20, 20], [20, 1, 20, 10, 20, 4, 3, 10, 20, 10, 20, 3, 0, 20, 20, 20, 0, 10, 20, 20, 20, 6, 20, 1, 6, 20, 20, 20, 3, 0, 0, 1, 20, 20, 20, 7, 20, 3, 10, 6, 1, 10, 20, 3, 3, 6, 10, 20, 1, 20, 20, 20], [20, 7, 20, 3, 10, 6, 1, 10, 20, 3, 3, 6, 10, 20, 1, 20, 20, 20, 20, 3, 0, 0, 1, 20, 20]] # fmt: on for tokenized_chat, expected_tokens in zip(tokenized_chats, expected_tokens): self.assertListEqual(tokenized_chat, expected_tokens) @require_tiktoken def test_tokenization_tiktoken(self): from tiktoken import encoding_name_for_model from transformers.integrations.tiktoken import convert_tiktoken_to_fast encoding = encoding_name_for_model("gpt2") convert_tiktoken_to_fast(encoding, self.tmpdirname) tiktoken_fast_tokenizer = GPT2TokenizerFast.from_pretrained(self.tmpdirname) rust_tokenizer = GPT2TokenizerFast.from_pretrained("openai-community/gpt2") sequence = "lower newer" self.assertEqual( rust_tokenizer.decode(rust_tokenizer.encode(sequence)), tiktoken_fast_tokenizer.decode(rust_tokenizer.encode(sequence)), ) @require_tokenizers class OPTTokenizationTest(unittest.TestCase): def test_serialize_deserialize_fast_opt(self): # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=True) text = "A photo of a cat" tokens_ids = tokenizer.encode( text, ) self.assertEqual(tokens_ids, [2, 250, 1345, 9, 10, 4758]) tokenizer.save_pretrained("test_opt") tokenizer = AutoTokenizer.from_pretrained("./test_opt") tokens_ids = tokenizer.encode( text, ) self.assertEqual(tokens_ids, [2, 250, 1345, 9, 10, 4758]) def test_fast_slow_equivalence(self): tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m", use_slow=True) text = "A photo of a cat" tokens_ids = tokenizer.encode( text, ) # Same as above self.assertEqual(tokens_ids, [2, 250, 1345, 9, 10, 4758]) @unittest.skip(reason="This test is failing because of a bug in the fast tokenizer") def test_users_can_modify_bos(self): tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=True) tokenizer.bos_token = "bos" tokenizer.bos_token_id = tokenizer.get_vocab()["bos"] text = "A photo of a cat" tokens_ids = tokenizer.encode( text, ) # We changed the bos token self.assertEqual(tokens_ids, [31957, 250, 1345, 9, 10, 4758]) tokenizer.save_pretrained("./tok") tokenizer = AutoTokenizer.from_pretrained("./tok") self.assertTrue(tokenizer.is_fast) tokens_ids = tokenizer.encode( text, ) self.assertEqual(tokens_ids, [31957, 250, 1345, 9, 10, 4758])
transformers/tests/models/gpt2/test_tokenization_gpt2.py/0
{ "file_path": "transformers/tests/models/gpt2/test_tokenization_gpt2.py", "repo_id": "transformers", "token_count": 7515 }
543
# Copyright 2022 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. """Testing suite for the PyTorch GroupViT model.""" import inspect import os import random import tempfile import unittest import numpy as np import requests from transformers import GroupViTConfig, GroupViTTextConfig, GroupViTVisionConfig from transformers.testing_utils import is_flaky, require_torch, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ( ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor, random_attention_mask, ) from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import GroupViTModel, GroupViTTextModel, GroupViTVisionModel if is_vision_available(): from PIL import Image from transformers import CLIPProcessor class GroupViTVisionModelTester: def __init__( self, parent, batch_size=12, image_size=30, patch_size=2, num_channels=3, is_training=True, hidden_size=32, depths=[6, 3, 3], num_group_tokens=[64, 8, 0], num_output_groups=[64, 8, 8], num_attention_heads=4, intermediate_size=37, dropout=0.1, attention_dropout=0.1, initializer_range=0.02, scope=None, ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.is_training = is_training self.hidden_size = hidden_size self.depths = depths self.num_hidden_layers = sum(depths) self.expected_num_hidden_layers = len(depths) + 1 self.num_group_tokens = num_group_tokens self.num_output_groups = num_output_groups self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.dropout = dropout self.attention_dropout = attention_dropout self.initializer_range = initializer_range self.scope = scope num_patches = (image_size // patch_size) ** 2 # no [CLS] token for GroupViT self.seq_length = num_patches def prepare_config_and_inputs(self): rng = random.Random(0) pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size], rng=rng) config = self.get_config() return config, pixel_values def get_config(self): return GroupViTVisionConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, depths=self.depths, num_group_tokens=self.num_group_tokens, num_output_groups=self.num_output_groups, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, dropout=self.dropout, attention_dropout=self.attention_dropout, initializer_range=self.initializer_range, ) def create_and_check_model(self, config, pixel_values): model = GroupViTVisionModel(config=config) model.to(torch_device) model.eval() with torch.no_grad(): result = model(pixel_values) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.num_output_groups[-1], self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class GroupViTVisionModelTest(ModelTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as GROUPVIT does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (GroupViTVisionModel,) if is_torch_available() else () test_pruning = False test_torchscript = False test_resize_embeddings = False test_head_masking = False def setUp(self): self.model_tester = GroupViTVisionModelTester(self) self.config_tester = ConfigTester( self, config_class=GroupViTVisionConfig, has_text_modality=False, hidden_size=37 ) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="GroupViT does not use inputs_embeds") def test_inputs_embeds(self): pass @is_flaky(description="The `index` computed with `max()` in `hard_softmax` is not stable.") def test_batching_equivalence(self): super().test_batching_equivalence() def test_model_get_set_embeddings(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) x = model.get_output_embeddings() self.assertTrue(x is None or isinstance(x, nn.Linear)) def test_forward_signature(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) signature = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic arg_names = [*signature.parameters.keys()] expected_arg_names = ["pixel_values"] self.assertListEqual(arg_names[:1], expected_arg_names) def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_attention_outputs(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True seq_len = getattr(self.model_tester, "seq_length", None) expected_num_attention_outputs = sum(g > 0 for g in self.model_tester.num_group_tokens) for model_class in self.all_model_classes: inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = False config.return_dict = True model = model_class._from_config(config, attn_implementation="eager") config = model.config model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.attentions # GroupViT returns attention grouping of each stage self.assertEqual(len(attentions), sum(g > 0 for g in self.model_tester.num_group_tokens)) # check that output_attentions also work using config del inputs_dict["output_attentions"] config.output_attentions = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.attentions # GroupViT returns attention grouping of each stage self.assertEqual(len(attentions), expected_num_attention_outputs) out_len = len(outputs) # Check attention is always last and order is fine inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) added_hidden_states = 1 self.assertEqual(out_len + added_hidden_states, len(outputs)) self_attentions = outputs.attentions # GroupViT returns attention grouping of each stage self.assertEqual(len(self_attentions), expected_num_attention_outputs) for i, self_attn in enumerate(self_attentions): if self_attn is None: continue self.assertListEqual( list(self_attn.shape[-2:]), [ self.model_tester.num_output_groups[i], self.model_tester.num_output_groups[i - 1] if i > 0 else seq_len, ], ) @unittest.skip def test_training(self): pass @unittest.skip def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant_false(self): pass # override since the attention mask from GroupViT is not used to compute loss, thus no grad def test_retain_grad_hidden_states_attentions(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.output_hidden_states = True config.output_attentions = self.has_attentions # no need to test all models as different heads yield the same functionality model_class = self.all_model_classes[0] model = model_class(config) model.to(torch_device) inputs = self._prepare_for_class(inputs_dict, model_class) outputs = model(**inputs) output = outputs[0] if config.is_encoder_decoder: # Seq2Seq models encoder_hidden_states = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() decoder_hidden_states = outputs.decoder_hidden_states[0] decoder_hidden_states.retain_grad() if self.has_attentions: encoder_attentions = outputs.encoder_attentions[0] encoder_attentions.retain_grad() decoder_attentions = outputs.decoder_attentions[0] decoder_attentions.retain_grad() cross_attentions = outputs.cross_attentions[0] cross_attentions.retain_grad() output.flatten()[0].backward(retain_graph=True) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(decoder_hidden_states.grad) if self.has_attentions: self.assertIsNotNone(encoder_attentions.grad) self.assertIsNotNone(decoder_attentions.grad) self.assertIsNotNone(cross_attentions.grad) else: # Encoder-/Decoder-only models hidden_states = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: attentions = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=True) self.assertIsNotNone(hidden_states.grad) if self.has_attentions: self.assertIsNone(attentions.grad) @slow def test_model_from_pretrained(self): model_name = "nvidia/groupvit-gcc-yfcc" model = GroupViTVisionModel.from_pretrained(model_name) self.assertIsNotNone(model) class GroupViTTextModelTester: def __init__( self, parent, batch_size=12, seq_length=7, is_training=True, use_input_mask=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, dropout=0.1, attention_dropout=0.1, max_position_embeddings=512, initializer_range=0.02, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.dropout = dropout self.attention_dropout = attention_dropout self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.scope = scope def prepare_config_and_inputs(self): rng = random.Random(0) input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size, rng=rng) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) if input_mask is not None: batch_size, seq_length = input_mask.shape rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,)) for batch_idx, start_index in enumerate(rnd_start_indices): input_mask[batch_idx, :start_index] = 1 input_mask[batch_idx, start_index:] = 0 config = self.get_config() return config, input_ids, input_mask def get_config(self): return GroupViTTextConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, dropout=self.dropout, attention_dropout=self.attention_dropout, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, ) def create_and_check_model(self, config, input_ids, input_mask): model = GroupViTTextModel(config=config) model.to(torch_device) model.eval() with torch.no_grad(): result = model(input_ids, attention_mask=input_mask) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, input_mask = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class GroupViTTextModelTest(ModelTesterMixin, unittest.TestCase): all_model_classes = (GroupViTTextModel,) if is_torch_available() else () test_pruning = False test_head_masking = False def setUp(self): self.model_tester = GroupViTTextModelTester(self) self.config_tester = ConfigTester(self, config_class=GroupViTTextConfig, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) @unittest.skip def test_training(self): pass @unittest.skip def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant_false(self): pass @unittest.skip(reason="GroupViTTextModel does not use inputs_embeds") def test_inputs_embeds(self): pass @slow def test_model_from_pretrained(self): model_name = "nvidia/groupvit-gcc-yfcc" model = GroupViTTextModel.from_pretrained(model_name) self.assertIsNotNone(model) class GroupViTModelTester: def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True): if text_kwargs is None: text_kwargs = {} if vision_kwargs is None: vision_kwargs = {} self.parent = parent self.text_model_tester = GroupViTTextModelTester(parent, **text_kwargs) self.vision_model_tester = GroupViTVisionModelTester(parent, **vision_kwargs) self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test self.is_training = is_training def prepare_config_and_inputs(self): text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs() vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs() config = self.get_config() return config, input_ids, attention_mask, pixel_values def get_config(self): return GroupViTConfig( text_config=self.text_model_tester.get_config().to_dict(), vision_config=self.vision_model_tester.get_config().to_dict(), projection_dim=64, ) def create_and_check_model(self, config, input_ids, attention_mask, pixel_values): model = GroupViTModel(config).to(torch_device).eval() with torch.no_grad(): result = model(input_ids, pixel_values, attention_mask) self.parent.assertEqual( result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size) ) self.parent.assertEqual( result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size) ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, attention_mask, pixel_values = config_and_inputs inputs_dict = { "input_ids": input_ids, "attention_mask": attention_mask, "pixel_values": pixel_values, "return_loss": True, } return config, inputs_dict @require_torch class GroupViTModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (GroupViTModel,) if is_torch_available() else () pipeline_model_mapping = {"feature-extraction": GroupViTModel} if is_torch_available() else {} test_head_masking = False test_pruning = False test_resize_embeddings = False test_attention_outputs = False def setUp(self): self.model_tester = GroupViTModelTester(self) common_properties = ["projection_dim", "projection_intermediate_dim", "logit_scale_init_value"] self.config_tester = ConfigTester( self, config_class=GroupViTConfig, has_text_modality=False, common_properties=common_properties ) def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_config(self): self.config_tester.run_common_tests() @is_flaky(description="The `index` computed with `max()` in `hard_softmax` is not stable.") def test_batching_equivalence(self): super().test_batching_equivalence() @unittest.skip(reason="hidden_states are tested in individual model tests") def test_hidden_states_output(self): pass @unittest.skip(reason="input_embeds are tested in individual model tests") def test_inputs_embeds(self): pass @unittest.skip(reason="tested in individual model tests") def test_retain_grad_hidden_states_attentions(self): pass @unittest.skip(reason="GroupViTModel does not have input/output embeddings") def test_model_get_set_embeddings(self): pass # override as the `logit_scale` parameter initialization is different for GROUPVIT def test_initialization(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() configs_no_init = _config_zero_init(config) for model_class in self.all_model_classes: model = model_class(config=configs_no_init) for name, param in model.named_parameters(): if param.requires_grad: # check if `logit_scale` is initialized as per the original implementation if name == "logit_scale": self.assertAlmostEqual( param.data.item(), np.log(1 / 0.07), delta=1e-3, msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) else: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item(), [0.0, 1.0], msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) def _create_and_check_torchscript(self, config, inputs_dict): if not self.test_torchscript: self.skipTest(reason="test_torchscript is set to False") configs_no_init = _config_zero_init(config) # To be sure we have no Nan configs_no_init.torchscript = True configs_no_init.return_dict = False for model_class in self.all_model_classes: model = model_class(config=configs_no_init) model.to(torch_device) model.eval() try: input_ids = inputs_dict["input_ids"] pixel_values = inputs_dict["pixel_values"] # GROUPVIT needs pixel_values traced_model = torch.jit.trace(model, (input_ids, pixel_values)) except RuntimeError: self.fail("Couldn't trace module.") with tempfile.TemporaryDirectory() as tmp_dir_name: pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt") try: torch.jit.save(traced_model, pt_file_name) except Exception: self.fail("Couldn't save module.") try: loaded_model = torch.jit.load(pt_file_name) except Exception: self.fail("Couldn't load module.") model.to(torch_device) model.eval() loaded_model.to(torch_device) loaded_model.eval() model_state_dict = model.state_dict() loaded_model_state_dict = loaded_model.state_dict() non_persistent_buffers = {} for key in loaded_model_state_dict: if key not in model_state_dict: non_persistent_buffers[key] = loaded_model_state_dict[key] loaded_model_state_dict = { key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers } self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys())) model_buffers = list(model.buffers()) for non_persistent_buffer in non_persistent_buffers.values(): found_buffer = False for i, model_buffer in enumerate(model_buffers): if torch.equal(non_persistent_buffer, model_buffer): found_buffer = True break self.assertTrue(found_buffer) model_buffers.pop(i) models_equal = True for layer_name, p1 in model_state_dict.items(): p2 = loaded_model_state_dict[layer_name] if p1.data.ne(p2.data).sum() > 0: models_equal = False self.assertTrue(models_equal) def test_load_vision_text_config(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() # Save GroupViTConfig and check if we can load GroupViTVisionConfig from it with tempfile.TemporaryDirectory() as tmp_dir_name: config.save_pretrained(tmp_dir_name) vision_config = GroupViTVisionConfig.from_pretrained(tmp_dir_name) self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict()) # Save GroupViTConfig and check if we can load GroupViTTextConfig from it with tempfile.TemporaryDirectory() as tmp_dir_name: config.save_pretrained(tmp_dir_name) text_config = GroupViTTextConfig.from_pretrained(tmp_dir_name) self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict()) @slow def test_model_from_pretrained(self): model_name = "nvidia/groupvit-gcc-yfcc" model = GroupViTModel.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): url = "http://images.cocodataset.org/val2017/000000039769.jpg" im = Image.open(requests.get(url, stream=True).raw) return im @require_vision @require_torch class GroupViTModelIntegrationTest(unittest.TestCase): @slow def test_inference(self): model_name = "nvidia/groupvit-gcc-yfcc" model = GroupViTModel.from_pretrained(model_name) processor = CLIPProcessor.from_pretrained(model_name) image = prepare_img() inputs = processor( text=["a photo of a cat", "a photo of a dog"], images=image, padding=True, return_tensors="pt" ) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the logits self.assertEqual( outputs.logits_per_image.shape, torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])), ) self.assertEqual( outputs.logits_per_text.shape, torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])), ) expected_logits = torch.tensor([[13.3523, 6.3629]]) torch.testing.assert_close(outputs.logits_per_image, expected_logits, rtol=1e-3, atol=1e-3)
transformers/tests/models/groupvit/test_modeling_groupvit.py/0
{ "file_path": "transformers/tests/models/groupvit/test_modeling_groupvit.py", "repo_id": "transformers", "token_count": 12366 }
544
# 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 copy import unittest from transformers import IBertConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, ) from transformers.models.ibert.modeling_ibert import ( IBertEmbeddings, IntGELU, IntLayerNorm, IntSoftmax, QuantAct, QuantEmbedding, QuantLinear, create_position_ids_from_input_ids, ) class IBertModelTester: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def get_config(self): return IBertConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, initializer_range=self.initializer_range, quant_mode=True, ) def get_pipeline_config(self): config = self.get_config() config.vocab_size = 300 return config def create_and_check_model( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = IBertModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) result = model(input_ids, token_type_ids=token_type_ids) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def create_and_check_for_masked_lm( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = IBertForMaskedLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_for_token_classification( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = IBertForTokenClassification(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def create_and_check_for_multiple_choice( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_choices = self.num_choices model = IBertForMultipleChoice(config=config) model.to(torch_device) model.eval() multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() result = model( multiple_choice_inputs_ids, attention_mask=multiple_choice_input_mask, token_type_ids=multiple_choice_token_type_ids, labels=choice_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) def create_and_check_for_question_answering( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = IBertForQuestionAnswering(config=config) model.to(torch_device) model.eval() result = model( input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, start_positions=sequence_labels, end_positions=sequence_labels, ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class IBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): test_pruning = False test_torchscript = False test_head_masking = False test_resize_embeddings = False all_model_classes = ( ( IBertForMaskedLM, IBertModel, IBertForSequenceClassification, IBertForTokenClassification, IBertForMultipleChoice, IBertForQuestionAnswering, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": IBertModel, "fill-mask": IBertForMaskedLM, "question-answering": IBertForQuestionAnswering, "text-classification": IBertForSequenceClassification, "token-classification": IBertForTokenClassification, "zero-shot": IBertForSequenceClassification, } if is_torch_available() else {} ) def setUp(self): self.model_tester = IBertModelTester(self) self.config_tester = ConfigTester(self, config_class=IBertConfig, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_model_various_embeddings(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() # I-BERT only supports absolute embedding for type in ["absolute"]: config_and_inputs[0].position_embedding_type = type self.model_tester.create_and_check_model(*config_and_inputs) def test_for_masked_lm(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) def test_for_token_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*config_and_inputs) def test_for_multiple_choice(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) def test_for_question_answering(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*config_and_inputs) @slow def test_model_from_pretrained(self): model_name = "kssteven/ibert-roberta-base" model = IBertModel.from_pretrained(model_name) self.assertIsNotNone(model) def test_create_position_ids_respects_padding_index(self): """This is a regression test for https://github.com/huggingface/transformers/issues/1761 The position ids should be masked with the embedding object's padding index. Therefore, the first available non-padding position index is IBertEmbeddings.padding_idx + 1 """ config = self.model_tester.prepare_config_and_inputs()[0] model = IBertEmbeddings(config=config) input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]]) expected_positions = torch.as_tensor( [[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]] ) position_ids = create_position_ids_from_input_ids(input_ids, model.padding_idx) self.assertEqual(position_ids.shape, expected_positions.shape) self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) def test_create_position_ids_from_inputs_embeds(self): """This is a regression test for https://github.com/huggingface/transformers/issues/1761 The position ids should be masked with the embedding object's padding index. Therefore, the first available non-padding position index is IBertEmbeddings.padding_idx + 1 """ config = self.model_tester.prepare_config_and_inputs()[0] embeddings = IBertEmbeddings(config=config) inputs_embeds = torch.empty(2, 4, 30) expected_single_positions = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions]) position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds) self.assertEqual(position_ids.shape, expected_positions.shape) self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) # Override def test_model_get_set_embeddings(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) self.assertIsInstance(model.get_input_embeddings(), QuantEmbedding) model.set_input_embeddings(nn.Embedding(10, 10)) x = model.get_output_embeddings() self.assertTrue(x is None or isinstance(x, nn.Linear)) # Override def test_feed_forward_chunking(self): pass # I-BERT does not support chunking # Override def test_inputs_embeds(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) if not self.is_encoder_decoder: input_ids = inputs["input_ids"] del inputs["input_ids"] else: encoder_input_ids = inputs["input_ids"] decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) del inputs["input_ids"] inputs.pop("decoder_input_ids", None) wte = model.get_input_embeddings() if not self.is_encoder_decoder: embed, embed_scaling_factor = wte(input_ids) inputs["inputs_embeds"] = embed else: inputs["inputs_embeds"] = wte(encoder_input_ids) inputs["decoder_inputs_embeds"] = wte(decoder_input_ids) with torch.no_grad(): model(**inputs)[0] @unittest.skip(reason="ibert overrides scaling to None if inputs_embeds") def test_inputs_embeds_matches_input_ids(self): pass @require_torch class IBertModelIntegrationTest(unittest.TestCase): def test_quant_embedding(self): weight_bit = 8 embedding = QuantEmbedding(2, 4, quant_mode=True, weight_bit=weight_bit) embedding_weight = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]]) embedding.weight = nn.Parameter(embedding_weight) expected_scaling_factor = embedding_weight.abs().max() / (2 ** (weight_bit - 1) - 1) x, x_scaling_factor = embedding(torch.tensor(0)) y, y_scaling_factor = embedding(torch.tensor(1)) # scaling factor should follow the symmetric quantization rule self.assertTrue(torch.allclose(x_scaling_factor, expected_scaling_factor, atol=1e-4)) self.assertTrue(torch.allclose(x_scaling_factor, expected_scaling_factor, atol=1e-4)) self.assertTrue(torch.allclose(y_scaling_factor, expected_scaling_factor, atol=1e-4)) # quantization error should not exceed the scaling factor self.assertTrue(torch.allclose(x, embedding_weight[0], atol=expected_scaling_factor)) self.assertTrue(torch.allclose(y, embedding_weight[1], atol=expected_scaling_factor)) def test_quant_act(self): def _test_range(): act = QuantAct(activation_bit, act_range_momentum, quant_mode=True) # First pass x = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]]) x_scaling_factor = torch.tensor(1.0) y, y_scaling_factor = act(x, x_scaling_factor) y_int = y / y_scaling_factor # After the first pass, x_min and x_max should be initialized with x.min() and x.max() expected_x_min, expected_x_max = x.min(), x.max() self.assertTrue(torch.allclose(act.x_min, expected_x_min, atol=1e-4)) self.assertTrue(torch.allclose(act.x_max, expected_x_max, atol=1e-4)) # scaling factor should follow the symmetric quantization rule expected_range = torch.max(expected_x_min.abs(), expected_x_max.abs()) expected_scaling_factor = expected_range / (2 ** (activation_bit - 1) - 1) self.assertTrue(torch.allclose(y_scaling_factor, expected_scaling_factor, atol=1e-4)) # quantization error should not exceed the scaling factor self.assertTrue(torch.allclose(x, y, atol=expected_scaling_factor)) # output should be integer self.assertTrue(torch.allclose(y_int, y_int.round(), atol=1e-4)) # Second Pass x = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]]) * 2 x_scaling_factor = torch.tensor(1.0) y, y_scaling_factor = act(x, x_scaling_factor) y_int = y / y_scaling_factor # From the second pass, x_min and x_max should be updated with moving average expected_x_min = expected_x_min * act_range_momentum + x.min() * (1 - act_range_momentum) expected_x_max = expected_x_max * act_range_momentum + x.max() * (1 - act_range_momentum) self.assertTrue(torch.allclose(act.x_min, expected_x_min, atol=1e-4)) self.assertTrue(torch.allclose(act.x_max, expected_x_max, atol=1e-4)) # scaling factor should follow the symmetric quantization rule expected_range = torch.max(expected_x_min.abs(), expected_x_max.abs()) expected_scaling_factor = expected_range / (2 ** (activation_bit - 1) - 1) self.assertTrue(torch.allclose(y_scaling_factor, expected_scaling_factor, atol=1e-4)) # quantization error should not exceed the scaling factor x = x.clamp(min=-expected_range, max=expected_range) self.assertTrue(torch.allclose(x, y, atol=expected_scaling_factor)) # output should be integer self.assertTrue(torch.allclose(y_int, y_int.round(), atol=1e-4)) # Third pass, with eval() act.eval() x = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]]) * 3 # In eval mode, min/max and scaling factor must be fixed self.assertTrue(torch.allclose(act.x_min, expected_x_min, atol=1e-4)) self.assertTrue(torch.allclose(act.x_max, expected_x_max, atol=1e-4)) self.assertTrue(torch.allclose(y_scaling_factor, expected_scaling_factor, atol=1e-4)) def _test_identity(): # test if identity and identity_scaling_factor are given # should add the input values act = QuantAct(activation_bit, act_range_momentum, quant_mode=True) x = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]]) y = torch.tensor([[6.0, -7.0, 1.0, -2.0], [3.0, -4.0, -8.0, 5.0]]) x_scaling_factor = torch.tensor(1.0) y_scaling_factor = torch.tensor(0.5) z, z_scaling_factor = act(x, x_scaling_factor, y, y_scaling_factor) z_int = z / z_scaling_factor self.assertTrue(torch.allclose(x + y, z, atol=0.1)) self.assertTrue(torch.allclose(z_int, z_int.round(), atol=1e-4)) activation_bit = 8 act_range_momentum = 0.95 _test_range() _test_identity() def test_quant_linear(self): def _test(per_channel): linear_q = QuantLinear(2, 4, quant_mode=True, per_channel=per_channel, weight_bit=weight_bit) linear_dq = QuantLinear(2, 4, quant_mode=False, per_channel=per_channel, weight_bit=weight_bit) linear_weight = torch.tensor([[-1.0, 2.0, 3.0, -4.0], [5.0, -6.0, -7.0, 8.0]]).T linear_q.weight = nn.Parameter(linear_weight) linear_dq.weight = nn.Parameter(linear_weight) q, q_scaling_factor = linear_q(x, x_scaling_factor) q_int = q / q_scaling_factor dq, dq_scaling_factor = linear_dq(x, x_scaling_factor) if per_channel: q_max = linear_weight.abs().max(dim=1).values else: q_max = linear_weight.abs().max() expected_scaling_factor = q_max / (2 ** (weight_bit - 1) - 1) # scaling factor should follow the symmetric quantization rule self.assertTrue(torch.allclose(linear_q.fc_scaling_factor, expected_scaling_factor, atol=1e-4)) # output of the normal linear layer and the quantized linear layer should be similar self.assertTrue(torch.allclose(q, dq, atol=0.5)) # output of the quantized linear layer should be integer self.assertTrue(torch.allclose(q_int, q_int.round(), atol=1e-4)) weight_bit = 8 x = torch.tensor([[2.0, -5.0], [-3.0, 4.0]]) x_scaling_factor = torch.tensor([1.0]) _test(True) _test(False) def test_int_gelu(self): gelu_q = IntGELU(quant_mode=True) gelu_dq = nn.GELU() x_int = torch.arange(-10000, 10001, 1) x_scaling_factor = torch.tensor(0.001) x = x_int * x_scaling_factor q, q_scaling_factor = gelu_q(x, x_scaling_factor) q_int = q / q_scaling_factor dq = gelu_dq(x) # output of the normal GELU and the quantized GELU should be similar self.assertTrue(torch.allclose(q, dq, atol=0.5)) # output of the quantized GELU layer should be integer self.assertTrue(torch.allclose(q_int, q_int.round(), atol=1e-4)) def test_force_dequant_gelu(self): x_int = torch.arange(-10000, 10001, 1) x_scaling_factor = torch.tensor(0.001) x = x_int * x_scaling_factor gelu_dq = IntGELU(quant_mode=False) gelu_fdqs_dict = { True: [ IntGELU(quant_mode=True, force_dequant="nonlinear"), IntGELU(quant_mode=True, force_dequant="gelu"), ], False: [ IntGELU(quant_mode=True, force_dequant="none"), IntGELU(quant_mode=True, force_dequant="softmax"), IntGELU(quant_mode=True, force_dequant="layernorm"), ], } dq, dq_scaling_factor = gelu_dq(x, x_scaling_factor) for label, gelu_fdqs in gelu_fdqs_dict.items(): for gelu_fdq in gelu_fdqs: q, q_scaling_factor = gelu_fdq(x, x_scaling_factor) if label: self.assertTrue(torch.allclose(q, dq, atol=1e-4)) else: self.assertFalse(torch.allclose(q, dq, atol=1e-4)) def test_int_softmax(self): output_bit = 8 softmax_q = IntSoftmax(output_bit, quant_mode=True) softmax_dq = nn.Softmax() def _test(array): x_int = torch.tensor(array) x_scaling_factor = torch.tensor(0.1) x = x_int * x_scaling_factor q, q_scaling_factor = softmax_q(x, x_scaling_factor) q_int = q / q_scaling_factor dq = softmax_dq(x) # output of the normal Softmax and the quantized Softmax should be similar self.assertTrue(torch.allclose(q, dq, atol=0.5)) # output of the quantized GELU layer should be integer self.assertTrue(torch.allclose(q_int, q_int.round(), atol=1e-4)) # Output of the quantize Softmax should not exceed the output_bit self.assertTrue(q.abs().max() < 2**output_bit) array = [[i + j for j in range(10)] for i in range(-10, 10)] _test(array) array = [[i + j for j in range(50)] for i in range(-10, 10)] _test(array) array = [[i + 100 * j for j in range(2)] for i in range(-10, 10)] _test(array) def test_force_dequant_softmax(self): output_bit = 8 array = [[i + j for j in range(10)] for i in range(-10, 10)] x_int = torch.tensor(array) x_scaling_factor = torch.tensor(0.1) x = x_int * x_scaling_factor softmax_dq = IntSoftmax(output_bit, quant_mode=False) softmax_fdqs_dict = { True: [ IntSoftmax(output_bit, quant_mode=True, force_dequant="nonlinear"), IntSoftmax(output_bit, quant_mode=True, force_dequant="softmax"), ], False: [ IntSoftmax(output_bit, quant_mode=True, force_dequant="none"), IntSoftmax(output_bit, quant_mode=True, force_dequant="gelu"), IntSoftmax(output_bit, quant_mode=True, force_dequant="layernorm"), ], } dq, dq_scaling_factor = softmax_dq(x, x_scaling_factor) for label, softmax_fdqs in softmax_fdqs_dict.items(): for softmax_fdq in softmax_fdqs: q, q_scaling_factor = softmax_fdq(x, x_scaling_factor) if label: self.assertTrue(torch.allclose(q, dq, atol=1e-4)) else: self.assertFalse(torch.allclose(q, dq, atol=1e-4)) def test_int_layernorm(self): output_bit = 8 # some random matrix array = [[[i * j * j + j for j in range(5, 15)]] for i in range(-10, 10)] x_int = torch.tensor(array) x_scaling_factor = torch.tensor(0.1) x = x_int * x_scaling_factor ln_q = IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit) ln_dq = nn.LayerNorm(x.shape[1:], 1e-5) ln_q.weight = nn.Parameter(torch.ones(x.shape[1:])) ln_q.bias = nn.Parameter(torch.ones(x.shape[1:])) ln_dq.weight = nn.Parameter(torch.ones(x.shape[1:])) ln_dq.bias = nn.Parameter(torch.ones(x.shape[1:])) q, q_scaling_factor = ln_q(x, x_scaling_factor) q_int = q / q_scaling_factor dq = ln_dq(x) # output of the normal LN and the quantized LN should be similar self.assertTrue(torch.allclose(q, dq, atol=0.5)) # output of the quantized GELU layer should be integer self.assertTrue(torch.allclose(q_int, q_int.round(), atol=1e-4)) def test_force_dequant_layernorm(self): output_bit = 8 array = [[[i * j * j + j for j in range(5, 15)]] for i in range(-10, 10)] x_int = torch.tensor(array) x_scaling_factor = torch.tensor(0.1) x = x_int * x_scaling_factor ln_dq = IntLayerNorm(x.shape[1:], 1e-5, quant_mode=False, output_bit=output_bit) ln_fdqs_dict = { True: [ IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit, force_dequant="nonlinear"), IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit, force_dequant="layernorm"), ], False: [ IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit, force_dequant="none"), IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit, force_dequant="gelu"), IntLayerNorm(x.shape[1:], 1e-5, quant_mode=True, output_bit=output_bit, force_dequant="softmax"), ], } ln_dq.weight = nn.Parameter(torch.ones(x.shape[1:])) ln_dq.bias = nn.Parameter(torch.ones(x.shape[1:])) dq, dq_scaling_factor = ln_dq(x, x_scaling_factor) for label, ln_fdqs in ln_fdqs_dict.items(): for ln_fdq in ln_fdqs: ln_fdq.weight = nn.Parameter(torch.ones(x.shape[1:])) ln_fdq.bias = nn.Parameter(torch.ones(x.shape[1:])) q, q_scaling_factor = ln_fdq(x, x_scaling_factor) if label: self.assertTrue(torch.allclose(q, dq, atol=1e-4)) else: self.assertFalse(torch.allclose(q, dq, atol=1e-4)) def quantize(self, model): # Helper function that quantizes the given model # Recursively convert all the `quant_mode` attributes as `True` if hasattr(model, "quant_mode"): model.quant_mode = True elif isinstance(model, nn.Sequential): for n, m in model.named_children(): self.quantize(m) elif isinstance(model, nn.ModuleList): for n in model: self.quantize(n) else: for attr in dir(model): mod = getattr(model, attr) if isinstance(mod, nn.Module) and mod != model: self.quantize(mod) @slow def test_inference_masked_lm(self): # I-BERT should be "equivalent" to RoBERTa if not quantized # Test coped from `test_modeling_roberta.py` model = IBertForMaskedLM.from_pretrained("kssteven/ibert-roberta-base") input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) output = model(input_ids)[0] expected_shape = torch.Size((1, 11, 50265)) self.assertEqual(output.shape, expected_shape) expected_slice = torch.tensor( [[[33.8802, -4.3103, 22.7761], [4.6539, -2.8098, 13.6253], [1.8228, -3.6898, 8.8600]]] ) self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4)) # I-BERT should be "similar" to RoBERTa if quantized self.quantize(model) output = model(input_ids)[0] self.assertEqual(output.shape, expected_shape) self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=0.1)) @slow def test_inference_classification_head(self): # I-BERT should be "equivalent" to RoBERTa if not quantized # Test coped from `test_modeling_roberta.py` model = IBertForSequenceClassification.from_pretrained("kssteven/ibert-roberta-large-mnli") input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) output = model(input_ids)[0] expected_shape = torch.Size((1, 3)) self.assertEqual(output.shape, expected_shape) expected_tensor = torch.tensor([[-0.9469, 0.3913, 0.5118]]) self.assertTrue(torch.allclose(output, expected_tensor, atol=1e-4)) # I-BERT should be "similar" to RoBERTa if quantized self.quantize(model) output = model(input_ids)[0] self.assertEqual(output.shape, expected_shape) self.assertTrue(torch.allclose(output, expected_tensor, atol=0.1))
transformers/tests/models/ibert/test_modeling_ibert.py/0
{ "file_path": "transformers/tests/models/ibert/test_modeling_ibert.py", "repo_id": "transformers", "token_count": 14901 }
545
# Copyright 2021 HuggingFace Inc. # # 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 json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import AutoImageProcessor from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class ImageGPTImageProcessingTester: def __init__( self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_normalize=True, ): size = size if size is not None else {"height": 18, "width": 18} self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_resize = do_resize self.size = size self.do_normalize = do_normalize def prepare_image_processor_dict(self): return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8866443634033203, 0.6618829369544983, 0.3891746401786804], [-0.6042559146881104, -0.02295008860528469, 0.5423797369003296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } def expected_output_image_shape(self, images): return (self.size["height"] * self.size["width"],) def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision class ImageGPTImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = ImageGPTImageProcessor if is_vision_available() else None def setUp(self): super().setUp() self.image_processor_tester = ImageGPTImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): image_processing = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processing, "clusters")) self.assertTrue(hasattr(image_processing, "do_resize")) self.assertTrue(hasattr(image_processing, "size")) self.assertTrue(hasattr(image_processing, "do_normalize")) def test_image_processor_from_dict_with_kwargs(self): image_processor = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size, {"height": 18, "width": 18}) image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42) self.assertEqual(image_processor.size, {"height": 42, "width": 42}) def test_image_processor_to_json_string(self): image_processor = self.image_processing_class(**self.image_processor_dict) obj = json.loads(image_processor.to_json_string()) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(value, obj[key])) else: self.assertEqual(obj[key], value) def test_image_processor_to_json_file(self): image_processor_first = self.image_processing_class(**self.image_processor_dict) with tempfile.TemporaryDirectory() as tmpdirname: json_file_path = os.path.join(tmpdirname, "image_processor.json") image_processor_first.to_json_file(json_file_path) image_processor_second = self.image_processing_class.from_json_file(json_file_path).to_dict() image_processor_first = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(value, image_processor_second[key])) else: self.assertEqual(value, value) def test_image_processor_from_and_save_pretrained(self): for image_processing_class in self.image_processor_list: image_processor_first = self.image_processing_class(**self.image_processor_dict) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(tmpdirname) image_processor_second = self.image_processing_class.from_pretrained(tmpdirname).to_dict() image_processor_first = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(value, image_processor_second[key])) else: self.assertEqual(value, value) def test_image_processor_save_load_with_autoimageprocessor(self): for image_processing_class in self.image_processor_list: image_processor_first = image_processing_class(**self.image_processor_dict) with tempfile.TemporaryDirectory() as tmpdirname: saved_file = image_processor_first.save_pretrained(tmpdirname)[0] check_json_file_has_correct_format(saved_file) image_processor_second = AutoImageProcessor.from_pretrained(tmpdirname) image_processor_first = image_processor_first.to_dict() image_processor_second = image_processor_second.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(value, image_processor_second[key])) else: self.assertEqual(value, value) @unittest.skip(reason="ImageGPT requires clusters at initialization") def test_init_without_params(self): pass # Override the test from ImageProcessingTestMixin as ImageGPT model takes input_ids as input def test_call_pil(self): # Initialize image_processing image_processing = self.image_processing_class(**self.image_processor_dict) # create random PIL images image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False) for image in image_inputs: self.assertIsInstance(image, Image.Image) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").input_ids expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(encoded_images) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").input_ids self.assertEqual( tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) ) # Override the test from ImageProcessingTestMixin as ImageGPT model takes input_ids as input def test_call_numpy(self): # Initialize image_processing image_processing = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) for image in image_inputs: self.assertIsInstance(image, np.ndarray) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").input_ids expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(encoded_images) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").input_ids self.assertEqual( tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) ) @unittest.skip(reason="ImageGPT assumes clusters for 3 channels") def test_call_numpy_4_channels(self): pass # Override the test from ImageProcessingTestMixin as ImageGPT model takes input_ids as input def test_call_pytorch(self): # Initialize image_processing image_processing = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) for image in image_inputs: self.assertIsInstance(image, torch.Tensor) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").input_ids self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").input_ids self.assertEqual( tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape), ) def prepare_images(): # we use revision="refs/pr/1" until the PR is merged # https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1 dataset = load_dataset("hf-internal-testing/fixtures_image_utils", split="test", revision="refs/pr/1") image1 = dataset[4]["image"] image2 = dataset[5]["image"] images = [image1, image2] return images @require_vision @require_torch class ImageGPTImageProcessorIntegrationTest(unittest.TestCase): @slow def test_image(self): image_processing = ImageGPTImageProcessor.from_pretrained("openai/imagegpt-small") images = prepare_images() # test non-batched encoding = image_processing(images[0], return_tensors="pt") self.assertIsInstance(encoding.input_ids, torch.LongTensor) self.assertEqual(encoding.input_ids.shape, (1, 1024)) expected_slice = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist(), expected_slice) # test batched encoding = image_processing(images, return_tensors="pt") self.assertIsInstance(encoding.input_ids, torch.LongTensor) self.assertEqual(encoding.input_ids.shape, (2, 1024)) expected_slice = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist(), expected_slice)
transformers/tests/models/imagegpt/test_image_processing_imagegpt.py/0
{ "file_path": "transformers/tests/models/imagegpt/test_image_processing_imagegpt.py", "repo_id": "transformers", "token_count": 4785 }
546
# Copyright 2024 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. """Testing suite for the PyTorch Jamba model.""" import math import tempfile import unittest import pytest from transformers import AutoTokenizer, JambaConfig, is_torch_available from transformers.testing_utils import ( DeviceProperties, Expectations, get_device_properties, require_bitsandbytes, require_flash_attn, require_torch, require_torch_gpu, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( JambaForCausalLM, JambaForSequenceClassification, JambaModel, ) from transformers.models.jamba.modeling_jamba import ( HybridMambaAttentionDynamicCache, ) class JambaConfigTester(ConfigTester): def _create_attn_config(self, attn_layer_offset: int, attn_layer_period: int): _input_dict = self.inputs_dict.copy() _input_dict["attn_layer_offset"] = attn_layer_offset _input_dict["attn_layer_period"] = attn_layer_period return self.config_class(**_input_dict) def _create_expert_config(self, expert_layer_offset: int, expert_layer_period: int): _input_dict = self.inputs_dict.copy() _input_dict["expert_layer_offset"] = expert_layer_offset _input_dict["expert_layer_period"] = expert_layer_period return self.config_class(**_input_dict) def test_attn_offsets(self): self._create_attn_config(attn_layer_offset=0, attn_layer_period=4) self._create_attn_config(attn_layer_offset=1, attn_layer_period=4) self._create_attn_config(attn_layer_offset=2, attn_layer_period=4) self._create_attn_config(attn_layer_offset=3, attn_layer_period=4) with self.parent.assertRaises(ValueError): self._create_attn_config(attn_layer_offset=4, attn_layer_period=4) with self.parent.assertRaises(ValueError): self._create_attn_config(attn_layer_offset=5, attn_layer_period=4) def test_expert_offsets(self): self._create_expert_config(expert_layer_offset=0, expert_layer_period=4) self._create_expert_config(expert_layer_offset=1, expert_layer_period=4) self._create_expert_config(expert_layer_offset=2, expert_layer_period=4) self._create_expert_config(expert_layer_offset=3, expert_layer_period=4) with self.parent.assertRaises(ValueError): self._create_expert_config(expert_layer_offset=4, expert_layer_period=4) with self.parent.assertRaises(ValueError): self._create_expert_config(expert_layer_offset=5, expert_layer_period=4) def test_jamba_offset_properties(self): self.test_attn_offsets() self.test_expert_offsets() def run_common_tests(self): self.test_jamba_offset_properties() return super().run_common_tests() class JambaModelTester: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=5, attn_layer_offset=1, attn_layer_period=8, num_attention_heads=4, num_key_value_heads=2, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.attn_layer_offset = attn_layer_offset self.attn_layer_period = attn_layer_period self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def get_config(self): return JambaConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, attn_layer_offset=self.attn_layer_offset, attn_layer_period=self.attn_layer_period, num_attention_heads=self.num_attention_heads, num_key_value_heads=self.num_key_value_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=True, initializer_range=self.initializer_range, use_mamba_kernels=False, num_experts=2, ) def prepare_config_and_inputs_for_decoder(self): ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = self.prepare_config_and_inputs() config.is_decoder = True return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def create_and_check_model(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels): model = JambaModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_for_causal_lm( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ): model = JambaForCausalLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=token_labels) result = model(input_ids, attention_mask=input_mask) result = model(input_ids, labels=token_labels) result = model(input_ids) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_decoder_model_past_large_inputs( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ): config.is_decoder = True config.add_cross_attention = True model = JambaForCausalLM(config=config) model.to(torch_device) model.eval() # first forward pass # Attention: Jamba needs the cache to be initialized to return a cache! past_key_values = HybridMambaAttentionDynamicCache( config, input_ids.shape[0], model.dtype, device=model.device ) outputs = model( input_ids, attention_mask=input_mask, past_key_values=past_key_values, use_cache=True, ) past_key_values = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) # append to next input_ids and next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) output_from_no_past = model( next_input_ids, attention_mask=next_attention_mask, output_hidden_states=True, )["hidden_states"][0] output_from_past = model( next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values, output_hidden_states=True, cache_position=torch.arange( input_ids.shape[1], input_ids.shape[1] + next_tokens.shape[1], device=model.device ), )["hidden_states"][0] # select random slice random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach() output_from_past_slice = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) def create_and_check_for_sequence_classification( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = JambaForSequenceClassification(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class JambaModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( JambaModel, JambaForCausalLM, JambaForSequenceClassification, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": JambaModel, "text-classification": JambaForSequenceClassification, "text-generation": JambaForCausalLM, "zero-shot": JambaForSequenceClassification, } if is_torch_available() else {} ) test_headmasking = False test_pruning = False def _check_past_key_values_for_generate(self, batch_size, decoder_past_key_values, cache_length, config): self.assertIsInstance(decoder_past_key_values, HybridMambaAttentionDynamicCache) # (batch, head, seq_length, head_features) expected_shape = ( batch_size, config.num_key_value_heads if hasattr(config, "num_key_value_heads") else config.num_attention_heads, cache_length, config.hidden_size // config.num_attention_heads, ) self.assertListEqual( [key_tensor.shape for key_tensor in decoder_past_key_values.key_cache], [expected_shape] * len(decoder_past_key_values.key_cache), ) self.assertListEqual( [value_cache.shape for value_cache in decoder_past_key_values.value_cache], [expected_shape] * len(decoder_past_key_values.value_cache), ) def setUp(self): self.model_tester = JambaModelTester(self) self.config_tester = JambaConfigTester(self, config_class=JambaConfig, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_for_casual_lm(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*config_and_inputs) def test_for_sequence_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) def test_decoder_model_past_with_large_inputs(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) def test_load_balancing_loss(self): r""" Let's make sure we can actually compute the loss and do a backward on it. """ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() config.num_labels = 3 config.num_experts = 16 config.output_router_logits = True input_ids = input_dict["input_ids"] attention_mask = input_ids.ne(config.pad_token_id).to(torch_device) model = JambaForCausalLM(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=attention_mask) bs, seqlen = input_ids.shape self.assertEqual(result.router_logits[0].shape, (bs * seqlen, config.num_experts)) torch.testing.assert_close(result.aux_loss.cpu(), torch.tensor(2, dtype=torch.float32), rtol=1e-2, atol=1e-2) # First, we make sure that adding padding tokens doesn't change the loss # loss(input_ids, attention_mask=None) == loss(input_ids + padding, attention_mask=attention_mask_with_padding) pad_length = 1000 # Add padding tokens to input_ids padding_block = config.pad_token_id * torch.ones(input_ids.shape[0], pad_length, dtype=torch.int32).to( torch_device ) padded_input_ids = torch.cat((padding_block, input_ids), dim=1) # this is to simulate padding to the left padded_attention_mask = padded_input_ids.ne(config.pad_token_id).to(torch_device) padded_result = model(padded_input_ids, attention_mask=padded_attention_mask) torch.testing.assert_close(result.aux_loss.cpu(), padded_result.aux_loss.cpu(), rtol=1e-4, atol=1e-4) # We make sure that the loss of including padding tokens != the loss without padding tokens # if attention_mask=None --> we don't exclude padding tokens include_padding_result = model(padded_input_ids, attention_mask=None) # This is to mimic torch.testing.assert_not_close self.assertNotAlmostEqual(include_padding_result.aux_loss.item(), result.aux_loss.item()) def test_initialization(self): r""" Overriding the test_initialization test as the A_log and D params of the Mamba block are initialized differently """ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() configs_no_init = _config_zero_init(config) for model_class in self.all_model_classes: model = model_class(config=configs_no_init) for name, param in model.named_parameters(): if param.requires_grad: if "A_log" in name: A = torch.arange(1, config.mamba_d_state + 1, dtype=torch.float32)[None, :] A = A.expand(config.mamba_expand * config.hidden_size, -1).contiguous() torch.testing.assert_close(param.data, torch.log(A), rtol=1e-5, atol=1e-5) elif "D" in name: # check if it's a ones like torch.testing.assert_close(param.data, torch.ones_like(param.data), rtol=1e-5, atol=1e-5) else: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item(), [0.0, 1.0], msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) def test_mismatched_shapes_have_properly_initialized_weights(self): r""" Overriding the test_mismatched_shapes_have_properly_initialized_weights test because A_log and D params of the Mamba block are initialized differently and we tested that in test_initialization """ self.skipTest(reason="Cumbersome and redundant for Jamba") def test_attention_outputs(self): r""" Overriding the test_attention_outputs test as the Jamba model outputs attention only for its attention layers """ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True seq_len = getattr(self.model_tester, "seq_length", None) encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) expected_num_attentions = math.ceil( (self.model_tester.num_hidden_layers - self.model_tester.attn_layer_offset) / self.model_tester.attn_layer_period ) for model_class in self.all_model_classes: inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = False config.return_dict = True model = model_class._from_config(config, attn_implementation="eager") config = model.config model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.attentions self.assertEqual(len(attentions), expected_num_attentions) # check that output_attentions also work using config del inputs_dict["output_attentions"] config.output_attentions = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.attentions self.assertEqual(len(attentions), expected_num_attentions) self.assertListEqual( list(attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], ) out_len = len(outputs) # Check attention is always last and order is fine inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) added_hidden_states = 1 self.assertEqual(out_len + added_hidden_states, len(outputs)) self_attentions = outputs.attentions self.assertEqual(len(self_attentions), expected_num_attentions) self.assertListEqual( list(self_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], ) @require_flash_attn @require_torch_gpu @require_bitsandbytes @pytest.mark.flash_attn_test @slow def test_flash_attn_2_fp32_ln(self): r""" Overriding the test_flash_attn_2_fp32_ln test as the Jamba model, like Mixtral, doesn't support right padding + use cache with FA2 """ for model_class in self.all_generative_model_classes: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() model = model_class(config) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) dummy_input = inputs_dict[model.main_input_name] dummy_attention_mask = inputs_dict.get("attention_mask", torch.ones_like(dummy_input)) # NOTE: Jamba does not support right padding + use_cache with FA2. dummy_attention_mask[:, -1] = 1 model = model_class.from_pretrained( tmpdirname, dtype=torch.float16, attn_implementation="flash_attention_2", load_in_4bit=True, ) for _, param in model.named_parameters(): # upcast only layer norms if (param.dtype == torch.float16) or (param.dtype == torch.bfloat16): param.data = param.data.to(torch.float32) _ = model(dummy_input) # with attention mask _ = model(dummy_input, attention_mask=dummy_attention_mask) @require_flash_attn @require_torch_gpu @pytest.mark.flash_attn_test @slow def test_flash_attn_2_inference_equivalence_right_padding(self): r""" Overriding the test_flash_attn_2_inference_padding_right test as the Jamba model, like Mixtral, doesn't support right padding + use cache with FA2 """ self.skipTest(reason="Jamba flash attention does not support right padding") @require_torch class JambaModelIntegrationTest(unittest.TestCase): model = None tokenizer = None # This variable is used to determine which acclerator are we using for our runners (e.g. A10 or T4) # Depending on the hardware we get different logits / generations device_properties: DeviceProperties = (None, None, None) @classmethod def setUpClass(cls): model_id = "ai21labs/Jamba-tiny-dev" cls.model = JambaForCausalLM.from_pretrained( model_id, dtype=torch.bfloat16, ) cls.tokenizer = AutoTokenizer.from_pretrained(model_id) cls.device_properties = get_device_properties() @slow def test_simple_generate(self): # ("cuda", 8) for A100/A10, and ("cuda", 7) for T4. # # considering differences in hardware processing and potential deviations in generated text. # fmt: off EXPECTED_TEXTS = Expectations( { ("cuda", 7): "<|startoftext|>Hey how are you doing on this lovely evening? Canyon rins hugaughter glamour Rutgers Singh<|reserved_797|>cw algunas", ("cuda", 8): "<|startoftext|>Hey how are you doing on this lovely evening? I'm so glad you're here.", ("rocm", 9): "<|startoftext|>Hey how are you doing on this lovely evening? Canyon rins hugaughter glamour Rutgers Singh Hebrew llam bb", } ) # fmt: on expected_sentence = EXPECTED_TEXTS.get_expectation() self.model.to(torch_device) input_ids = self.tokenizer("Hey how are you doing on this lovely evening?", return_tensors="pt")[ "input_ids" ].to(torch_device) out = self.model.generate(input_ids, do_sample=False, max_new_tokens=10) output_sentence = self.tokenizer.decode(out[0, :]) self.assertEqual(output_sentence, expected_sentence) # TODO: there are significant differences in the logits across major cuda versions, which shouldn't exist if self.device_properties[0] == "cuda" and self.device_properties[1] == 8: with torch.no_grad(): logits = self.model(input_ids=input_ids).logits EXPECTED_LOGITS_NO_GRAD = torch.tensor( [ -7.6875, -7.6562, 8.9375, -7.7812, -7.4062, -7.9688, -8.3125, -7.4062, -7.8125, -8.1250, -7.8125, -7.3750, -7.8438, -7.5000, -8.0625, -8.0625, -7.5938, -7.9688, -8.2500, -7.5625, -7.7500, -7.7500, -7.6562, -7.6250, -8.1250, -8.0625, -8.1250, -7.8750, -8.1875, -8.2500, -7.5938, -8.0000, -7.5000, -7.7500, -7.9375, -7.4688, -8.0625, -7.3438, -8.0000, -7.5000 ] , dtype=torch.float32) # fmt: skip torch.testing.assert_close(logits[0, -1, :40].cpu(), EXPECTED_LOGITS_NO_GRAD, rtol=1e-3, atol=1e-3) @slow def test_simple_batched_generate_with_padding(self): # ("cuda", 8) for A100/A10, and ("cuda", 7) for T4. # # considering differences in hardware processing and potential deviations in generated text. # fmt: off EXPECTED_TEXTS = Expectations( { ("cuda", 7): ["<|startoftext|>Hey how are you doing on this lovely evening? Canyon rins hugaughter glamour Rutgers Singh Hebrew cases Cats", "<|pad|><|pad|><|pad|><|pad|><|pad|><|pad|><|startoftext|>Tell me a storyptus Nets Madison El chamadamodern updximVaparsed",], ("cuda", 8): ["<|startoftext|>Hey how are you doing on this lovely evening? I'm so glad you're here.", "<|pad|><|pad|><|pad|><|pad|><|pad|><|pad|><|startoftext|>Tell me a story about a woman who was born in the United States",], ("rocm", 9): ["<|startoftext|>Hey how are you doing on this lovely evening? Canyon rins hugaughter glamour Rutgers Singh<|reserved_797|>cw algunas", "<|pad|><|pad|><|pad|><|pad|><|pad|><|pad|><|startoftext|>Tell me a storyptus Nets Madison El chamadamodern updximVaparsed",], } ) # fmt: on expected_sentences = EXPECTED_TEXTS.get_expectation() self.model.to(torch_device) inputs = self.tokenizer( ["Hey how are you doing on this lovely evening?", "Tell me a story"], padding=True, return_tensors="pt" ).to(torch_device) out = self.model.generate(**inputs, do_sample=False, max_new_tokens=10) output_sentences = self.tokenizer.batch_decode(out) self.assertEqual(output_sentences[0], expected_sentences[0]) self.assertEqual(output_sentences[1], expected_sentences[1]) # TODO: there are significant differences in the logits across major cuda versions, which shouldn't exist if self.device_properties[0] == "cuda" and self.device_properties[1] == 8: with torch.no_grad(): logits = self.model(input_ids=inputs["input_ids"]).logits # TODO fix logits EXPECTED_LOGITS_NO_GRAD_0 = torch.tensor( [ -7.7188, -7.6875, 8.8750, -7.8125, -7.4062, -8.0000, -8.3125, -7.4375, -7.8125, -8.1250, -7.8125, -7.4062, -7.8438, -7.5312, -8.0625, -8.0625, -7.6250, -8.0000, -8.3125, -7.5938, -7.7500, -7.7500, -7.6562, -7.6562, -8.1250, -8.0625, -8.1250, -7.8750, -8.1875, -8.2500, -7.5938, -8.0625, -7.5000, -7.7812, -7.9375, -7.4688, -8.0625, -7.3750, -8.0000, -7.50003 ] , dtype=torch.float32) # fmt: skip EXPECTED_LOGITS_NO_GRAD_1 = torch.tensor( [ -3.5469, -4.0625, 8.5000, -3.8125, -3.6406, -3.7969, -3.8125, -3.3594, -3.7188, -3.7500, -3.7656, -3.5469, -3.7969, -4.0000, -3.5625, -3.6406, -3.7188, -3.6094, -4.0938, -3.6719, -3.8906, -3.9844, -3.8594, -3.4219, -3.2031, -3.4375, -3.7500, -3.6562, -3.9688, -4.1250, -3.6406, -3.57811, -3.0312, -3.4844, -3.6094, -3.5938, -3.7656, -3.8125, -3.7500, -3.8594 ] , dtype=torch.float32) # fmt: skip torch.testing.assert_close(logits[0, -1, :40].cpu(), EXPECTED_LOGITS_NO_GRAD_0, rtol=1e-3, atol=1e-3) torch.testing.assert_close(logits[1, -1, :40].cpu(), EXPECTED_LOGITS_NO_GRAD_1, rtol=1e-3, atol=1e-3)
transformers/tests/models/jamba/test_modeling_jamba.py/0
{ "file_path": "transformers/tests/models/jamba/test_modeling_jamba.py", "repo_id": "transformers", "token_count": 13904 }
547
# Copyright 2018 LXMERT Authors, The Hugging Face 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 os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class LxmertTokenizationTest(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "unc-nlp/lxmert-base-uncased" tokenizer_class = LxmertTokenizer rust_tokenizer_class = LxmertTokenizerFast test_rust_tokenizer = True space_between_special_tokens = True @classmethod def setUpClass(cls): super().setUpClass() vocab_tokens = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] cls.vocab_file = os.path.join(cls.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) with open(cls.vocab_file, "w", encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) def get_input_output_texts(self, tokenizer): input_text = "UNwant\u00e9d,running" output_text = "unwanted, running" return input_text, output_text def test_full_tokenizer(self): tokenizer = self.tokenizer_class(self.vocab_file) tokens = tokenizer.tokenize("UNwant\u00e9d,running") self.assertListEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"]) self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9]) def test_rust_and_python_full_tokenizers(self): if not self.test_rust_tokenizer: self.skipTest(reason="test_rust_tokenizer is set to False") tokenizer = self.get_tokenizer() rust_tokenizer = self.get_rust_tokenizer() sequence = "I was born in 92000, and this is falsé." tokens = tokenizer.tokenize(sequence) rust_tokens = rust_tokenizer.tokenize(sequence) self.assertListEqual(tokens, rust_tokens) ids = tokenizer.encode(sequence, add_special_tokens=False) rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) self.assertListEqual(ids, rust_ids) rust_tokenizer = self.get_rust_tokenizer() ids = tokenizer.encode(sequence) rust_ids = rust_tokenizer.encode(sequence) self.assertListEqual(ids, rust_ids)
transformers/tests/models/lxmert/test_tokenization_lxmert.py/0
{ "file_path": "transformers/tests/models/lxmert/test_tokenization_lxmert.py", "repo_id": "transformers", "token_count": 1336 }
548
# Copyright 2023 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. """Testing suite for the PyTorch Mixtral model.""" import unittest import pytest from transformers import MixtralConfig, is_torch_available from transformers.testing_utils import ( Expectations, require_flash_attn, require_torch, require_torch_accelerator, require_torch_gpu, slow, torch_device, ) if is_torch_available(): import torch from transformers import ( MixtralForCausalLM, MixtralForQuestionAnswering, MixtralForSequenceClassification, MixtralForTokenClassification, MixtralModel, ) from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester class MixtralModelTester(CausalLMModelTester): config_class = MixtralConfig if is_torch_available(): base_model_class = MixtralModel causal_lm_class = MixtralForCausalLM sequence_class = MixtralForSequenceClassification token_class = MixtralForTokenClassification question_answering_class = MixtralForQuestionAnswering @require_torch class MistralModelTest(CausalLMModelTest, unittest.TestCase): all_model_classes = ( ( MixtralModel, MixtralForCausalLM, MixtralForSequenceClassification, MixtralForTokenClassification, MixtralForQuestionAnswering, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": MixtralModel, "text-classification": MixtralForSequenceClassification, "token-classification": MixtralForTokenClassification, "text-generation": MixtralForCausalLM, "question-answering": MixtralForQuestionAnswering, } if is_torch_available() else {} ) test_headmasking = False test_pruning = False model_tester_class = MixtralModelTester # TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79245/workflows/9490ef58-79c2-410d-8f51-e3495156cf9c/jobs/1012146 def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): return True @require_flash_attn @require_torch_gpu @pytest.mark.flash_attn_test @slow def test_flash_attn_2_inference_equivalence_right_padding(self): self.skipTest(reason="Mistral flash attention does not support right padding") # Ignore copy def test_load_balancing_loss(self): r""" Let's make sure we can actually compute the loss and do a backward on it. """ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() config.num_labels = 3 config.num_local_experts = 8 config.output_router_logits = True input_ids = input_dict["input_ids"] attention_mask = input_ids.ne(1).to(torch_device) model = MixtralForCausalLM(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=attention_mask) self.assertEqual(result.router_logits[0].shape, (91, config.num_local_experts)) torch.testing.assert_close(result.aux_loss.cpu(), torch.tensor(2, dtype=torch.float32), rtol=1e-2, atol=1e-2) # First, we make sure that adding padding tokens doesn't change the loss # loss(input_ids, attention_mask=None) == loss(input_ids + padding, attention_mask=attention_mask_with_padding) pad_length = 1000 # Add padding tokens (assume that pad_token_id=1) to input_ids padding_block = torch.ones(input_ids.shape[0], pad_length, dtype=torch.int32).to(torch_device) padded_input_ids = torch.cat((padding_block, input_ids), dim=1) # this is to simulate padding to the left padded_attention_mask = padded_input_ids.ne(1).to(torch_device) padded_result = model(padded_input_ids, attention_mask=padded_attention_mask) torch.testing.assert_close(result.aux_loss.cpu(), padded_result.aux_loss.cpu(), rtol=1e-4, atol=1e-4) # We make sure that the loss of including padding tokens != the loss without padding tokens # if attention_mask=None --> we don't exclude padding tokens include_padding_result = model(padded_input_ids, attention_mask=None) # This is to mimic torch.testing.assert_not_close self.assertNotAlmostEqual(include_padding_result.aux_loss.item(), result.aux_loss.item()) @require_torch class MixtralIntegrationTest(unittest.TestCase): @slow @require_torch_accelerator def test_small_model_logits(self): model_id = "hf-internal-testing/Mixtral-tiny" dummy_input = torch.LongTensor([[0, 1, 0], [0, 1, 0]]).to(torch_device) model = MixtralForCausalLM.from_pretrained( model_id, dtype=torch.bfloat16, ).to(torch_device) # TODO: might need to tweak it in case the logits do not match on our daily runners # these logits have been obtained with the original megablocks implementation. # ("cuda", 8) for A100/A10, and ("cuda", 7) for T4 # considering differences in hardware processing and potential deviations in output. # fmt: off EXPECTED_LOGITS = Expectations( { ("cuda", 7): torch.Tensor([[0.1640, 0.1621, 0.6093], [-0.8906, -0.1640, -0.6093], [0.1562, 0.1250, 0.7226]]).to(torch_device), ("cuda", 8): torch.Tensor([[0.1631, 0.1621, 0.6094], [-0.8906, -0.1621, -0.6094], [0.1572, 0.1270, 0.7227]]).to(torch_device), ("rocm", 9): torch.Tensor([[0.1641, 0.1621, 0.6094], [-0.8906, -0.1631, -0.6094], [0.1572, 0.1260, 0.7227]]).to(torch_device), } ) # fmt: on expected_logit = EXPECTED_LOGITS.get_expectation() with torch.no_grad(): logits = model(dummy_input).logits logits = logits.float() torch.testing.assert_close(logits[0, :3, :3], expected_logit, atol=1e-3, rtol=1e-3) torch.testing.assert_close(logits[1, :3, :3], expected_logit, atol=1e-3, rtol=1e-3) @slow @require_torch_accelerator def test_small_model_logits_batched(self): model_id = "hf-internal-testing/Mixtral-tiny" dummy_input = torch.LongTensor([[0, 0, 0, 0, 0, 0, 1, 2, 3], [1, 1, 2, 3, 4, 5, 6, 7, 8]]).to(torch_device) attention_mask = dummy_input.ne(0).to(torch.long) model = MixtralForCausalLM.from_pretrained( model_id, dtype=torch.bfloat16, ).to(torch_device) # TODO: might need to tweak it in case the logits do not match on our daily runners # # ("cuda", 8) for A100/A10, and ("cuda", 7) for T4. # # considering differences in hardware processing and potential deviations in generated text. EXPECTED_LOGITS_LEFT_UNPADDED = Expectations( { ("xpu", 3): [[0.2236, 0.5195, -0.3828], [0.8203, -0.2295, 0.6055], [0.2676, -0.7070, 0.2461]], ("cuda", 7): [[0.2236, 0.5195, -0.3828], [0.8203, -0.2275, 0.6054], [0.2656, -0.7070, 0.2460]], ("cuda", 8): [[0.2217, 0.5195, -0.3828], [0.8203, -0.2295, 0.6055], [0.2676, -0.7109, 0.2461]], ("rocm", 9): [[0.2236, 0.5195, -0.3828], [0.8203, -0.2285, 0.6055], [0.2637, -0.7109, 0.2451]], } ) expected_left_unpadded = torch.tensor(EXPECTED_LOGITS_LEFT_UNPADDED.get_expectation(), device=torch_device) EXPECTED_LOGITS_RIGHT_UNPADDED = Expectations( { ("xpu", 3): [[0.2178, 0.1270, -0.1641], [-0.3496, 0.2988, -1.0312], [0.0693, 0.7930, 0.8008]], ("cuda", 7): [[0.2167, 0.1269, -0.1640], [-0.3496, 0.2988, -1.0312], [0.0688, 0.7929, 0.8007]], ("cuda", 8): [[0.2178, 0.1260, -0.1621], [-0.3496, 0.2988, -1.0312], [0.0693, 0.7930, 0.8008]], ("rocm", 9): [[0.2197, 0.1250, -0.1611], [-0.3516, 0.3008, -1.0312], [0.0684, 0.7930, 0.8008]], } ) expected_right_unpadded = torch.tensor(EXPECTED_LOGITS_RIGHT_UNPADDED.get_expectation(), device=torch_device) with torch.no_grad(): logits = model(dummy_input, attention_mask=attention_mask).logits logits = logits.float() torch.testing.assert_close( logits[0, -3:, -3:], expected_left_unpadded, atol=1e-3, rtol=1e-3, ) torch.testing.assert_close( logits[1, -3:, -3:], expected_right_unpadded, atol=1e-3, rtol=1e-3, )
transformers/tests/models/mixtral/test_modeling_mixtral.py/0
{ "file_path": "transformers/tests/models/mixtral/test_modeling_mixtral.py", "repo_id": "transformers", "token_count": 4333 }
549
# Copyright 2022 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. """Testing suite for the PyTorch MobileNetV1 model.""" import unittest from transformers import MobileNetV1Config from transformers.testing_utils import Expectations, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetV1ForImageClassification, MobileNetV1Model if is_vision_available(): from PIL import Image from transformers import MobileNetV1ImageProcessor class MobileNetV1ConfigTester(ConfigTester): def create_and_test_config_common_properties(self): config = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(config, "tf_padding")) self.parent.assertTrue(hasattr(config, "depth_multiplier")) class MobileNetV1ModelTester: def __init__( self, parent, batch_size=13, num_channels=3, image_size=32, depth_multiplier=0.25, min_depth=8, tf_padding=True, last_hidden_size=1024, output_stride=32, hidden_act="relu6", classifier_dropout_prob=0.1, initializer_range=0.02, is_training=True, use_labels=True, num_labels=10, scope=None, ): self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.depth_multiplier = depth_multiplier self.min_depth = min_depth self.tf_padding = tf_padding self.last_hidden_size = int(last_hidden_size * depth_multiplier) self.output_stride = output_stride self.hidden_act = hidden_act self.classifier_dropout_prob = classifier_dropout_prob self.use_labels = use_labels self.is_training = is_training self.num_labels = num_labels self.initializer_range = initializer_range self.scope = scope def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) labels = None pixel_labels = None if self.use_labels: labels = ids_tensor([self.batch_size], self.num_labels) pixel_labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels) config = self.get_config() return config, pixel_values, labels, pixel_labels def get_config(self): return MobileNetV1Config( num_channels=self.num_channels, image_size=self.image_size, depth_multiplier=self.depth_multiplier, min_depth=self.min_depth, tf_padding=self.tf_padding, hidden_act=self.hidden_act, classifier_dropout_prob=self.classifier_dropout_prob, initializer_range=self.initializer_range, ) def create_and_check_model(self, config, pixel_values, labels, pixel_labels): model = MobileNetV1Model(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertEqual( result.last_hidden_state.shape, ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ), ) def create_and_check_for_image_classification(self, config, pixel_values, labels, pixel_labels): config.num_labels = self.num_labels model = MobileNetV1ForImageClassification(config) model.to(torch_device) model.eval() result = model(pixel_values, labels=labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values, labels, pixel_labels = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class MobileNetV1ModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as MobileNetV1 does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (MobileNetV1Model, MobileNetV1ForImageClassification) if is_torch_available() else () pipeline_model_mapping = ( {"image-feature-extraction": MobileNetV1Model, "image-classification": MobileNetV1ForImageClassification} if is_torch_available() else {} ) test_pruning = False test_resize_embeddings = False test_head_masking = False has_attentions = False test_torch_exportable = True def setUp(self): self.model_tester = MobileNetV1ModelTester(self) self.config_tester = MobileNetV1ConfigTester(self, config_class=MobileNetV1Config, has_text_modality=False) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings") def test_model_get_set_embeddings(self): pass @unittest.skip(reason="MobileNetV1 does not output attentions") def test_attention_outputs(self): pass def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.hidden_states expected_num_stages = 26 self.assertEqual(len(hidden_states), expected_num_stages) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) def test_for_image_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*config_and_inputs) @slow def test_model_from_pretrained(self): model_name = "google/mobilenet_v1_1.0_224" model = MobileNetV1Model.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch @require_vision class MobileNetV1ModelIntegrationTest(unittest.TestCase): @cached_property def default_image_processor(self): return ( MobileNetV1ImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224") if is_vision_available() else None ) @slow def test_inference_image_classification_head(self): model = MobileNetV1ForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224").to(torch_device) image_processor = self.default_image_processor image = prepare_img() inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the logits expected_shape = torch.Size((1, 1001)) self.assertEqual(outputs.logits.shape, expected_shape) expectations = Expectations( { (None, None): [-4.1739, -1.1233, 3.1205], ("cuda", 8): [-4.1739, -1.1233, 3.1205], } ) expected_slice = torch.tensor(expectations.get_expectation()).to(torch_device) torch.testing.assert_close(outputs.logits[0, :3], expected_slice, rtol=2e-4, atol=2e-4)
transformers/tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py/0
{ "file_path": "transformers/tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py", "repo_id": "transformers", "token_count": 3888 }
550
# Copyright 2024, 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. """Testing suite for the PyTorch Moshi model.""" import copy import tempfile import unittest import numpy as np import pytest from datasets import Audio, load_dataset from parameterized import parameterized from transformers import ( MoshiConfig, PretrainedConfig, ) from transformers.integrations.deepspeed import ( is_deepspeed_available, is_deepspeed_zero3_enabled, ) from transformers.testing_utils import ( is_flaky, is_torch_available, require_torch, require_torch_fp16, slow, torch_device, ) from transformers.utils import cached_property from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ( TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION, ModelTesterMixin, floats_tensor, ids_tensor, ) from ...test_pipeline_mixin import PipelineTesterMixin if is_deepspeed_available(): import deepspeed if is_torch_available(): import torch from transformers import ( AutoFeatureExtractor, AutoTokenizer, MoshiForCausalLM, MoshiForConditionalGeneration, MoshiModel, ) def _config_zero_init(config): configs_no_init = copy.deepcopy(config) for key in configs_no_init.__dict__: if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(configs_no_init, key, 1e-10) if isinstance(getattr(configs_no_init, key, None), PretrainedConfig): no_init_subconfig = _config_zero_init(getattr(configs_no_init, key)) setattr(configs_no_init, key, no_init_subconfig) return configs_no_init class MoshiDecoderTester: def __init__( self, parent, batch_size=4, # need batch_size != num_hidden_layers seq_length=7, is_training=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=4, hidden_act="silu", rms_norm_eps=0.001, ffn_dim=32, hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=100, pad_token_id=25, num_codebooks=4, audio_encoder_type="mimi", attn_implementation="eager", ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.rms_norm_eps = rms_norm_eps self.ffn_dim = ffn_dim self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.pad_token_id = pad_token_id self.num_codebooks = num_codebooks self.audio_encoder_type = audio_encoder_type self.attn_implementation = attn_implementation def prepare_config_and_inputs(self, batch_size=None): batch_size = self.batch_size if batch_size is None else batch_size input_ids = ids_tensor([batch_size, self.seq_length], self.vocab_size) config = self.get_config() attention_mask = input_ids.ne(self.pad_token_id) inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask} return config, inputs_dict def get_config(self): config = MoshiConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, d_ff=self.intermediate_size, num_codebooks=self.num_codebooks, rms_norm_eps=self.rms_norm_eps, tie_word_embeddings=False, pad_token_id=self.pad_token_id, ffn_dim=self.ffn_dim, audio_encoder_config={"model_type": self.audio_encoder_type}, attn_implementation=self.attn_implementation, ) return config def prepare_config_and_inputs_for_common(self, batch_size=None): config, inputs_dict = self.prepare_config_and_inputs(batch_size) return config, inputs_dict @require_torch class MoshiDecoderTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (MoshiModel, MoshiForCausalLM) if is_torch_available() else () test_pruning = False test_resize_embeddings = True test_head_masking = False pipeline_model_mapping = ( { "feature-extraction": MoshiModel, "text-generation": MoshiForCausalLM, } if is_torch_available() else {} ) def setUp(self): self.model_tester = MoshiDecoderTester(self) self.config_tester = ConfigTester( self, config_class=MoshiConfig, hidden_size=16, audio_encoder_config={"model_type": self.model_tester.audio_encoder_type}, ) @unittest.skip(reason="The MoshiModel does not have support dynamic compile yet") @pytest.mark.torch_compile_test def test_sdpa_can_compile_dynamic(self): pass def _get_input_ids_and_config(self, batch_size=1): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common(batch_size) input_ids = inputs_dict.pop("input_ids").to(torch_device) attention_mask = inputs_dict.pop("attention_mask").to(torch_device) return config, input_ids, attention_mask, inputs_dict def _get_logits_processor_kwargs(self, do_sample=False, config=None): logits_processor_kwargs = {} return logits_processor_kwargs @parameterized.expand(TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION) def test_eager_matches_sdpa_inference( self, name, dtype, padding_side, use_attention_mask, output_attentions, enable_kernels ): if use_attention_mask or (not use_attention_mask and dtype == "fp32" and not output_attentions): self.skipTest("Test is failing, fix me :) ") parent_parameterized_test = getattr(ModelTesterMixin, self._testMethodName) parent_parameterized_test(self) # Copied from tests.test_modeling_common.ModelTesterMixin.test_resize_tokens_embeddings def test_resize_tokens_embeddings(self): if not self.test_resize_embeddings: self.skipTest(reason="test_resize_embeddings is set to `False`") ( original_config, inputs_dict, ) = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: config = copy.deepcopy(original_config) if is_deepspeed_zero3_enabled(): with deepspeed.zero.Init(): model = model_class(config) else: model = model_class(config) model.to(torch_device) model_embed_pre_resize = model.get_input_embeddings() type_model_embed_pre_resize = type(model_embed_pre_resize) if self.model_tester.is_training is False: model.eval() model_vocab_size = config.get_text_config().vocab_size # Retrieve the embeddings and clone theme model_embed = model.resize_token_embeddings(model_vocab_size) cloned_embeddings = model_embed.weight.clone() # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size model_embed = model.resize_token_embeddings(model_vocab_size + 10) new_model_vocab_size = model.config.get_text_config().vocab_size self.assertEqual(new_model_vocab_size, model_vocab_size + 10) # Check that it actually resizes the embeddings matrix self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) # Check to make sure the type of embeddings returned post resizing is same as type of input type_model_embed_post_resize = type(model_embed) self.assertEqual(type_model_embed_pre_resize, type_model_embed_post_resize) # Check that added embeddings mean is close to the old embeddings mean if is_deepspeed_zero3_enabled(): with deepspeed.zero.GatheredParameters(model_embed.weight, modifier_rank=None): old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0) new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0) else: old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0) new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0) torch.testing.assert_close(old_embeddings_mean, new_embeddings_mean, rtol=1e-3, atol=1e-3) # Check that the model can still do a forward pass successfully (every parameter should be resized) if not is_deepspeed_zero3_enabled(): # A distriputed launcher is needed for the forward pass when deepspeed is enabled model(**self._prepare_for_class(inputs_dict, model_class)) # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size model_embed = model.resize_token_embeddings(model_vocab_size - 15) new_model_vocab_size = model.config.get_text_config().vocab_size self.assertEqual(new_model_vocab_size, model_vocab_size - 15) # Check that it actually resizes the embeddings matrix self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15) # Check that the model can still do a forward pass successfully (every parameter should be resized) # Input ids should be clamped to the maximum size of the vocabulary inputs_dict["input_ids"].clamp_(max=model_vocab_size - 15 - 1) # make sure that decoder_input_ids are resized as well if not is_deepspeed_zero3_enabled(): # A distriputed launcher is needed for the forward pass when deepspeed is enabled if "decoder_input_ids" in inputs_dict: inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) model(**self._prepare_for_class(inputs_dict, model_class)) # Check that adding and removing tokens has not modified the first part of the embedding matrix. models_equal = True for p1, p2 in zip(cloned_embeddings, model_embed.weight): if p1.data.ne(p2.data).sum() > 0: models_equal = False self.assertTrue(models_equal) del model if is_deepspeed_zero3_enabled(): with deepspeed.zero.Init(): model = model_class(config) else: model = model_class(config) model.to(torch_device) model_vocab_size = config.get_text_config().vocab_size model.resize_token_embeddings(model_vocab_size + 10, pad_to_multiple_of=1) new_model_vocab_size = model.config.get_text_config().vocab_size self.assertTrue(new_model_vocab_size + 10, model_vocab_size) model_embed = model.resize_token_embeddings(model_vocab_size, pad_to_multiple_of=64) new_model_vocab_size = model.config.get_text_config().vocab_size self.assertTrue(model_embed.weight.shape[0] // 64, 0) self.assertTrue(model_embed.weight.shape[0], new_model_vocab_size) self.assertTrue(new_model_vocab_size, model.vocab_size) model_embed = model.resize_token_embeddings(model_vocab_size + 13, pad_to_multiple_of=64) self.assertTrue(model_embed.weight.shape[0] // 64, 0) # Check that resizing a model to a multiple of pad_to_multiple leads to a model of exactly that size target_dimension = 128 model_embed = model.resize_token_embeddings(target_dimension, pad_to_multiple_of=64) self.assertTrue(model_embed.weight.shape[0], target_dimension) with self.assertRaisesRegex( ValueError, "Asking to pad the embedding matrix to a multiple of `1.3`, which is not and integer. Please make sure to pass an integer", ): model.resize_token_embeddings(model_vocab_size, pad_to_multiple_of=1.3) # Test when `vocab_size` is smaller than `hidden_size`. del model config.vocab_size = 4 config.pad_token_id = 4 # Ignore copy if is_deepspeed_zero3_enabled(): with deepspeed.zero.Init(): model = model_class(config) else: model = model_class(config) model.to(torch_device) model_vocab_size = config.get_text_config().vocab_size # Retrieve the embeddings and clone theme model_embed = model.resize_token_embeddings(model_vocab_size) cloned_embeddings = model_embed.weight.clone() # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size model_embed = model.resize_token_embeddings(model_vocab_size + 10) new_model_vocab_size = model.config.get_text_config().vocab_size self.assertEqual(new_model_vocab_size, model_vocab_size + 10) # Check that it actually resizes the embeddings matrix self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) # Check to make sure the type of embeddings returned post resizing is same as type of input type_model_embed_post_resize = type(model_embed) self.assertEqual(type_model_embed_pre_resize, type_model_embed_post_resize) # Check that added embeddings mean is close to the old embeddings mean if is_deepspeed_zero3_enabled(): with deepspeed.zero.GatheredParameters(model_embed.weight, modifier_rank=None): old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0) new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0) else: old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0) new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0) torch.testing.assert_close(old_embeddings_mean, new_embeddings_mean, rtol=1e-3, atol=1e-3) @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.") def test_cpu_offload(self): pass @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.") def test_disk_offload_bin(self): pass @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.") def test_disk_offload_safetensors(self): pass @unittest.skip(reason="Test becomes too complex with Moshi requiring multiple input modalities.") def test_generate_continue_from_inputs_embeds(self): pass @is_flaky(max_attempts=5, description="flaky on some models.") def test_save_load(self): super().test_save_load() class MoshiTester: def __init__( self, parent, batch_size=4, # need batch_size != num_hidden_layers seq_length=7, is_training=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=8, intermediate_size=4, hidden_act="silu", rms_norm_eps=0.001, ffn_dim=32, hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=100, pad_token_id=25, bos_token_id=25, num_codebooks=4, audio_encoder_type="mimi", attn_implementation="eager", depth_hidden_size=16, depth_num_hidden_layers=2, depth_max_position_embeddings=5, depth_num_attention_heads=8, depth_ffn_dim=16, depth_sliding_window=4, mimi_intermediate_size=40, mimi_hidden_size=32, mimi_num_filters=8, mimi_num_residual_layers=1, mimi_upsampling_ratios=[8, 4], mimi_codebook_size=64, mimi_vector_quantization_hidden_dimension=64, mimi_codebook_dim=64, mimi_upsample_groups=32, mimi_num_hidden_layers=2, mimi_num_attention_heads=2, mimi_num_key_value_heads=2, mimi_sliding_window=3, sampling_rate=800, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.rms_norm_eps = rms_norm_eps self.ffn_dim = ffn_dim self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.pad_token_id = pad_token_id self.bos_token_id = bos_token_id self.num_codebooks = num_codebooks self.attn_implementation = attn_implementation self.depth_hidden_size = depth_hidden_size self.depth_num_hidden_layers = depth_num_hidden_layers self.depth_max_position_embeddings = depth_max_position_embeddings self.depth_num_attention_heads = depth_num_attention_heads self.depth_ffn_dim = depth_ffn_dim self.depth_sliding_window = depth_sliding_window self.audio_encoder_type = audio_encoder_type self.mimi_intermediate_size = mimi_intermediate_size self.mimi_hidden_size = mimi_hidden_size self.mimi_num_filters = mimi_num_filters self.mimi_num_residual_layers = mimi_num_residual_layers self.mimi_upsampling_ratios = mimi_upsampling_ratios self.mimi_codebook_size = mimi_codebook_size self.mimi_vector_quantization_hidden_dimension = mimi_vector_quantization_hidden_dimension self.mimi_codebook_dim = mimi_codebook_dim self.mimi_upsample_groups = mimi_upsample_groups self.mimi_num_hidden_layers = mimi_num_hidden_layers self.mimi_num_attention_heads = mimi_num_attention_heads self.mimi_num_key_value_heads = mimi_num_key_value_heads self.mimi_sliding_window = mimi_sliding_window self.sampling_rate = sampling_rate self.num_hidden_states_types = 2 def prepare_config_and_inputs(self, batch_size=None): batch_size = self.batch_size if batch_size is None else batch_size input_ids = ids_tensor([batch_size, self.seq_length], self.vocab_size) moshi_audio_codes = ids_tensor([batch_size, self.num_codebooks, self.seq_length], self.mimi_codebook_size) user_audio_codes = ids_tensor([batch_size, self.num_codebooks, self.seq_length], self.mimi_codebook_size) attention_mask = input_ids.ne(self.pad_token_id) config = self.get_config() inputs_dict = { "input_ids": input_ids, "moshi_audio_codes": moshi_audio_codes, "user_audio_codes": user_audio_codes, "attention_mask": attention_mask, } return config, inputs_dict def get_config(self): mimi_dict_config = { "model_type": self.audio_encoder_type, "audio_channels": 1, "hidden_size": self.mimi_hidden_size, "num_filters": self.mimi_num_filters, "num_residual_layers": self.mimi_num_residual_layers, "upsampling_ratios": self.mimi_upsampling_ratios, "codebook_size": self.mimi_codebook_size, "vector_quantization_hidden_dimension": self.mimi_vector_quantization_hidden_dimension, "upsample_groups": self.mimi_upsample_groups, "num_hidden_layers": self.mimi_num_hidden_layers, "num_attention_heads": self.mimi_num_attention_heads, "num_key_value_heads": self.mimi_num_key_value_heads, "sliding_window": self.mimi_sliding_window, "codebook_dim": self.mimi_codebook_dim, "use_cache": False, "sampling_rate": self.sampling_rate, } depth_dict_config = { "hidden_size": self.depth_hidden_size, "num_hidden_layers": self.depth_num_hidden_layers, "max_position_embeddings": self.depth_max_position_embeddings, "num_attention_heads": self.depth_num_attention_heads, "ffn_dim": self.depth_ffn_dim, "sliding_window": self.depth_sliding_window, } config = MoshiConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, d_ff=self.intermediate_size, num_codebooks=self.num_codebooks, rms_norm_eps=self.rms_norm_eps, tie_word_embeddings=False, pad_token_id=self.pad_token_id, bos_token_id=self.bos_token_id, ffn_dim=self.ffn_dim, audio_encoder_config=mimi_dict_config, depth_decoder_config=depth_dict_config, attn_implementation=self.attn_implementation, ) return config def prepare_config_and_inputs_for_common(self, batch_size=None): config, inputs_dict = self.prepare_config_and_inputs(batch_size) return config, inputs_dict @require_torch class MoshiTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): all_model_classes = (MoshiForConditionalGeneration,) if is_torch_available() else () test_pruning = False # training is not supported yet for Moshi test_headmasking = False test_resize_embeddings = False test_torchscript = False def setUp(self): self.model_tester = MoshiTester(self) # special case for labels def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) if return_labels: inputs_dict["text_labels"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device, ) return inputs_dict def _get_input_ids_and_config(self, batch_size=2): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common(batch_size) input_ids = inputs_dict.pop("input_ids").to(torch_device) attention_mask = inputs_dict.pop("attention_mask").to(torch_device) # Make sure we only return `input_ids`. # Note that audio_codes will still be generated internally, so the ability to test audio codes is still there. # There are further tests to test that audio waveforms and codes are well generated. inputs_dict["return_audio_waveforms"] = False inputs_dict["return_audio_codes"] = False inputs_dict["concat_unconditional_inputs"] = False return config, input_ids, attention_mask, inputs_dict def prepare_config_and_inputs_for_generate(self, batch_size=2): config, filtered_inputs_dict = super().prepare_config_and_inputs_for_generate(batch_size=batch_size) # Make sure we only return `input_ids`. # Note that audio_codes will still be generated internally, so the ability to test audio codes is still there. # There are further tests to test that audio waveforms and codes are well generated. filtered_inputs_dict["return_audio_waveforms"] = False filtered_inputs_dict["return_audio_codes"] = False filtered_inputs_dict["concat_unconditional_inputs"] = False return config, filtered_inputs_dict def _check_generate_outputs(self, output, config, use_cache=False, num_return_sequences=1, num_beams=1): # Overwrite because the generate method actually always uses `inputs_embeds` so `use_cache` is always `True` super()._check_generate_outputs( output, config, use_cache=True, num_return_sequences=num_return_sequences, num_beams=num_beams ) def test_initialization(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() configs_no_init = _config_zero_init(config) for model_class in self.all_model_classes: model = model_class(config=configs_no_init) for name, param in model.named_parameters(): uniform_init_parms = ["conv", "input_proj", "output_proj"] if param.requires_grad: if any(x in name for x in uniform_init_parms): self.assertTrue( -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) @unittest.skip(reason="Continuing from past key values is not straightforward as we're dealing with 3 inputs") def test_generate_continue_from_past_key_values(self): pass @unittest.skip("Moshi doesn't support contrastive generation yet.") def test_contrastive_generate(self): pass @unittest.skip("Moshi doesn't support contrastive generation yet.") def test_contrastive_generate_dict_outputs_use_cache(self): pass @unittest.skip("Moshi doesn't support contrastive generation yet.") def test_contrastive_generate_low_memory(self): pass @unittest.skip( "Moshi either needs default generation config or fix for fullgraph compile because it hardcodes SlidingWindowCache in custom generation loop." ) def test_greedy_generate_dict_outputs_use_cache(self): pass @unittest.skip( "Moshi either needs default generation config or fix for fullgraph compile because it hardcodes SlidingWindowCache in custom generation loop." ) def test_beam_search_generate_dict_outputs_use_cache(self): pass @parameterized.expand(TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION) @unittest.skip(reason="Unimplemented. Relies on `test_eager_matches_sdpa_generate` to check correctness.") def test_eager_matches_sdpa_inference( self, name, dtype, padding_side, use_attention_mask, output_attentions, enable_kernels ): pass @unittest.skip(reason="The Moshi model does not have support dynamic compile yet") @pytest.mark.torch_compile_test def test_sdpa_can_compile_dynamic(self): pass @pytest.mark.generate def test_left_padding_compatibility(self): # NOTE: left-padding results in small numerical differences. This is expected. # See https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535 # Then, test left-padding for model_class in self.all_generative_model_classes: config, input_ids, attention_mask, input_dict = self._get_input_ids_and_config() model = model_class(config).to(torch_device).eval() # no cache as some models require special cache classes to be init outside forward model.generation_config.use_cache = False # Without padding next_logits_wo_padding = model(input_ids=input_ids, attention_mask=attention_mask, **input_dict).logits[ :, -1, : ] # With left-padding (length 32) # can hardcode pad_token to be 0 as we'll do attn masking anyway pad_token_id = ( config.get_text_config().pad_token_id if config.get_text_config().pad_token_id is not None else 0 ) pad_size = (input_ids.shape[0], 32) padding = torch.ones(pad_size, dtype=input_ids.dtype, device=torch_device) * pad_token_id padded_input_ids = torch.cat((padding, input_ids), dim=1) padded_attention_mask = torch.cat((torch.zeros_like(padding), attention_mask), dim=1) padding = ( torch.ones( (pad_size[0], self.model_tester.num_codebooks, 32), dtype=input_ids.dtype, device=torch_device ) * config.audio_vocab_size ) padded_moshi_audio_codes = torch.cat((padding, input_dict["moshi_audio_codes"]), dim=2) padded_user_audio_codes = torch.cat((padding, input_dict["user_audio_codes"]), dim=2) model_kwargs = { "input_ids": padded_input_ids, "attention_mask": padded_attention_mask, "moshi_audio_codes": padded_moshi_audio_codes, "user_audio_codes": padded_user_audio_codes, } next_logits_with_padding = model(**model_kwargs).logits[:, -1, :] # They should result in very similar logits torch.testing.assert_close(next_logits_wo_padding, next_logits_with_padding, rtol=1e-5, atol=1e-5) @slow @is_flaky(max_attempts=5, description="flaky on some models.") def test_eager_matches_sdpa_generate(self): """Overwritten -- mochi has custom inputs and custom output checks""" max_new_tokens = 5 for model_class in self.all_generative_model_classes: if not model_class._supports_sdpa: self.skipTest(f"{model_class.__name__} does not support SDPA") config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() dummy_input = inputs_dict[model_class.main_input_name] if dummy_input.dtype in [torch.float32, torch.bfloat16]: dummy_input = dummy_input.to(torch.float16) inputs_dict[model_class.main_input_name] = dummy_input # make sure that all models have enough positions for generation if hasattr(config, "max_position_embeddings"): config.max_position_embeddings = max_new_tokens + dummy_input.shape[1] + 1 model = model_class(config) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model_sdpa = model_class.from_pretrained( tmpdirname, dtype=torch.float16, ).to(torch_device) self.assertTrue(model_sdpa.config._attn_implementation == "sdpa") model_eager = model_class.from_pretrained( tmpdirname, dtype=torch.float16, attn_implementation="eager", ).to(torch_device) self.assertTrue(model_eager.config._attn_implementation == "eager") for name, submodule in model_eager.named_modules(): class_name = submodule.__class__.__name__ if "SdpaAttention" in class_name or "SdpaSelfAttention" in class_name: raise ValueError("The eager model should not have SDPA attention layers") has_sdpa = False for name, submodule in model_sdpa.named_modules(): class_name = submodule.__class__.__name__ if "SdpaAttention" in class_name or "SdpaSelfAttention" in class_name: has_sdpa = True break if not has_sdpa: raise ValueError("The SDPA model should have SDPA attention layers") # Just test that a large cache works as expected res_eager = model_eager.generate( **inputs_dict, max_new_tokens=max_new_tokens, do_sample=False, depth_decoder_do_sample=False, ) res_sdpa = model_sdpa.generate( **inputs_dict, max_new_tokens=max_new_tokens, do_sample=False, depth_decoder_do_sample=False, ) torch.testing.assert_close(res_eager.sequences, res_sdpa.sequences) torch.testing.assert_close(res_eager.audio_sequences, res_sdpa.audio_sequences) @pytest.mark.generate def test_generate_without_input_ids(self): config, _, _, _ = self._get_input_ids_and_config() for model_class in self.all_generative_model_classes: model = model_class(config).to(torch_device) model.eval() output_ids_generate = model.generate( do_sample=False, max_new_tokens=self.max_new_tokens, remove_invalid_values=True ) print(output_ids_generate) self.assertIsNotNone(output_ids_generate) @unittest.skip(reason="The audio encoder has no gradients.") def test_training_gradient_checkpointing(self): pass @unittest.skip(reason="The audio encoder has no gradients.") def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip(reason="The audio encoder has no gradients.") def test_training_gradient_checkpointing_use_reentrant_false(self): pass def test_generate_from_input_values(self): for model_class in self.all_generative_model_classes: config, input_ids, _, _ = self._get_input_ids_and_config() model = model_class(config).to(torch_device).eval() input_values_length = int( self.model_tester.seq_length * config.sampling_rate / config.audio_encoder_config.frame_rate ) user_input_values = floats_tensor((input_ids.shape[0], 1, input_values_length)) moshi_input_values = floats_tensor((input_ids.shape[0], 1, input_values_length)) user_audio_codes = model.audio_encoder.encode(user_input_values, num_quantizers=model.num_codebooks)[0] moshi_audio_codes = model.audio_encoder.encode(moshi_input_values, num_quantizers=model.num_codebooks)[0] outputs_from_audio_codes = model.generate( input_ids, max_new_tokens=5, user_audio_codes=user_audio_codes, moshi_audio_codes=moshi_audio_codes ) outputs_from_audio_values = model.generate( input_ids, max_new_tokens=5, user_input_values=user_input_values, moshi_input_values=moshi_input_values ) self.assertTrue((outputs_from_audio_values.sequences == outputs_from_audio_codes.sequences).all()) self.assertTrue( torch.allclose(outputs_from_audio_codes.audio_sequences, outputs_from_audio_values.audio_sequences) ) def test_generate_depth_decoder_kwargs(self): # test sampling and beam search for model_class in self.all_generative_model_classes: config, input_ids, _, input_dict = self._get_input_ids_and_config() model = model_class(config).to(torch_device).eval() model.generate(input_ids, max_new_tokens=5, **input_dict, depth_decoder_do_sample=True) model.generate( input_ids, max_new_tokens=5, **input_dict, depth_decoder_do_sample=True, depth_decoder_num_beams=5 ) def test_generate_from_unconditional(self): # test sampling and beam search for model_class in self.all_generative_model_classes: config, input_ids, _, input_dict = self._get_input_ids_and_config() model = model_class(config).to(torch_device).eval() # check bs>1 model.generate( **model.get_unconditional_inputs(num_samples=4), max_new_tokens=5, concat_unconditional_inputs=False ) # check same results from unconditional or no inputs outputs_from_unconditional = model.generate( **model.get_unconditional_inputs(num_samples=1), max_new_tokens=5, concat_unconditional_inputs=False ) outputs_from_none = model.generate(max_new_tokens=5) self.assertTrue((outputs_from_unconditional.sequences == outputs_from_none.sequences).all()) self.assertTrue( torch.allclose(outputs_from_unconditional.audio_sequences, outputs_from_none.audio_sequences) ) @unittest.skip(reason="Compile not yet supported because in Moshi models") def test_sdpa_can_dispatch_on_flash(self): pass @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.") def test_cpu_offload(self): pass @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.") def test_disk_offload_bin(self): pass @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.") def test_disk_offload_safetensors(self): pass @unittest.skip(reason="Test becomes too complex with Moshi requiring multiple modalities") def test_generate_continue_from_inputs_embeds(self): pass @is_flaky(max_attempts=5, description="flaky on some models.") def test_save_load(self): super().test_save_load() def place_dict_on_device(dict_to_place, device): for key in dict_to_place: if dict_to_place[key] is not None and isinstance(dict_to_place[key], torch.Tensor): dict_to_place[key] = dict_to_place[key].to(device) return dict_to_place @require_torch class MoshiIntegrationTests(unittest.TestCase): @cached_property def feature_extractor(self): return AutoFeatureExtractor.from_pretrained("kmhf/hf-moshiko") @cached_property def tokenizer(self): return AutoTokenizer.from_pretrained("kmhf/hf-moshiko") def _load_datasample(self): ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") dataset = ds.cast_column("audio", Audio(sampling_rate=self.feature_extractor.sampling_rate)) # automatic decoding with librispeech speech_sample = dataset.sort("id")[0]["audio"]["array"] return speech_sample @slow def test_moshika_conditional_greedy(self): model = MoshiForConditionalGeneration.from_pretrained( "kmhf/hf-moshika", dtype=torch.float16, device_map="auto" ) inputs = self.feature_extractor(self._load_datasample(), return_tensors="pt").to( device=torch_device, dtype=torch.float16 ) user_audio_codes = model.audio_encoder.encode(**inputs, num_quantizers=8).audio_codes input_ids = self.tokenizer.encode("<pad><pad><pad><pad><unk> Hello,<pad><unk>", return_tensors="pt").to( torch_device ) # fmt: off moshi_audio_codes = [[[1049, 127, 1880, 972, 972, 1156, 1913, 415, 1933], [1700, 243, 91, 91, 91, 745, 1478, 638, 57], [1626, 457, 457, 457, 457, 1839, 200, 2011, 1142], [546, 290, 390, 390, 290, 1408, 1812, 1187, 1911], [306, 306, 1314, 1314, 1314, 759, 796, 854, 1466], [1443, 1443, 1030, 317, 347, 1178, 613, 1576, 2023], [1871, 428, 1433, 1433, 1978, 1405, 1755, 820, 610], [2008, 1744, 1511, 568, 1533, 550, 237, 1412, 1401]]] # fmt: on moshi_audio_codes = torch.tensor(moshi_audio_codes, device=torch_device) user_audio_codes = user_audio_codes[:, :, : moshi_audio_codes.shape[-1]] model_outputs = model.generate( user_audio_codes=user_audio_codes, moshi_audio_codes=moshi_audio_codes, input_ids=input_ids, do_sample=False, depth_decoder_do_sample=False, return_audio_codes=True, max_new_tokens=2, ) expected_text_token = 452 expected_audio_tokens = [916, 1396, 1238, 579, 1105, 914, 1257, 810] # fmt: skip self.assertTrue(expected_text_token == model_outputs.sequences[0, -2].item()) self.assertTrue(expected_audio_tokens == model_outputs.audio_codes[0, :, -1].tolist()) @slow def test_moshiko_greedy_unconditional_fp16_eager(self): model = MoshiForConditionalGeneration.from_pretrained( "kmhf/hf-moshiko", dtype=torch.float16, device_map="auto" ) some_expected_audio_tokens = [[1049, 127], [1700, 243], [1626, 457], [546, 290], [306, 306], [1443, 1443], [1871, 428], [2008, 1744]] # fmt: skip model_outputs = model.generate( do_sample=False, depth_decoder_do_sample=False, return_audio_codes=True, max_new_tokens=10 ) # eager equivalence is not as strict as sdpa. self.assertTrue(some_expected_audio_tokens == model_outputs.audio_codes[0, :, :2].tolist()) @slow def test_moshiko_greedy_unconditional_fp32(self): model = MoshiForConditionalGeneration.from_pretrained( "kmhf/hf-moshiko", dtype=torch.float32, device_map="auto" ) expected_audio_codesum = 72065 expected_text_tokens = [3, 3, 3, 0, 11725, 261, 3, 3, 3, 3] # fmt: skip some_expected_audio_tokens = [[1049, 127], [1700, 243], [1626, 457], [546, 290], [306, 306], [1443, 1443], [1871, 428], [2008, 1744]] # fmt: skip model_outputs = model.generate( do_sample=False, depth_decoder_do_sample=False, return_audio_codes=True, max_new_tokens=10 ) # make sure audio encoded codes are correct audio_code_sums = model_outputs.audio_codes.sum().item() self.assertTrue(np.abs(audio_code_sums - expected_audio_codesum) <= (3e-3 * audio_code_sums)) self.assertTrue(expected_text_tokens == model_outputs.sequences[0, 1:].tolist()) self.assertTrue(some_expected_audio_tokens == model_outputs.audio_codes[0, :, :2].tolist()) @slow @require_torch_fp16 def test_moshiko_greedy_unconditional_fp16(self): model = MoshiForConditionalGeneration.from_pretrained( "kmhf/hf-moshiko", dtype=torch.float16, device_map="auto" ) expected_audio_codesum = 72065 expected_text_tokens = [3, 3, 3, 0, 11725, 261, 3, 3, 3, 3] # fmt: skip some_expected_audio_tokens = [[1049, 127], [1700, 243], [1626, 457], [546, 290], [306, 306], [1443, 1443], [1871, 428], [2008, 1744]] # fmt: skip model_outputs = model.generate( do_sample=False, depth_decoder_do_sample=False, return_audio_codes=True, max_new_tokens=10 ) # make sure audio encoded codes are correct audio_code_sums = model_outputs.audio_codes.sum().item() self.assertTrue(np.abs(audio_code_sums - expected_audio_codesum) <= (3e-3 * audio_code_sums)) self.assertTrue(expected_text_tokens == model_outputs.sequences[0, 1:].tolist()) self.assertTrue(some_expected_audio_tokens == model_outputs.audio_codes[0, :, :2].tolist()) @slow @require_torch_fp16 def test_moshika_greedy_unconditional_fp16(self): model = MoshiForConditionalGeneration.from_pretrained( "kmhf/hf-moshika", dtype=torch.float16, device_map="auto" ) expected_audio_codesum = 72932 expected_text_tokens = [3, 3, 3, 0, 667, 263, 3, 3, 0, 705] # fmt: skip some_expected_audio_tokens = [[1049, 127], [1700, 243], [1626, 457], [546, 290], [306, 306], [1443, 347], [1871, 428], [2008, 2008]] # fmt: skip model_outputs = model.generate( do_sample=False, depth_decoder_do_sample=False, return_audio_codes=True, max_new_tokens=10 ) # make sure audio encoded codes are correct audio_code_sums = model_outputs.audio_codes.sum().item() self.assertTrue(np.abs(audio_code_sums - expected_audio_codesum) <= 2048) self.assertTrue(expected_text_tokens == model_outputs.sequences[0, 1:].tolist()) self.assertTrue(some_expected_audio_tokens == model_outputs.audio_codes[0, :, :2].tolist())
transformers/tests/models/moshi/test_modeling_moshi.py/0
{ "file_path": "transformers/tests/models/moshi/test_modeling_moshi.py", "repo_id": "transformers", "token_count": 20535 }
551
# 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 unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class OpenAIGPTModelTester: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope self.pad_token_id = self.vocab_size - 1 def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = OpenAIGPTConfig( vocab_size=self.vocab_size, n_embd=self.hidden_size, n_layer=self.num_hidden_layers, n_head=self.num_attention_heads, # intermediate_size=self.intermediate_size, # hidden_act=self.hidden_act, # hidden_dropout_prob=self.hidden_dropout_prob, # attention_probs_dropout_prob=self.attention_probs_dropout_prob, n_positions=self.max_position_embeddings, # type_vocab_size=self.type_vocab_size, # initializer_range=self.initializer_range pad_token_id=self.pad_token_id, ) head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def create_and_check_openai_gpt_model(self, config, input_ids, head_mask, token_type_ids, *args): model = OpenAIGPTModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask) result = model(input_ids, token_type_ids=token_type_ids) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_lm_head_model(self, config, input_ids, head_mask, token_type_ids, *args): model = OpenAIGPTLMHeadModel(config) model.to(torch_device) model.eval() result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids) self.parent.assertEqual(result.loss.shape, ()) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_double_lm_head_model(self, config, input_ids, head_mask, token_type_ids, *args): model = OpenAIGPTDoubleHeadsModel(config) model.to(torch_device) model.eval() result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids) self.parent.assertEqual(result.loss.shape, ()) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_openai_gpt_for_sequence_classification( self, config, input_ids, head_mask, token_type_ids, *args ): config.num_labels = self.num_labels model = OpenAIGPTForSequenceClassification(config) model.to(torch_device) model.eval() sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) result = model(input_ids, token_type_ids=token_type_ids, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) = config_and_inputs inputs_dict = { "input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask, } return config, inputs_dict @require_torch class OpenAIGPTModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) # TODO: Fix the failed tests def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): if pipeline_test_case_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False # special case for DoubleHeads model def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": inputs_dict["labels"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length), dtype=torch.long, device=torch_device, ) inputs_dict["input_ids"] = inputs_dict["labels"] inputs_dict["token_type_ids"] = inputs_dict["labels"] inputs_dict["mc_token_ids"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices), dtype=torch.long, device=torch_device, ) inputs_dict["mc_labels"] = torch.zeros( self.model_tester.batch_size, dtype=torch.long, device=torch_device ) return inputs_dict def setUp(self): self.model_tester = OpenAIGPTModelTester(self) self.config_tester = ConfigTester(self, config_class=OpenAIGPTConfig, n_embd=37) def test_config(self): self.config_tester.run_common_tests() def test_openai_gpt_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*config_and_inputs) def test_openai_gpt_lm_head_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*config_and_inputs) def test_openai_gpt_double_lm_head_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*config_and_inputs) def test_openai_gpt_classification_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*config_and_inputs) @slow def test_model_from_pretrained(self): model_name = "openai-community/openai-gpt" model = OpenAIGPTModel.from_pretrained(model_name) self.assertIsNotNone(model) @require_torch class OPENAIGPTModelLanguageGenerationTest(unittest.TestCase): @slow def test_lm_generate_openai_gpt(self): model = OpenAIGPTLMHeadModel.from_pretrained("openai-community/openai-gpt") model.to(torch_device) input_ids = torch.tensor([[481, 4735, 544]], dtype=torch.long, device=torch_device) # the president is expected_output_ids = [ 481, 4735, 544, 246, 963, 870, 762, 239, 244, 40477, 244, 249, 719, 881, 487, 544, 240, 244, 603, 481, ] # the president is a very good man. " \n " i\'m sure he is, " said the output_ids = model.generate(input_ids, do_sample=False) self.assertListEqual(output_ids[0].tolist(), expected_output_ids)
transformers/tests/models/openai/test_modeling_openai.py/0
{ "file_path": "transformers/tests/models/openai/test_modeling_openai.py", "repo_id": "transformers", "token_count": 5403 }
552
# Copyright 2021 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. """Testing suite for the PyTorch Perceiver model.""" import copy import inspect import math import tempfile import unittest import warnings import numpy as np from datasets import load_dataset from transformers import PerceiverConfig from transformers.testing_utils import ( IS_ROCM_SYSTEM, require_torch, require_torch_multi_gpu, require_vision, slow, torch_device, ) from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverModel, PerceiverTokenizer, ) from transformers.models.auto.modeling_auto import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_MAPPING_NAMES, ) if is_vision_available(): from PIL import Image from transformers import PerceiverImageProcessor class PerceiverModelTester: def __init__( self, parent, batch_size=13, seq_length=7, num_channels=3, image_size=32, train_size=[20, 20], num_frames=5, audio_samples_per_frame=200, samples_per_patch=20, nchunks=20, num_latents=10, d_latents=20, d_model=64, num_blocks=1, num_self_attends_per_block=2, num_self_attention_heads=1, num_cross_attention_heads=1, self_attention_widening_factor=4, cross_attention_widening_factor=4, is_training=True, use_input_mask=True, use_labels=True, vocab_size=99, hidden_act="gelu", attention_probs_dropout_prob=0.1, initializer_range=0.02, max_position_embeddings=7, num_labels=3, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.num_channels = num_channels self.image_size = image_size self.train_size = train_size self.num_frames = num_frames self.audio_samples_per_frame = audio_samples_per_frame self.samples_per_patch = samples_per_patch self.nchunks = nchunks self.num_latents = num_latents self.d_latents = d_latents self.d_model = d_model self.num_blocks = num_blocks self.num_self_attends_per_block = num_self_attends_per_block self.num_self_attention_heads = num_self_attention_heads self.num_cross_attention_heads = num_cross_attention_heads self.self_attention_widening_factor = self_attention_widening_factor self.cross_attention_widening_factor = cross_attention_widening_factor self.is_training = is_training self.use_input_mask = use_input_mask self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_act = hidden_act self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.num_labels = num_labels self.scope = scope # set subsampling for multimodal model (take first chunk) image_chunk_size = np.prod((self.num_frames, self.image_size, self.image_size)) // self.nchunks audio_chunk_size = self.num_frames * self.audio_samples_per_frame // self.samples_per_patch // self.nchunks self.subsampling = { "image": torch.arange(0, image_chunk_size), "audio": torch.arange(0, audio_chunk_size), "label": None, } def prepare_config_and_inputs(self, model_class=None): config = self.get_config() input_mask = None sequence_labels = None token_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.num_labels) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) if model_class is None or model_class.__name__ == "PerceiverModel": inputs = floats_tensor([self.batch_size, self.seq_length, config.d_model], scale=1.0) return config, inputs, input_mask, sequence_labels, token_labels elif model_class.__name__ in ["PerceiverForMaskedLM", "PerceiverForSequenceClassification"]: inputs = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) # input mask is only relevant for text inputs if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) elif model_class.__name__ == "PerceiverForImageClassificationLearned": inputs = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) elif model_class.__name__ == "PerceiverForImageClassificationFourier": inputs = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) elif model_class.__name__ == "PerceiverForImageClassificationConvProcessing": inputs = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) elif model_class.__name__ == "PerceiverForOpticalFlow": inputs = floats_tensor([self.batch_size, 2, 27, self.train_size[0], self.train_size[1]]) elif model_class.__name__ == "PerceiverForMultimodalAutoencoding": images = torch.randn( (self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size), device=torch_device, ) audio = torch.randn( (self.batch_size, self.num_frames * self.audio_samples_per_frame, 1), device=torch_device ) inputs = { "image": images, "audio": audio, "label": torch.zeros((self.batch_size, self.num_labels), device=torch_device), } else: raise ValueError(f"Model class {model_class} not supported") return config, inputs, input_mask, sequence_labels, token_labels def get_config(self): return PerceiverConfig( num_latents=self.num_latents, d_latents=self.d_latents, d_model=self.d_model, qk_channels=self.d_latents, v_channels=self.d_latents, num_blocks=self.num_blocks, num_self_attends_per_block=self.num_self_attends_per_block, num_self_attention_heads=self.num_self_attention_heads, num_cross_attention_heads=self.num_cross_attention_heads, self_attention_widening_factor=self.self_attention_widening_factor, cross_attention_widening_factor=self.cross_attention_widening_factor, vocab_size=self.vocab_size, hidden_act=self.hidden_act, attention_probs_dropout_prob=self.attention_probs_dropout_prob, initializer_range=self.initializer_range, max_position_embeddings=self.max_position_embeddings, image_size=self.image_size, train_size=self.train_size, num_frames=self.num_frames, audio_samples_per_frame=self.audio_samples_per_frame, samples_per_patch=self.samples_per_patch, num_labels=self.num_labels, output_num_channels=32, _label_trainable_num_channels=16, ) def get_pipeline_config(self): config = self.get_config() # Byte level vocab config.vocab_size = 261 config.max_position_embeddings = 40 return config def create_and_check_for_masked_lm(self, config, inputs, input_mask, sequence_labels, token_labels): model = PerceiverForMaskedLM(config=config) model.to(torch_device) model.eval() result = model(inputs, attention_mask=input_mask, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_for_sequence_classification(self, config, inputs, input_mask, sequence_labels, token_labels): model = PerceiverForSequenceClassification(config=config) model.to(torch_device) model.eval() result = model(inputs, attention_mask=input_mask, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def create_and_check_for_image_classification_learned( self, config, inputs, input_mask, sequence_labels, token_labels ): model = PerceiverForImageClassificationLearned(config=config) model.to(torch_device) model.eval() result = model(inputs, attention_mask=input_mask, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def create_and_check_for_image_classification_fourier( self, config, inputs, input_mask, sequence_labels, token_labels ): model = PerceiverForImageClassificationFourier(config=config) model.to(torch_device) model.eval() result = model(inputs, attention_mask=input_mask, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def create_and_check_for_image_classification_conv( self, config, inputs, input_mask, sequence_labels, token_labels ): model = PerceiverForImageClassificationConvProcessing(config=config) model.to(torch_device) model.eval() result = model(inputs, attention_mask=input_mask, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, inputs, input_mask, sequence_labels, token_labels = config_and_inputs inputs_dict = {"inputs": inputs, "attention_mask": input_mask} return config, inputs_dict def prepare_config_and_inputs_for_model_class(self, model_class): config_and_inputs = self.prepare_config_and_inputs(model_class) config, inputs, input_mask, sequence_labels, token_labels = config_and_inputs inputs_dict = {"inputs": inputs, "attention_mask": input_mask} return config, inputs_dict @require_torch class PerceiverModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( PerceiverModel, PerceiverForMaskedLM, PerceiverForImageClassificationLearned, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForOpticalFlow, PerceiverForMultimodalAutoencoding, PerceiverForSequenceClassification, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": PerceiverModel, "fill-mask": PerceiverForMaskedLM, "image-classification": ( PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, ), "text-classification": PerceiverForSequenceClassification, "zero-shot": PerceiverForSequenceClassification, } if is_torch_available() else {} ) test_pruning = False test_head_masking = False test_torchscript = False maxDiff = None def setUp(self): self.model_tester = PerceiverModelTester(self) self.config_tester = ConfigTester( self, config_class=PerceiverConfig, hidden_size=37, common_properties=["d_model", "num_self_attention_heads", "num_cross_attention_heads"], ) def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): inputs_dict = copy.deepcopy(inputs_dict) if model_class.__name__ == "PerceiverForMultimodalAutoencoding": inputs_dict["subsampled_output_points"] = self.model_tester.subsampling if return_labels: if model_class.__name__ in [ *MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values(), "PerceiverForImageClassificationLearned", "PerceiverForImageClassificationFourier", "PerceiverForImageClassificationConvProcessing", *MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES.values(), ]: inputs_dict["labels"] = torch.zeros( self.model_tester.batch_size, dtype=torch.long, device=torch_device ) elif model_class.__name__ in [ *MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES.values(), *MODEL_FOR_MASKED_LM_MAPPING_NAMES.values(), ]: inputs_dict["labels"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device ) return inputs_dict def test_config(self): self.config_tester.run_common_tests() def test_for_masked_lm(self): config_and_inputs = self.model_tester.prepare_config_and_inputs(model_class=PerceiverForMaskedLM) self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) def test_for_sequence_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs(model_class=PerceiverForSequenceClassification) self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) def test_for_image_classification_learned(self): config_and_inputs = self.model_tester.prepare_config_and_inputs( model_class=PerceiverForImageClassificationLearned ) self.model_tester.create_and_check_for_image_classification_learned(*config_and_inputs) def test_for_image_classification_fourier(self): config_and_inputs = self.model_tester.prepare_config_and_inputs( model_class=PerceiverForImageClassificationFourier ) self.model_tester.create_and_check_for_image_classification_fourier(*config_and_inputs) def test_for_image_classification_conv(self): config_and_inputs = self.model_tester.prepare_config_and_inputs( model_class=PerceiverForImageClassificationConvProcessing ) self.model_tester.create_and_check_for_image_classification_conv(*config_and_inputs) def test_model_get_set_embeddings(self): for model_class in self.all_model_classes: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) model = model_class(config) # we overwrite this, as the embeddings of Perceiver are an instance of nn.Parameter # and Perceiver doesn't support get_output_embeddings self.assertIsInstance(model.get_input_embeddings(), (nn.Parameter)) def test_training(self): if not self.model_tester.is_training: self.skipTest(reason="model_tester.is_training is set to False") for model_class in self.all_model_classes: if model_class.__name__ in [ *MODEL_MAPPING_NAMES.values(), "PerceiverForOpticalFlow", "PerceiverForMultimodalAutoencoding", ]: continue config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) config.return_dict = True model = model_class(config) model.to(torch_device) model.train() inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) loss = model(**inputs).loss loss.backward() def test_forward_signature(self): for model_class in self.all_model_classes: config, _ = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) model = model_class(config) signature = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic arg_names = [*signature.parameters.keys()] expected_arg_names = ["inputs"] self.assertListEqual(arg_names[:1], expected_arg_names) def test_determinism(self): for model_class in self.all_model_classes: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): inputs_dict = self._prepare_for_class(inputs_dict, model_class) first = model(**inputs_dict)[0] second = model(**inputs_dict)[0] if model_class.__name__ == "PerceiverForMultimodalAutoencoding": # model outputs a dictionary with logits per modality, let's verify each modality for modality in first: out_1 = first[modality].cpu().numpy() out_2 = second[modality].cpu().numpy() out_1 = out_1[~np.isnan(out_1)] out_2 = out_2[~np.isnan(out_2)] max_diff = np.amax(np.abs(out_1 - out_2)) self.assertLessEqual(max_diff, 1e-5) else: out_1 = first.cpu().numpy() out_2 = second.cpu().numpy() out_1 = out_1[~np.isnan(out_1)] out_2 = out_2[~np.isnan(out_2)] max_diff = np.amax(np.abs(out_1 - out_2)) self.assertLessEqual(max_diff, 1e-5) def test_attention_outputs(self): seq_len = getattr(self.model_tester, "num_latents", None) for model_class in self.all_model_classes: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) config.return_dict = True inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = False config.return_dict = True model = model_class._from_config(config, attn_implementation="eager") config = model.config model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) self_attentions = outputs.attentions cross_attentions = outputs.cross_attentions # check expected number of attentions depending on model class expected_num_self_attentions = self.model_tester.num_blocks * self.model_tester.num_self_attends_per_block if model.__class__.__name__ == "PerceiverModel": # we expect to have 2 cross-attentions, namely one in the PerceiverEncoder, and one in PerceiverBasicDecoder expected_num_cross_attentions = 1 else: # we expect to have 2 cross-attentions, namely one in the PerceiverEncoder, and one in PerceiverBasicDecoder expected_num_cross_attentions = 2 self.assertEqual(len(self_attentions), expected_num_self_attentions) self.assertEqual(len(cross_attentions), expected_num_cross_attentions) # check that output_attentions also work using config del inputs_dict["output_attentions"] config.output_attentions = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) self_attentions = outputs.attentions cross_attentions = outputs.cross_attentions self.assertEqual(len(self_attentions), expected_num_self_attentions) self.assertEqual(len(cross_attentions), expected_num_cross_attentions) self.assertListEqual( list(self_attentions[0].shape[-3:]), [self.model_tester.num_self_attention_heads, seq_len, seq_len], ) out_len = len(outputs) # Check attention is always last and order is fine inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) self.assertEqual(out_len + 1, len(outputs)) self_attentions = outputs.attentions self.assertEqual(len(self_attentions), expected_num_self_attentions) self.assertListEqual( list(self_attentions[0].shape[-3:]), [self.model_tester.num_self_attention_heads, seq_len, seq_len], ) def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.hidden_states expected_num_layers = self.model_tester.num_blocks * self.model_tester.num_self_attends_per_block + 1 self.assertEqual(len(hidden_states), expected_num_layers) seq_length = self.model_tester.num_latents self.assertListEqual( list(hidden_states[0].shape[-2:]), [seq_length, self.model_tester.d_latents], ) for model_class in self.all_model_classes: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) def test_model_outputs_equivalence(self): def set_nan_tensor_to_zero(t): t[t != t] = 0 return t def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}): with torch.no_grad(): tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs) dict_output = model(**dict_inputs, return_dict=True, **additional_kwargs).to_tuple() def recursive_check(tuple_object, dict_object): if isinstance(tuple_object, (list, tuple)): for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object): recursive_check(tuple_iterable_value, dict_iterable_value) elif isinstance(tuple_object, dict): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values(), dict_object.values() ): recursive_check(tuple_iterable_value, dict_iterable_value) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(tuple_object), set_nan_tensor_to_zero(dict_object), atol=1e-5 ), msg=( "Tuple and dict output are not equal. Difference:" f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:" f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has" f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}." ), ) recursive_check(tuple_output, dict_output) for model_class in self.all_model_classes: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) model = model_class(config) model.to(torch_device) model.eval() tuple_inputs = self._prepare_for_class(inputs_dict, model_class) dict_inputs = self._prepare_for_class(inputs_dict, model_class) check_equivalence(model, tuple_inputs, dict_inputs) if model_class.__name__ not in ["PerceiverForOpticalFlow", "PerceiverForMultimodalAutoencoding"]: # optical flow + multimodal models don't support training for now tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) check_equivalence(model, tuple_inputs, dict_inputs) tuple_inputs = self._prepare_for_class(inputs_dict, model_class) dict_inputs = self._prepare_for_class(inputs_dict, model_class) check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) tuple_inputs = self._prepare_for_class(inputs_dict, model_class) dict_inputs = self._prepare_for_class(inputs_dict, model_class) check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) if model_class.__name__ not in ["PerceiverForOpticalFlow", "PerceiverForMultimodalAutoencoding"]: # optical flow + multimodal models don't support training for now tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) if model_class.__name__ not in ["PerceiverForOpticalFlow", "PerceiverForMultimodalAutoencoding"]: # optical flow + multimodal models don't support training for now tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) if model_class.__name__ not in ["PerceiverForOpticalFlow", "PerceiverForMultimodalAutoencoding"]: # optical flow + multimodal models don't support training for now tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) check_equivalence( model, tuple_inputs, dict_inputs, {"output_hidden_states": True, "output_attentions": True} ) def test_retain_grad_hidden_states_attentions(self): # no need to test all models as different heads yield the same functionality model_class = PerceiverForMaskedLM config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) config.output_hidden_states = True config.output_attentions = True model = model_class(config) model.to(torch_device) inputs = self._prepare_for_class(inputs_dict, model_class) outputs = model(**inputs) output = outputs[0] # Encoder-only model hidden_states = outputs.hidden_states[0] attentions = outputs.attentions[0] hidden_states.retain_grad() attentions.retain_grad() output.flatten()[0].backward(retain_graph=True) self.assertIsNotNone(hidden_states.grad) self.assertIsNotNone(attentions.grad) def test_feed_forward_chunking(self): for model_class in self.all_model_classes: original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) torch.manual_seed(0) config = copy.deepcopy(original_config) model = model_class(config) model.to(torch_device) model.eval() hidden_states_no_chunk = model(**self._prepare_for_class(inputs_dict, model_class))[0] torch.manual_seed(0) config.chunk_size_feed_forward = 1 model = model_class(config) model.to(torch_device) model.eval() hidden_states_with_chunk = model(**self._prepare_for_class(inputs_dict, model_class))[0] if model_class.__name__ == "PerceiverForMultimodalAutoencoding": # model outputs a dictionary with logits for each modality for modality in hidden_states_no_chunk: self.assertTrue( torch.allclose(hidden_states_no_chunk[modality], hidden_states_with_chunk[modality], atol=1e-3) ) else: torch.testing.assert_close(hidden_states_no_chunk, hidden_states_with_chunk, rtol=1e-3, atol=1e-3) def test_save_load(self): for model_class in self.all_model_classes: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) if model_class.__name__ == "PerceiverForMultimodalAutoencoding": for modality in outputs[0]: out_2 = outputs[0][modality].cpu().numpy() out_2[np.isnan(out_2)] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model = model_class.from_pretrained(tmpdirname) model.to(torch_device) with torch.no_grad(): after_outputs = model(**self._prepare_for_class(inputs_dict, model_class)) # Make sure we don't have nans out_1 = after_outputs[0][modality].cpu().numpy() out_1[np.isnan(out_1)] = 0 max_diff = np.amax(np.abs(out_1 - out_2)) self.assertLessEqual(max_diff, 1e-5) else: out_2 = outputs[0].cpu().numpy() out_2[np.isnan(out_2)] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model = model_class.from_pretrained(tmpdirname) model.to(torch_device) with torch.no_grad(): after_outputs = model(**self._prepare_for_class(inputs_dict, model_class)) # Make sure we don't have nans out_1 = after_outputs[0].cpu().numpy() out_1[np.isnan(out_1)] = 0 max_diff = np.amax(np.abs(out_1 - out_2)) self.assertLessEqual(max_diff, 1e-5) def test_correct_missing_keys(self): if not self.test_missing_keys: self.skipTest(reason="test_missing_keys is set to False") config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # most Perceiver models don't have a typical head like is the case with BERT if model_class.__name__ in [ "PerceiverForOpticalFlow", "PerceiverForMultimodalAutoencoding", *MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values(), "PerceiverForImageClassificationLearned", "PerceiverForImageClassificationFourier", "PerceiverForImageClassificationConvProcessing", *MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES.values(), ]: continue model = model_class(config) base_model_prefix = model.base_model_prefix if hasattr(model, base_model_prefix): with tempfile.TemporaryDirectory() as temp_dir_name: model.base_model.save_pretrained(temp_dir_name) model, loading_info = model_class.from_pretrained(temp_dir_name, output_loading_info=True) with self.subTest(msg=f"Missing keys for {model.__class__.__name__}"): self.assertGreater(len(loading_info["missing_keys"]), 0) def test_problem_types(self): problem_types = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if model_class.__name__ not in MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values(): continue config, inputs, input_mask, _, _ = self.model_tester.prepare_config_and_inputs(model_class=model_class) inputs_dict = {"inputs": inputs, "attention_mask": input_mask} for problem_type in problem_types: with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}"): config.problem_type = problem_type["title"] config.num_labels = problem_type["num_labels"] model = model_class(config) model.to(torch_device) model.train() inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) if problem_type["num_labels"] > 1: inputs["labels"] = inputs["labels"].unsqueeze(1).repeat(1, problem_type["num_labels"]) inputs["labels"] = inputs["labels"].to(problem_type["dtype"]) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=True) as warning_list: loss = model(**inputs).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( f"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @require_torch_multi_gpu @unittest.skip( reason=( "Perceiver does not work with data parallel (DP) because of a bug in PyTorch:" " https://github.com/pytorch/pytorch/issues/36035" ) ) def test_multi_gpu_data_parallel_forward(self): pass @unittest.skip(reason="Perceiver doesn't support resize_token_embeddings") def test_resize_tokens_embeddings(self): pass @unittest.skip(reason="Perceiver doesn't support resize_token_embeddings") def test_resize_embeddings_untied(self): pass @unittest.skip(reason="Perceiver doesn't support inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="Perceiver doesn't support the AutoModel API") def test_load_with_mismatched_shapes(self): pass @slow def test_model_from_pretrained(self): model_name = "deepmind/language-perceiver" model = PerceiverModel.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image # Helper functions for optical flow integration test def prepare_optical_flow_images(): ds = load_dataset("hf-internal-testing/fixtures_sintel", split="test") return list(ds["image"][:2]) def normalize(img): return img / 255.0 * 2 - 1 def extract_image_patches(x, kernel, stride=1, dilation=1): # Do TF 'SAME' Padding b, c, h, w = x.shape h2 = math.ceil(h / stride) w2 = math.ceil(w / stride) pad_row = (h2 - 1) * stride + (kernel - 1) * dilation + 1 - h pad_col = (w2 - 1) * stride + (kernel - 1) * dilation + 1 - w x = torch.nn.functional.pad(x, (pad_row // 2, pad_row - pad_row // 2, pad_col // 2, pad_col - pad_col // 2)) # Extract patches patches = x.unfold(2, kernel, stride).unfold(3, kernel, stride) patches = patches.permute(0, 4, 5, 1, 2, 3).contiguous() return patches.view(b, -1, patches.shape[-2], patches.shape[-1]) @require_torch @require_vision class PerceiverModelIntegrationTest(unittest.TestCase): @slow def test_inference_masked_lm(self): tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver") model = PerceiverForMaskedLM.from_pretrained("deepmind/language-perceiver") model.to(torch_device) # prepare inputs text = "This is an incomplete sentence where some words are missing." encoding = tokenizer(text, padding="max_length", return_tensors="pt") # mask " missing.". encoding.input_ids[0, 52:61] = tokenizer.mask_token_id inputs, input_mask = encoding.input_ids.to(torch_device), encoding.attention_mask.to(torch_device) # forward pass with torch.no_grad(): outputs = model(inputs=inputs, attention_mask=input_mask) logits = outputs.logits # verify logits expected_shape = torch.Size((1, tokenizer.model_max_length, len(tokenizer))) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor( [[-10.8609, -10.7651, -10.9187], [-12.1689, -11.9389, -12.1479], [-12.1518, -11.9707, -12.2073]], device=torch_device, ) torch.testing.assert_close(logits[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4) expected_greedy_predictions = [38, 115, 111, 121, 121, 111, 116, 109, 52] masked_tokens_predictions = logits[0, 52:61].argmax(dim=-1).tolist() self.assertListEqual(expected_greedy_predictions, masked_tokens_predictions) @slow def test_inference_image_classification(self): image_processor = PerceiverImageProcessor() model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned") model.to(torch_device) # prepare inputs image = prepare_img() inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device) input_mask = None # forward pass with torch.no_grad(): outputs = model(inputs=inputs, attention_mask=input_mask) logits = outputs.logits # verify logits expected_shape = torch.Size((1, model.config.num_labels)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor([-1.1652, -0.1992, -0.7520], device=torch_device) atol = 1e-3 if IS_ROCM_SYSTEM else 1e-4 torch.testing.assert_close(logits[0, :3], expected_slice, rtol=atol, atol=atol) @slow def test_inference_image_classification_fourier(self): image_processor = PerceiverImageProcessor() model = PerceiverForImageClassificationFourier.from_pretrained("deepmind/vision-perceiver-fourier") model.to(torch_device) # prepare inputs image = prepare_img() inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device) input_mask = None # forward pass with torch.no_grad(): outputs = model(inputs=inputs, attention_mask=input_mask) logits = outputs.logits # verify logits expected_shape = torch.Size((1, model.config.num_labels)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor([-1.1295, -0.2832, 0.3226], device=torch_device) torch.testing.assert_close(logits[0, :3], expected_slice, rtol=1e-4, atol=1e-4) @slow def test_inference_image_classification_conv(self): image_processor = PerceiverImageProcessor() model = PerceiverForImageClassificationConvProcessing.from_pretrained("deepmind/vision-perceiver-conv") model.to(torch_device) # prepare inputs image = prepare_img() inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device) input_mask = None # forward pass with torch.no_grad(): outputs = model(inputs=inputs, attention_mask=input_mask) logits = outputs.logits # verify logits expected_shape = torch.Size((1, model.config.num_labels)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor([-1.1186, 0.0554, 0.0897], device=torch_device) torch.testing.assert_close(logits[0, :3], expected_slice, rtol=1e-4, atol=1e-4) @slow def test_inference_optical_flow(self): model = PerceiverForOpticalFlow.from_pretrained("deepmind/optical-flow-perceiver") model.to(torch_device) # prepare inputs image1, image2 = prepare_optical_flow_images() img1 = normalize(np.array(image1)) img2 = normalize(np.array(image1)) # stack images img1 = torch.tensor(np.moveaxis(img1, -1, 0)) img2 = torch.tensor(np.moveaxis(img2, -1, 0)) images = torch.stack([img1, img2], dim=0) # extract 3x3 patches patch_size = model.config.train_size inputs = images[..., : patch_size[0], : patch_size[1]].unsqueeze(0) batch_size, _, C, H, W = inputs.shape patches = extract_image_patches(inputs.view(batch_size * 2, C, H, W), kernel=3) _, C, H, W = patches.shape patches = patches.view(batch_size, -1, C, H, W).float() # forward pass with torch.no_grad(): outputs = model(inputs=patches.to(torch_device)) logits = outputs.logits # verify logits expected_shape = torch.Size((1, 368, 496, 2)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor( [ [[0.0025, -0.0050], [0.0025, -0.0049], [0.0025, -0.0048]], [[0.0026, -0.0049], [0.0026, -0.0048], [0.0026, -0.0047]], [[0.0026, -0.0049], [0.0026, -0.0048], [0.0026, -0.0046]], ], device=torch_device, ) torch.testing.assert_close(logits[0, :3, :3, :3], expected_slice, rtol=1e-4, atol=1e-4) @slow def test_inference_interpolate_pos_encoding(self): image_processor = PerceiverImageProcessor(size={"height": 384, "width": 384}) model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned") model.to(torch_device) # prepare inputs image = prepare_img() inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device) input_mask = None # forward pass with torch.no_grad(): outputs = model(inputs=inputs, attention_mask=input_mask, interpolate_pos_encoding=True) logits = outputs.logits # verify logits expected_shape = torch.Size((1, model.config.num_labels)) self.assertEqual(logits.shape, expected_shape)
transformers/tests/models/perceiver/test_modeling_perceiver.py/0
{ "file_path": "transformers/tests/models/perceiver/test_modeling_perceiver.py", "repo_id": "transformers", "token_count": 21107 }
553
# 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. import unittest import pytest import requests from parameterized import parameterized from transformers import ( AutoModelForCausalLM, AutoProcessor, GenerationConfig, Phi4MultimodalAudioConfig, Phi4MultimodalConfig, Phi4MultimodalForCausalLM, Phi4MultimodalModel, Phi4MultimodalVisionConfig, is_torch_available, is_vision_available, ) from transformers.testing_utils import ( Expectations, cleanup, require_torch, require_torch_large_accelerator, require_torchcodec, slow, torch_device, ) from transformers.utils import is_torchcodec_available from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor if is_torch_available(): import torch if is_vision_available(): from PIL import Image if is_torchcodec_available(): import torchcodec class Phi4MultimodalModelTester: def __init__( self, parent, batch_size=2, seq_length=12, image_seq_length=275, audio_seq_length=8, is_training=True, num_hidden_layers=2, vocab_size=49, hidden_size=32, intermediate_size=64, num_attention_heads=8, num_key_value_heads=4, bos_token_id=0, eos_token_id=0, pad_token_id=0, image_token_id=1, audio_token_id=2, image_size=16, audio_size=12, audio_config=Phi4MultimodalAudioConfig( num_blocks=2, hidden_size=32, num_attention_heads=8, intermediate_size=48, depthwise_seperable_out_channel=128, nemo_conv_channels=128, initializer_range=1e-5, ), vision_config=Phi4MultimodalVisionConfig( num_hidden_layers=2, hidden_size=32, intermediate_size=64, num_attention_heads=8, crop_size=16, initializer_range=1e-5, ), ): self.parent = parent self.num_hidden_layers = num_hidden_layers self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.bos_token_id = bos_token_id self.pad_token_id = pad_token_id self.eos_token_id = eos_token_id self.image_token_id = image_token_id self.audio_token_id = audio_token_id self.audio_config = audio_config self.vision_config = vision_config self.is_training = is_training self.batch_size = batch_size self.seq_length = seq_length + image_seq_length + audio_seq_length self.image_seq_length = image_seq_length self.audio_seq_length = audio_seq_length self.image_size = image_size self.audio_size = audio_size self.num_channels = 3 def get_config(self): return Phi4MultimodalConfig( num_hidden_layers=self.num_hidden_layers, vocab_size=self.vocab_size, hidden_size=self.hidden_size, intermediate_size=self.intermediate_size, num_attention_heads=self.num_attention_heads, num_key_value_heads=self.num_key_value_heads, bos_token_id=self.bos_token_id, eos_token_id=self.eos_token_id, pad_token_id=self.pad_token_id, vision_config=self.vision_config, audio_config=self.audio_config, ) def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) # The shapes corresponds to the inputs for image of size 16x16 image_pixel_values = floats_tensor([self.batch_size, 2, self.num_channels, self.image_size, self.image_size]) image_attention_mask = torch.ones(self.batch_size, 2, 1, 1) image_sizes = torch.tensor( [[self.image_size, self.image_size]] * self.batch_size, dtype=torch.long, device=torch_device ) # Feature sizes returned by an audio of size 10000 audio_input_features = floats_tensor([self.batch_size, 61, 80]) audio_embed_sizes = torch.tensor([self.audio_seq_length] * self.batch_size, dtype=torch.long) input_ids[input_ids == self.pad_token_id] = self.pad_token_id + 1 # random value but not pad token input_ids[-1, 0] = self.pad_token_id # mask the last text token input_ids[:, -self.image_seq_length - self.audio_seq_length : -self.audio_seq_length] = self.image_token_id input_ids[:, -self.audio_seq_length :] = self.audio_token_id attention_mask = torch.ones_like(input_ids) attention_mask[-1, 0] = 0 # mask the last text token config = self.get_config() return ( config, input_ids, attention_mask, image_pixel_values, image_attention_mask, image_sizes, audio_input_features, audio_embed_sizes, ) def prepare_config_and_inputs_for_common(self): ( config, input_ids, attention_mask, image_pixel_values, image_attention_mask, image_sizes, audio_input_features, audio_embed_sizes, ) = self.prepare_config_and_inputs() inputs_dict = { "input_ids": input_ids, "attention_mask": attention_mask, "image_pixel_values": image_pixel_values, "image_attention_mask": image_attention_mask, "image_sizes": image_sizes, "audio_input_features": audio_input_features, "audio_embed_sizes": audio_embed_sizes, } return config, inputs_dict @require_torch class Phi4MultimodalModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): """ Model tester for `Phi4Multimodal`. """ all_model_classes = (Phi4MultimodalForCausalLM, Phi4MultimodalModel) if is_torch_available() else () test_pruning = False test_head_masking = False _is_composite = True def setUp(self): self.model_tester = Phi4MultimodalModelTester(self) self.config_tester = ConfigTester(self, config_class=Phi4MultimodalConfig) @unittest.skip(reason="Unstable test") def test_initialization(self): pass @unittest.skip(reason="Right padding not supported") def test_flash_attn_2_inference_equivalence_right_padding(self): pass @unittest.skip(reason="Depending on input modalities, some params may not have gradients") def test_training_gradient_checkpointing(self): pass @unittest.skip(reason="Depending on input modalities, some params may not have gradients") def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip(reason="Depending on input modalities, some params may not have gradients") def test_training_gradient_checkpointing_use_reentrant_false(self): pass @unittest.skip(reason="Test tries to instantiate dynamic cache with an arg") def test_multi_gpu_data_parallel_forward(self): pass @unittest.skip(reason="Test is only for old attention format") def test_sdpa_can_dispatch_composite_models(self): pass @unittest.skip(reason="Static cache supported only for text-only inputs (not images or audios)") def test_generate_from_inputs_embeds_with_static_cache(self): pass @unittest.skip(reason="Static cache supported only for text-only inputs (not images or audios)") def test_generate_with_static_cache(self): pass @unittest.skip( reason="Supported only for text-only inputs (otherwise dynamic control flows for multimodal inputs)" ) def test_generate_compilation_all_outputs(self): pass @unittest.skip( reason="Supported only for text-only inputs (otherwise dynamic control flows for multimodal inputs)" ) @pytest.mark.torch_compile_test def test_generate_compile_model_forward_fullgraph(self): pass @parameterized.expand([("random",), ("same",)]) @unittest.skip(reason="`image_attention_mask` has a specific shape") def test_assisted_decoding_matches_greedy_search(self, assistant_type): pass @unittest.skip(reason="`image_attention_mask` has a specific shape") def test_assisted_decoding_sample(self): pass @unittest.skip(reason="`image_attention_mask` has a specific shape") def test_prompt_lookup_decoding_matches_greedy_search(self): pass @unittest.skip(reason="Cannot unpad inputs for all modalities so easily") def test_flash_attention_2_padding_matches_padding_free_with_position_ids(self): pass @unittest.skip(reason="Dynamo error") def test_flex_attention_with_grads(self): pass @require_torch @slow class Phi4MultimodalIntegrationTest(unittest.TestCase): checkpoint_path = "microsoft/Phi-4-multimodal-instruct" revision = "refs/pr/70" image_url = "https://www.ilankelman.org/stopsigns/australia.jpg" audio_url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/f2641_0_throatclearing.wav" def setUp(self): # Currently, the Phi-4 checkpoint on the hub is not working with the latest Phi-4 code, so the slow integration tests # won't pass without using the correct revision (refs/pr/70) self.processor = AutoProcessor.from_pretrained(self.checkpoint_path, revision=self.revision) self.generation_config = GenerationConfig(max_new_tokens=20, do_sample=False) self.user_token = "<|user|>" self.assistant_token = "<|assistant|>" self.end_token = "<|end|>" self.image = Image.open(requests.get(self.image_url, stream=True).raw) audio_bytes = requests.get(self.audio_url, stream=True).raw.data samples = torchcodec.decoders.AudioDecoder(audio_bytes).get_all_samples() self.audio, self.sampling_rate = samples.data, samples.sample_rate cleanup(torch_device, gc_collect=True) def tearDown(self): cleanup(torch_device, gc_collect=True) def test_text_only_generation(self): model = AutoModelForCausalLM.from_pretrained( self.checkpoint_path, revision=self.revision, dtype=torch.float16, device_map=torch_device ) prompt = f"{self.user_token}What is the answer for 1+1? Explain it.{self.end_token}{self.assistant_token}" inputs = self.processor(prompt, images=None, return_tensors="pt").to(torch_device) output = model.generate( **inputs, generation_config=self.generation_config, ) output = output[:, inputs["input_ids"].shape[1] :] response = self.processor.batch_decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] EXPECTED_RESPONSE = "The answer for 1+1 is 2. This is because when you add one to another" self.assertEqual(response, EXPECTED_RESPONSE) def test_vision_text_generation(self): model = AutoModelForCausalLM.from_pretrained( self.checkpoint_path, revision=self.revision, dtype=torch.float16, device_map=torch_device ) prompt = f"{self.user_token}<|image|>What is shown in this image?{self.end_token}{self.assistant_token}" inputs = self.processor(prompt, images=self.image, return_tensors="pt").to(torch_device) output = model.generate( **inputs, generation_config=self.generation_config, ) output = output[:, inputs["input_ids"].shape[1] :] response = self.processor.batch_decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] EXPECTED_RESPONSES = Expectations( { ("cuda", 7): 'The image shows a vibrant scene at a traditional Chinese-style street entrance, known as a "gate"', ("cuda", 8): 'The image shows a vibrant scene at a street intersection in a city with a Chinese-influenced architectural', } ) # fmt: skip EXPECTED_RESPONSE = EXPECTED_RESPONSES.get_expectation() self.assertEqual(response, EXPECTED_RESPONSE) @require_torch_large_accelerator def test_multi_image_vision_text_generation(self): model = AutoModelForCausalLM.from_pretrained( self.checkpoint_path, revision=self.revision, dtype=torch.float16, device_map=torch_device ) images = [] placeholder = "" for i in range(1, 5): url = f"https://image.slidesharecdn.com/azureintroduction-191206101932/75/Introduction-to-Microsoft-Azure-Cloud-{i}-2048.jpg" images.append(Image.open(requests.get(url, stream=True).raw)) placeholder += "<|image|>" prompt = f"{self.user_token}{placeholder}Summarize the deck of slides.{self.end_token}{self.assistant_token}" inputs = self.processor(prompt, images, return_tensors="pt").to(torch_device) output = model.generate( **inputs, generation_config=self.generation_config, ) output = output[:, inputs["input_ids"].shape[1] :] response = self.processor.batch_decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] EXPECTED_RESPONSE = "The presentation provides an overview of Microsoft Azure, a cloud computing platform by Microsoft, and its various services" self.assertEqual(response, EXPECTED_RESPONSE) @require_torchcodec def test_audio_text_generation(self): model = AutoModelForCausalLM.from_pretrained( self.checkpoint_path, revision=self.revision, dtype=torch.float16, device_map=torch_device ) prompt = f"{self.user_token}<|audio|>What is happening in this audio?{self.end_token}{self.assistant_token}" inputs = self.processor(prompt, audio=self.audio, sampling_rate=self.sampling_rate, return_tensors="pt").to( torch_device ) output = model.generate( **inputs, generation_config=self.generation_config, ) output = output[:, inputs["input_ids"].shape[1] :] response = self.processor.batch_decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] # Yes, it is truly the expected response... Even though the model correctly treats the audio file EXPECTED_RESPONSE = "I'm sorry, but I can't listen to audio. However, if you describe the audio to me," self.assertEqual(response, EXPECTED_RESPONSE)
transformers/tests/models/phi4_multimodal/test_modeling_phi4_multimodal.py/0
{ "file_path": "transformers/tests/models/phi4_multimodal/test_modeling_phi4_multimodal.py", "repo_id": "transformers", "token_count": 6526 }
554
# Copyright 2023 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. """Testing suite for the PyTorch Pvt model.""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import ( Expectations, require_accelerate, require_torch, require_torch_accelerator, require_torch_fp16, slow, torch_device, ) from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import PvtConfig, PvtForImageClassification, PvtImageProcessor, PvtModel from transformers.models.auto.modeling_auto import MODEL_MAPPING_NAMES if is_vision_available(): from PIL import Image class PvtConfigTester(ConfigTester): def run_common_tests(self): config = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(config, "hidden_sizes")) self.parent.assertTrue(hasattr(config, "num_encoder_blocks")) class PvtModelTester: def __init__( self, parent, batch_size=13, image_size=64, num_channels=3, num_encoder_blocks=4, depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], hidden_sizes=[16, 32, 64, 128], downsampling_rates=[1, 4, 8, 16], num_attention_heads=[1, 2, 4, 8], is_training=True, use_labels=True, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, initializer_range=0.02, num_labels=3, scope=None, ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.num_channels = num_channels self.num_encoder_blocks = num_encoder_blocks self.sr_ratios = sr_ratios self.depths = depths self.hidden_sizes = hidden_sizes self.downsampling_rates = downsampling_rates self.num_attention_heads = num_attention_heads self.is_training = is_training self.use_labels = use_labels self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.initializer_range = initializer_range self.num_labels = num_labels self.scope = scope def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) labels = None if self.use_labels: labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels) config = self.get_config() return config, pixel_values, labels def get_config(self): return PvtConfig( image_size=self.image_size, num_channels=self.num_channels, num_encoder_blocks=self.num_encoder_blocks, depths=self.depths, hidden_sizes=self.hidden_sizes, num_attention_heads=self.num_attention_heads, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, initializer_range=self.initializer_range, ) def create_and_check_model(self, config, pixel_values, labels): model = PvtModel(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertIsNotNone(result.last_hidden_state) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values, labels = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch class PvtModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (PvtModel, PvtForImageClassification) if is_torch_available() else () pipeline_model_mapping = ( {"image-feature-extraction": PvtModel, "image-classification": PvtForImageClassification} if is_torch_available() else {} ) test_head_masking = False test_pruning = False test_resize_embeddings = False test_torchscript = False has_attentions = False test_torch_exportable = True def setUp(self): self.model_tester = PvtModelTester(self) self.config_tester = PvtConfigTester(self, config_class=PvtConfig) def test_batching_equivalence(self, atol=1e-4, rtol=1e-4): super().test_batching_equivalence(atol=atol, rtol=rtol) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) @unittest.skip(reason="Pvt does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="Pvt does not have get_input_embeddings method and get_output_embeddings methods") def test_model_get_set_embeddings(self): pass def test_initialization(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config=config) for name, param in model.named_parameters(): self.assertTrue( -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.hidden_states expected_num_layers = sum(self.model_tester.depths) + 1 self.assertEqual(len(hidden_states), expected_num_layers) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:]), [ self.model_tester.batch_size, (self.model_tester.image_size // 4) ** 2, self.model_tester.image_size // 4, ], ) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) def test_training(self): if not self.model_tester.is_training: self.skipTest(reason="model_tester.is_training is set to False") config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True for model_class in self.all_model_classes: if model_class.__name__ in MODEL_MAPPING_NAMES.values(): continue model = model_class(config) model.to(torch_device) model.train() inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) loss = model(**inputs).loss loss.backward() @slow def test_model_from_pretrained(self): model_name = "Zetatech/pvt-tiny-224" model = PvtModel.from_pretrained(model_name) self.assertIsNotNone(model) @require_torch class PvtModelIntegrationTest(unittest.TestCase): @slow def test_inference_image_classification(self): # only resize + normalize image_processor = PvtImageProcessor.from_pretrained("Zetatech/pvt-tiny-224") model = PvtForImageClassification.from_pretrained("Zetatech/pvt-tiny-224").to(torch_device).eval() image = prepare_img() encoded_inputs = image_processor(images=image, return_tensors="pt") pixel_values = encoded_inputs.pixel_values.to(torch_device) with torch.no_grad(): outputs = model(pixel_values) expected_shape = torch.Size((1, model.config.num_labels)) self.assertEqual(outputs.logits.shape, expected_shape) expectations = Expectations( { (None, None): [-1.4192, -1.9158, -0.9702], ("cuda", 8): [-1.4194, -1.9161, -0.9705], } ) expected_slice = torch.tensor(expectations.get_expectation()).to(torch_device) torch.testing.assert_close(outputs.logits[0, :3], expected_slice, rtol=2e-4, atol=2e-4) @slow def test_inference_model(self): model = PvtModel.from_pretrained("Zetatech/pvt-tiny-224").to(torch_device).eval() image_processor = PvtImageProcessor.from_pretrained("Zetatech/pvt-tiny-224") image = prepare_img() inputs = image_processor(images=image, return_tensors="pt") pixel_values = inputs.pixel_values.to(torch_device) # forward pass with torch.no_grad(): outputs = model(pixel_values) # verify the logits expected_shape = torch.Size((1, 50, 512)) self.assertEqual(outputs.last_hidden_state.shape, expected_shape) expectations = Expectations( { (None, None): [[-0.3086, 1.0402, 1.1816], [-0.2880, 0.5781, 0.6124], [0.1480, 0.6129, -0.0590]], ("cuda", 8): [[-0.3086, 1.0402, 1.1816], [-0.2880, 0.5781, 0.6124], [0.1480, 0.6129, -0.0590]], } ) expected_slice = torch.tensor(expectations.get_expectation()).to(torch_device) torch.testing.assert_close(outputs.last_hidden_state[0, :3, :3], expected_slice, rtol=2e-4, atol=2e-4) @slow @require_accelerate @require_torch_accelerator @require_torch_fp16 def test_inference_fp16(self): r""" A small test to make sure that inference work in half precision without any problem. """ model = PvtForImageClassification.from_pretrained("Zetatech/pvt-tiny-224", dtype=torch.float16) model.to(torch_device) image_processor = PvtImageProcessor(size=224) image = prepare_img() inputs = image_processor(images=image, return_tensors="pt") pixel_values = inputs.pixel_values.to(torch_device, dtype=torch.float16) # forward pass to make sure inference works in fp16 with torch.no_grad(): _ = model(pixel_values)
transformers/tests/models/pvt/test_modeling_pvt.py/0
{ "file_path": "transformers/tests/models/pvt/test_modeling_pvt.py", "repo_id": "transformers", "token_count": 5175 }
555
# Copyright 2024 The Qwen team, Alibaba Group 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. """Testing suite for the PyTorch Qwen2MoE model.""" import gc import unittest import pytest from transformers import AutoTokenizer, Qwen2MoeConfig, is_torch_available, set_seed from transformers.testing_utils import ( backend_empty_cache, require_bitsandbytes, require_flash_attn, require_torch, require_torch_gpu, slow, torch_device, ) if is_torch_available(): import torch from transformers import ( Qwen2MoeForCausalLM, Qwen2MoeForQuestionAnswering, Qwen2MoeForSequenceClassification, Qwen2MoeForTokenClassification, Qwen2MoeModel, ) from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester class Qwen2MoeModelTester(CausalLMModelTester): config_class = Qwen2MoeConfig if is_torch_available(): base_model_class = Qwen2MoeModel causal_lm_class = Qwen2MoeForCausalLM sequence_class = Qwen2MoeForSequenceClassification token_class = Qwen2MoeForTokenClassification question_answering_class = Qwen2MoeForQuestionAnswering @require_torch class Qwen2MoeModelTest(CausalLMModelTest, unittest.TestCase): all_model_classes = ( ( Qwen2MoeModel, Qwen2MoeForCausalLM, Qwen2MoeForSequenceClassification, Qwen2MoeForTokenClassification, Qwen2MoeForQuestionAnswering, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": Qwen2MoeModel, "text-classification": Qwen2MoeForSequenceClassification, "token-classification": Qwen2MoeForTokenClassification, "text-generation": Qwen2MoeForCausalLM, "question-answering": Qwen2MoeForQuestionAnswering, } if is_torch_available() else {} ) test_headmasking = False test_pruning = False test_all_params_have_gradient = False model_tester_class = Qwen2MoeModelTester # TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79245/workflows/9490ef58-79c2-410d-8f51-e3495156cf9c/jobs/1012146 def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): return True @require_flash_attn @require_torch_gpu @pytest.mark.flash_attn_test @slow def test_flash_attn_2_inference_equivalence_right_padding(self): self.skipTest(reason="Qwen2Moe flash attention does not support right padding") # Ignore copy def test_load_balancing_loss(self): r""" Let's make sure we can actually compute the loss and do a backward on it. """ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() config.num_labels = 3 config.num_experts = 8 config.expert_interval = 2 config.output_router_logits = True input_ids = input_dict["input_ids"] attention_mask = input_ids.ne(1).to(torch_device) model = Qwen2MoeForCausalLM(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=attention_mask) self.assertEqual(result.router_logits[0].shape, (91, config.num_experts)) torch.testing.assert_close(result.aux_loss.cpu(), torch.tensor(2, dtype=torch.float32), rtol=1e-2, atol=1e-2) # First, we make sure that adding padding tokens doesn't change the loss # loss(input_ids, attention_mask=None) == loss(input_ids + padding, attention_mask=attention_mask_with_padding) pad_length = 1000 # Add padding tokens (assume that pad_token_id=1) to input_ids padding_block = torch.ones(input_ids.shape[0], pad_length, dtype=torch.int32).to(torch_device) padded_input_ids = torch.cat((padding_block, input_ids), dim=1) # this is to simulate padding to the left padded_attention_mask = padded_input_ids.ne(1).to(torch_device) padded_result = model(padded_input_ids, attention_mask=padded_attention_mask) torch.testing.assert_close(result.aux_loss.cpu(), padded_result.aux_loss.cpu(), rtol=1e-4, atol=1e-4) # We make sure that the loss of including padding tokens != the loss without padding tokens # if attention_mask=None --> we don't exclude padding tokens include_padding_result = model(padded_input_ids, attention_mask=None) # This is to mimic torch.testing.assert_not_close self.assertNotAlmostEqual(include_padding_result.aux_loss.item(), result.aux_loss.item()) @require_torch class Qwen2MoeIntegrationTest(unittest.TestCase): @slow def test_model_a2_7b_logits(self): input_ids = [1, 306, 4658, 278, 6593, 310, 2834, 338] model = Qwen2MoeForCausalLM.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B", device_map="auto") input_ids = torch.tensor([input_ids]).to(model.model.embed_tokens.weight.device) with torch.no_grad(): out = model(input_ids).logits.float().cpu() # Expected mean on dim = -1 EXPECTED_MEAN = torch.tensor([[-4.2125, -3.6416, -4.9136, -4.3005, -4.9938, -3.4393, -3.5195, -4.1621]]) torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, rtol=1e-2, atol=1e-2) # slicing logits[0, 0, 0:30] EXPECTED_SLICE = torch.tensor([2.3013, -0.6595, -0.1389, -1.4095, -1.7381, -1.7609, -2.0449, -2.4289, -3.0271, -2.1351, -0.6568, -4.6012, -1.9102, -0.7475, -3.1377, 4.6904, 7.1936, 7.0991, 6.4414, 6.1720, 6.2617, 5.8751, 5.6997, 5.6011, 5.5828, -3.9505, -0.5384, -0.3392, 1.2445, 2.0714]) # fmt: skip print(out[0, 0, :30]) torch.testing.assert_close(out[0, 0, :30], EXPECTED_SLICE, rtol=1e-4, atol=1e-4) del model backend_empty_cache(torch_device) gc.collect() @slow def test_model_a2_7b_generation(self): EXPECTED_TEXT_COMPLETION = """To be or not to be, that is the question. This is the question that has been asked by many people over the""" prompt = "To be or not to" tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B", use_fast=False) model = Qwen2MoeForCausalLM.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B", device_map="auto") input_ids = tokenizer.encode(prompt, return_tensors="pt").to(model.model.embed_tokens.weight.device) # greedy generation outputs generated_ids = model.generate(input_ids, max_new_tokens=20, temperature=0) text = tokenizer.decode(generated_ids[0], skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, text) del model backend_empty_cache(torch_device) gc.collect() @require_bitsandbytes @slow @require_flash_attn @pytest.mark.flash_attn_test def test_model_a2_7b_long_prompt(self): EXPECTED_OUTPUT_TOKEN_IDS = [306, 338] # An input with 4097 tokens that is above the size of the sliding window input_ids = [1] + [306, 338] * 2048 model = Qwen2MoeForCausalLM.from_pretrained( "Qwen/Qwen1.5-MoE-A2.7B", device_map="auto", load_in_4bit=True, attn_implementation="flash_attention_2", ) input_ids = torch.tensor([input_ids]).to(model.model.embed_tokens.weight.device) generated_ids = model.generate(input_ids, max_new_tokens=4, temperature=0) self.assertEqual(EXPECTED_OUTPUT_TOKEN_IDS, generated_ids[0][-2:].tolist()) # Assisted generation assistant_model = model assistant_model.generation_config.num_assistant_tokens = 2 assistant_model.generation_config.num_assistant_tokens_schedule = "constant" generated_ids = model.generate(input_ids, max_new_tokens=4, temperature=0) self.assertEqual(EXPECTED_OUTPUT_TOKEN_IDS, generated_ids[0][-2:].tolist()) del assistant_model del model backend_empty_cache(torch_device) gc.collect() @slow def test_model_a2_7b_long_prompt_sdpa(self): EXPECTED_OUTPUT_TOKEN_IDS = [306, 338] # An input with 4097 tokens that is above the size of the sliding window input_ids = [1] + [306, 338] * 2048 model = Qwen2MoeForCausalLM.from_pretrained( "Qwen/Qwen1.5-MoE-A2.7B", device_map="auto", attn_implementation="sdpa", ) input_ids = torch.tensor([input_ids]).to(model.model.embed_tokens.weight.device) generated_ids = model.generate(input_ids, max_new_tokens=4, temperature=0) self.assertEqual(EXPECTED_OUTPUT_TOKEN_IDS, generated_ids[0][-2:].tolist()) # Assisted generation assistant_model = model assistant_model.generation_config.num_assistant_tokens = 2 assistant_model.generation_config.num_assistant_tokens_schedule = "constant" generated_ids = assistant_model.generate(input_ids, max_new_tokens=4, temperature=0) self.assertEqual(EXPECTED_OUTPUT_TOKEN_IDS, generated_ids[0][-2:].tolist()) del assistant_model backend_empty_cache(torch_device) gc.collect() EXPECTED_TEXT_COMPLETION = """To be or not to be, that is the question. This is the question that has been asked by many people over the""" prompt = "To be or not to" tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B", use_fast=False) input_ids = tokenizer.encode(prompt, return_tensors="pt").to(model.model.embed_tokens.weight.device) # greedy generation outputs generated_ids = model.generate(input_ids, max_new_tokens=20, temperature=0) text = tokenizer.decode(generated_ids[0], skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, text) @slow def test_speculative_generation(self): EXPECTED_TEXT_COMPLETION = ( "To be or not to be, that is the question.\nThe answer is to be, of course. But what does it" ) prompt = "To be or not to" tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B", use_fast=False) model = Qwen2MoeForCausalLM.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B", device_map="auto", dtype=torch.float16) assistant_model = Qwen2MoeForCausalLM.from_pretrained( "Qwen/Qwen1.5-MoE-A2.7B", device_map="auto", dtype=torch.float16 ) input_ids = tokenizer.encode(prompt, return_tensors="pt").to(model.model.embed_tokens.weight.device) # greedy generation outputs set_seed(0) generated_ids = model.generate( input_ids, max_new_tokens=20, do_sample=True, temperature=0.3, assistant_model=assistant_model ) text = tokenizer.decode(generated_ids[0], skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, text) del model backend_empty_cache(torch_device) gc.collect()
transformers/tests/models/qwen2_moe/test_modeling_qwen2_moe.py/0
{ "file_path": "transformers/tests/models/qwen2_moe/test_modeling_qwen2_moe.py", "repo_id": "transformers", "token_count": 5139 }
556
# Copyright 2022 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. """Testing suite for the PyTorch RoCBert model.""" import unittest from transformers import RoCBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertModel, ) class RoCBertModelTester: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, pronunciation_vocab_size=99, shape_vocab_size=99, pronunciation_embed_dim=32, shape_embed_dim=32, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.pronunciation_vocab_size = pronunciation_vocab_size self.shape_vocab_size = shape_vocab_size self.pronunciation_embed_dim = pronunciation_embed_dim self.shape_embed_dim = shape_embed_dim self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_shape_ids = ids_tensor([self.batch_size, self.seq_length], self.shape_vocab_size) input_pronunciation_ids = ids_tensor([self.batch_size, self.seq_length], self.pronunciation_vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return ( config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def get_config(self): return RoCBertConfig( vocab_size=self.vocab_size, shape_vocab_size=self.shape_vocab_size, pronunciation_vocab_size=self.pronunciation_vocab_size, shape_embed_dim=self.shape_embed_dim, pronunciation_embed_dim=self.pronunciation_embed_dim, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=False, initializer_range=self.initializer_range, ) def prepare_config_and_inputs_for_decoder(self): ( config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = self.prepare_config_and_inputs() config.is_decoder = True encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) return ( config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def create_and_check_model( self, config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ): model = RoCBertModel(config=config) model.to(torch_device) model.eval() result = model( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, attention_mask=input_mask, token_type_ids=token_type_ids, ) result = model( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, token_type_ids=token_type_ids, ) result = model(input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_model_as_decoder( self, config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ): config.add_cross_attention = True model = RoCBertModel(config) model.to(torch_device) model.eval() result = model( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, attention_mask=input_mask, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, ) result = model( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, attention_mask=input_mask, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states, ) result = model( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, attention_mask=input_mask, token_type_ids=token_type_ids, ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_for_masked_lm( self, config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ): model = RoCBertForMaskedLM(config=config) model.to(torch_device) model.eval() result = model( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_decoder_model_past_large_inputs( self, config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ): config.is_decoder = True config.add_cross_attention = True model = RoCBertForCausalLM(config=config) model.to(torch_device) model.eval() # first forward pass outputs = model( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, attention_mask=input_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, use_cache=True, ) past_key_values = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) next_shape_tokens = ids_tensor((self.batch_size, 3), config.shape_vocab_size) next_pronunciation_tokens = ids_tensor((self.batch_size, 3), config.pronunciation_vocab_size) next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) # append to next input_ids and next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) next_input_shape_ids = torch.cat([input_shape_ids, next_shape_tokens], dim=-1) next_input_pronunciation_ids = torch.cat([input_pronunciation_ids, next_pronunciation_tokens], dim=-1) next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) output_from_no_past = model( next_input_ids, input_shape_ids=next_input_shape_ids, input_pronunciation_ids=next_input_pronunciation_ids, attention_mask=next_attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_hidden_states=True, )["hidden_states"][0] output_from_past = model( next_tokens, input_shape_ids=next_shape_tokens, input_pronunciation_ids=next_pronunciation_tokens, attention_mask=next_attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, past_key_values=past_key_values, output_hidden_states=True, )["hidden_states"][0] # select random slice random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach() output_from_past_slice = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) def create_and_check_for_question_answering( self, config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ): model = RoCBertForQuestionAnswering(config=config) model.to(torch_device) model.eval() result = model( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, attention_mask=input_mask, token_type_ids=token_type_ids, start_positions=sequence_labels, end_positions=sequence_labels, ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def create_and_check_for_sequence_classification( self, config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ): config.num_labels = self.num_labels model = RoCBertForSequenceClassification(config) model.to(torch_device) model.eval() result = model( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def create_and_check_for_token_classification( self, config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ): config.num_labels = self.num_labels model = RoCBertForTokenClassification(config=config) model.to(torch_device) model.eval() result = model( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def create_and_check_for_multiple_choice( self, config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ): config.num_choices = self.num_choices model = RoCBertForMultipleChoice(config=config) model.to(torch_device) model.eval() multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_inputs_shape_ids = input_shape_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_inputs_pronunciation_ids = ( input_pronunciation_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() ) multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() result = model( multiple_choice_inputs_ids, input_shape_ids=multiple_choice_inputs_shape_ids, input_pronunciation_ids=multiple_choice_inputs_pronunciation_ids, attention_mask=multiple_choice_input_mask, token_type_ids=multiple_choice_token_type_ids, labels=choice_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = config_and_inputs inputs_dict = { "input_ids": input_ids, "input_shape_ids": input_shape_ids, "input_pronunciation_ids": input_pronunciation_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict def create_and_check_for_pretraining( self, config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ): model = RoCBertForPreTraining(config=config) model.to(torch_device) model.eval() result = model( input_ids, input_shape_ids, input_pronunciation_ids, attention_mask=input_mask, token_type_ids=token_type_ids, attack_input_ids=input_ids, attack_input_shape_ids=input_shape_ids, attack_input_pronunciation_ids=input_pronunciation_ids, attack_attention_mask=input_mask, attack_token_type_ids=token_type_ids, labels_input_ids=token_labels, labels_input_shape_ids=input_shape_ids, labels_input_pronunciation_ids=input_pronunciation_ids, labels_attention_mask=input_mask, labels_token_type_ids=token_type_ids, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) @require_torch class RoCBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( RoCBertModel, RoCBertForMaskedLM, RoCBertForCausalLM, RoCBertForMultipleChoice, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertForPreTraining, ) if is_torch_available() else () ) # Doesn't run generation tests. There are interface mismatches when using `generate` -- TODO @gante all_generative_model_classes = () pipeline_model_mapping = ( { "feature-extraction": RoCBertModel, "fill-mask": RoCBertForMaskedLM, "question-answering": RoCBertForQuestionAnswering, "text-classification": RoCBertForSequenceClassification, "text-generation": RoCBertForCausalLM, "token-classification": RoCBertForTokenClassification, "zero-shot": RoCBertForSequenceClassification, } if is_torch_available() else {} ) # TODO: Fix the failed tests when this model gets more usage def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): if pipeline_test_case_name in [ "FillMaskPipelineTests", "FeatureExtractionPipelineTests", "TextClassificationPipelineTests", "TokenClassificationPipelineTests", ]: # Get error: IndexError: index out of range in self. # `word_shape_file` and `word_pronunciation_file` should be shrunk during tiny model creation, # otherwise `IndexError` could occur in some embedding layers. Skip for now until this model has # more usage. return True return False # special case for ForPreTraining model def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) if return_labels: if model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING): inputs_dict["labels_input_ids"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device ) inputs_dict["labels_input_shape_ids"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device ) inputs_dict["labels_input_pronunciation_ids"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device ) inputs_dict["attack_input_ids"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device ) inputs_dict["attack_input_shape_ids"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device ) inputs_dict["attack_input_pronunciation_ids"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device ) return inputs_dict def setUp(self): self.model_tester = RoCBertModelTester(self) self.config_tester = ConfigTester(self, config_class=RoCBertConfig, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_model_various_embeddings(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: config_and_inputs[0].position_embedding_type = type self.model_tester.create_and_check_model(*config_and_inputs) def test_for_masked_lm(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) def test_for_multiple_choice(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) def test_decoder_model_past_with_large_inputs(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) def test_decoder_model_past_with_large_inputs_relative_pos_emb(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() config_and_inputs[0].position_embedding_type = "relative_key" self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) def test_for_question_answering(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*config_and_inputs) def test_for_sequence_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs) def test_for_token_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*config_and_inputs) def test_for_pretraining(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*config_and_inputs) def test_model_as_decoder(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) def test_model_as_decoder_with_default_input_mask(self): ( config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) = self.model_tester.prepare_config_and_inputs_for_decoder() input_mask = None self.model_tester.create_and_check_model_as_decoder( config, input_ids, input_shape_ids, input_pronunciation_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) @slow def test_model_from_pretrained(self): model_name = "weiweishi/roc-bert-base-zh" model = RoCBertModel.from_pretrained(model_name) self.assertIsNotNone(model) @require_torch class RoCBertModelIntegrationTest(unittest.TestCase): @slow def test_inference_masked_lm(self): model = RoCBertForMaskedLM.from_pretrained("weiweishi/roc-bert-base-zh") # input_text: ['[CLS]', 'b', 'a', '里', '系', '[MASK]', '国', '的', '首', '都', '[SEP]'] is the adversarial text # of ['[CLS]', '巴', '黎', '是', '[MASK]', '国', '的', '首', '都', '[SEP]'], means # "Paris is the [MASK] of France" in English input_ids = torch.tensor([[101, 144, 143, 7027, 5143, 103, 1744, 4638, 7674, 6963, 102]]) input_shape_ids = torch.tensor([[2, 20324, 23690, 8740, 706, 1, 10900, 23343, 20205, 5850, 2]]) input_pronunciation_ids = torch.tensor([[2, 718, 397, 52, 61, 1, 168, 273, 180, 243, 2]]) output = model(input_ids, input_shape_ids, input_pronunciation_ids) output_ids = torch.argmax(output.logits, dim=2) # convert to tokens is: ['[CLS]', '巴', '*', '黎', '是', '法', '国', '的', '首', '都', '[SEP]'] expected_output = torch.tensor([[101, 2349, 115, 7944, 3221, 3791, 1744, 4638, 7674, 6963, 102]]) assert torch.allclose(output_ids, expected_output)
transformers/tests/models/roc_bert/test_modeling_roc_bert.py/0
{ "file_path": "transformers/tests/models/roc_bert/test_modeling_roc_bert.py", "repo_id": "transformers", "token_count": 13163 }
557
# 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 shutil import tempfile import unittest import numpy as np from transformers.testing_utils import require_torch, require_torchvision, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_processing_common import ProcessorTesterMixin if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch from transformers.models.sam.image_processing_sam import _mask_to_rle_pytorch @require_vision @require_torchvision class SamProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = SamProcessor @classmethod def setUpClass(cls): cls.tmpdirname = tempfile.mkdtemp() image_processor = SamImageProcessor() processor = SamProcessor(image_processor) processor.save_pretrained(cls.tmpdirname) def get_image_processor(self, **kwargs): return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor @classmethod def tearDownClass(cls): shutil.rmtree(cls.tmpdirname, ignore_errors=True) def prepare_mask_inputs(self): """This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True, or a list of PyTorch tensors if one specifies torchify=True. """ mask_inputs = [np.random.randint(255, size=(30, 400), dtype=np.uint8)] mask_inputs = [Image.fromarray(x) for x in mask_inputs] return mask_inputs def test_chat_template_save_loading(self): self.skipTest("SamProcessor does not have a tokenizer") def test_image_processor_defaults_preserved_by_image_kwargs(self): self.skipTest("SamProcessor does not have a tokenizer") def test_kwargs_overrides_default_image_processor_kwargs(self): self.skipTest("SamProcessor does not have a tokenizer") def test_kwargs_overrides_default_tokenizer_kwargs(self): self.skipTest("SamProcessor does not have a tokenizer") def test_tokenizer_defaults_preserved_by_kwargs(self): self.skipTest("SamProcessor does not have a tokenizer") def test_save_load_pretrained_additional_features(self): with tempfile.TemporaryDirectory() as tmpdir: processor = SamProcessor(image_processor=self.get_image_processor()) processor.save_pretrained(tmpdir) image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0) processor = SamProcessor.from_pretrained(tmpdir, do_normalize=False, padding_value=1.0) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor, SamImageProcessor) def test_image_processor_no_masks(self): image_processor = self.get_image_processor() processor = SamProcessor(image_processor=image_processor) image_input = self.prepare_image_inputs() input_feat_extract = image_processor(image_input, return_tensors="np") input_processor = processor(images=image_input, return_tensors="np") for key in input_feat_extract: self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) for image in input_feat_extract.pixel_values: self.assertEqual(image.shape, (3, 1024, 1024)) for original_size in input_feat_extract.original_sizes: np.testing.assert_array_equal(original_size, np.array([30, 400])) for reshaped_input_size in input_feat_extract.reshaped_input_sizes: np.testing.assert_array_equal( reshaped_input_size, np.array([77, 1024]) ) # reshaped_input_size value is before padding def test_image_processor_with_masks(self): image_processor = self.get_image_processor() processor = SamProcessor(image_processor=image_processor) image_input = self.prepare_image_inputs() mask_input = self.prepare_mask_inputs() input_feat_extract = image_processor(images=image_input, segmentation_maps=mask_input, return_tensors="np") input_processor = processor(images=image_input, segmentation_maps=mask_input, return_tensors="np") for key in input_feat_extract: self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) for label in input_feat_extract.labels: self.assertEqual(label.shape, (256, 256)) @require_torch def test_post_process_masks(self): image_processor = self.get_image_processor() processor = SamProcessor(image_processor=image_processor) dummy_masks = [torch.ones((1, 3, 5, 5))] original_sizes = [[1764, 2646]] reshaped_input_size = [[683, 1024]] masks = processor.post_process_masks(dummy_masks, original_sizes, reshaped_input_size) self.assertEqual(masks[0].shape, (1, 3, 1764, 2646)) masks = processor.post_process_masks( dummy_masks, torch.tensor(original_sizes), torch.tensor(reshaped_input_size) ) self.assertEqual(masks[0].shape, (1, 3, 1764, 2646)) # should also work with np dummy_masks = [np.ones((1, 3, 5, 5))] masks = processor.post_process_masks(dummy_masks, np.array(original_sizes), np.array(reshaped_input_size)) self.assertEqual(masks[0].shape, (1, 3, 1764, 2646)) dummy_masks = [[1, 0], [0, 1]] with self.assertRaises(TypeError): masks = processor.post_process_masks(dummy_masks, np.array(original_sizes), np.array(reshaped_input_size)) def test_rle_encoding(self): """ Test the run-length encoding function. """ # Test that a mask of all zeros returns a single run [height * width]. input_mask = torch.zeros((1, 2, 2), dtype=torch.long) # shape: 1 x 2 x 2 rle = _mask_to_rle_pytorch(input_mask) self.assertEqual(len(rle), 1) self.assertEqual(rle[0]["size"], [2, 2]) # For a 2x2 all-zero mask, we expect a single run of length 4: self.assertEqual(rle[0]["counts"], [4]) # Test that a mask of all ones returns [0, height * width]. input_mask = torch.ones((1, 2, 2), dtype=torch.long) # shape: 1 x 2 x 2 rle = _mask_to_rle_pytorch(input_mask) self.assertEqual(len(rle), 1) self.assertEqual(rle[0]["size"], [2, 2]) # For a 2x2 all-one mask, we expect two runs: [0, 4]. self.assertEqual(rle[0]["counts"], [0, 4]) # Test a mask with mixed 0s and 1s to ensure the run-length encoding is correct. # Example mask: # Row 0: [0, 1] # Row 1: [1, 1] # This is shape (1, 2, 2). # Flattened in Fortran order -> [0, 1, 1, 1]. # The RLE for [0,1,1,1] is [1, 3]. input_mask = torch.tensor([[[0, 1], [1, 1]]], dtype=torch.long) rle = _mask_to_rle_pytorch(input_mask) self.assertEqual(len(rle), 1) self.assertEqual(rle[0]["size"], [2, 2]) self.assertEqual(rle[0]["counts"], [1, 3]) # 1 zero, followed by 3 ones
transformers/tests/models/sam/test_processing_sam.py/0
{ "file_path": "transformers/tests/models/sam/test_processing_sam.py", "repo_id": "transformers", "token_count": 3156 }
558
# Copyright 2025 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 json import os import shutil import tempfile import unittest from collections.abc import Mapping from parameterized import parameterized from transformers import GemmaTokenizer, ShieldGemma2Processor from transformers.testing_utils import get_tests_dir, require_vision from transformers.utils import is_vision_available from ...test_processing_common import ProcessorTesterMixin if is_vision_available(): from transformers import Gemma3ImageProcessor SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") # Copied from _CHAT_TEMPLATE in src/transformers/models/shieldgemma2/convert_shieldgemma2_weights_orbax_to_hf.py _CHAT_TEMPLATE = """{{ bos_token }} {%- for message in messages -%} {%- if message['content'] is iterable -%} {%- for item in message['content'] -%} {{ '<start_of_turn>user\n' }} {%- if item['type'] == 'image' -%} {{ '<start_of_image>' }} {%- elif item['type'] == 'text' -%} {{ 'You are a policy expert trying to help determine whether a generated or real image is in' }} {{ ' violation of the safety policy below. Your decision must very clearly follow the specific'}} {{ ' language used in the safety policy and should not include any interpretation outside of the' }} {{ ' safety policy.\n\n' }} {{ '<BEGIN_SAFETY_POLICY>\n' }} {{ item['text'] + '\n' }} {{ '</END_SAFETY_POLICY>\n\n' }} {{ 'Does the image violate the above policy? Your Answer must start with \\'Yes\\' or \\'No\\'.' }} {{ '<end_of_turn>\n' }} {%- endif -%} {%- endfor -%} {{'<start_of_turn>model\n'}} {%- else -%} {{ raise_exception("Conversation messages must contain iterable content containing images and policy definitions in text.") }} {%- endif -%} {%- endfor -%} """ # Simplified from _SHIELDGEMMA2_POLICIES in src/transformers/models/shieldgemma2/convert_shieldgemma2_weights_orbax_to_hf.py _SHIELDGEMMA2_POLICIES: Mapping[str, str] = { "dangerous": "Test policy related to dangerous content.", "sexual": "Test policy related to sexually explicit content.", "violence": "Test policy related to violent content.", } @require_vision class ShieldGemma2ProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = ShieldGemma2Processor @classmethod def setUpClass(cls): cls.tmpdirname = tempfile.mkdtemp() image_processor = Gemma3ImageProcessor.from_pretrained("google/siglip-so400m-patch14-384") extra_special_tokens = { "image_token": "<image_soft_token>", "boi_token": "<start_of_image>", "eoi_token": "<end_of_image>", } tokenizer = GemmaTokenizer(SAMPLE_VOCAB, keep_accents=True, extra_special_tokens=extra_special_tokens) processor_kwargs = cls.prepare_processor_dict() processor = ShieldGemma2Processor(image_processor=image_processor, tokenizer=tokenizer, **processor_kwargs) processor.save_pretrained(cls.tmpdirname) @classmethod def tearDownClass(cls): shutil.rmtree(cls.tmpdirname, ignore_errors=True) @classmethod def prepare_processor_dict(cls): return { "chat_template": _CHAT_TEMPLATE, "policy_definitions": _SHIELDGEMMA2_POLICIES, } def test_policy_definitions_saved_in_config(self): processor_config_path = os.path.join(self.tmpdirname, "processor_config.json") with open(processor_config_path, "rb") as processor_config_file: json_dict = json.load(processor_config_file) self.assertIsInstance(json_dict, dict) self.assertIn("policy_definitions", json_dict) self.assertIs(len(json_dict["policy_definitions"]), 3) @parameterized.expand( [ ("all_policies", None, 3), ("selected_policies", ["dangerous", "violence"], 2), ("single_policy", ["sexual"], 1), ] ) def test_with_default_policies(self, name, policies, expected_batch_size): processor = self.get_processor() if processor.chat_template is None: self.skipTest("Processor has no chat template") images = self.prepare_image_inputs() processed_inputs = processor(images=images, policies=policies) self.assertEqual(len(processed_inputs[self.text_input_name]), expected_batch_size) self.assertEqual(len(processed_inputs[self.images_input_name]), expected_batch_size) @parameterized.expand( [ ("all_policies", None, 6), ("selected_policies_from_both", ["cbrne", "dangerous", "specialized_advice", "violence"], 4), ("selected_policies_from_custom", ["cbrne", "specialized_advice"], 2), ("selected_policies_from_default", ["dangerous", "violence"], 2), ("single_policy_from_custom", ["ip"], 1), ("single_policy_from_default", ["sexual"], 1), ] ) def test_with_custom_policies(self, name, policies, expected_batch_size): processor = self.get_processor() if processor.chat_template is None: self.skipTest("Processor has no chat template") # Test policies adapted from https://ailuminate.mlcommons.org/benchmarks/ hazard categories custom_policies = { "cbrne": "Test policy related to indiscriminate weapons.", "ip": "Test policy related to intellectual property.", "specialized_advice": "Test policy related to specialized advice.", } images = self.prepare_image_inputs() processed_inputs = processor(images=images, custom_policies=custom_policies, policies=policies) self.assertEqual(len(processed_inputs[self.text_input_name]), expected_batch_size) self.assertEqual(len(processed_inputs[self.images_input_name]), expected_batch_size) def test_with_multiple_images(self): processor = self.get_processor() if processor.chat_template is None: self.skipTest("Processor has no chat template") images = self.prepare_image_inputs(batch_size=2) processed_inputs = processor(images=images) self.assertEqual(len(processed_inputs[self.text_input_name]), 6) self.assertEqual(len(processed_inputs[self.images_input_name]), 6) # TODO(ryanmullins): Adapt this test for ShieldGemma 2 @parameterized.expand([(1, "np"), (1, "pt"), (2, "np"), (2, "pt")]) @unittest.skip("ShieldGemma 2 chat template requires different message structure from parent.") def test_apply_chat_template_image(self, batch_size: int, return_tensors: str): pass # TODO(ryanmullins): Adapt this test for ShieldGemma 2 @unittest.skip("Parent test needs to be adapted for ShieldGemma 2.") def test_unstructured_kwargs_batched(self): pass # TODO(ryanmullins): Adapt this test for ShieldGemma 2 @unittest.skip("Parent test needs to be adapted for ShieldGemma 2.") def test_unstructured_kwargs(self): pass # TODO(ryanmullins): Adapt this test for ShieldGemma 2 @unittest.skip("Parent test needs to be adapted for ShieldGemma 2.") def test_tokenizer_defaults_preserved_by_kwargs(self): pass # TODO(ryanmullins): Adapt this test for ShieldGemma 2 @unittest.skip("Parent test needs to be adapted for ShieldGemma 2.") def test_structured_kwargs_nested_from_dict(self): pass # TODO(ryanmullins): Adapt this test for ShieldGemma 2 @unittest.skip("Parent test needs to be adapted for ShieldGemma 2.") def test_structured_kwargs_nested(self): pass # TODO(ryanmullins): Adapt this test for ShieldGemma 2 @unittest.skip("Parent test needs to be adapted for ShieldGemma 2.") def test_kwargs_overrides_default_tokenizer_kwargs(self): pass # TODO(ryanmullins): Adapt this test for ShieldGemma 2 @unittest.skip("Parent test needs to be adapted for ShieldGemma 2.") def test_kwargs_overrides_default_image_processor_kwargs(self): pass @unittest.skip("ShieldGemma requires images in input, and fails in text-only processing") def test_apply_chat_template_assistant_mask(self): pass
transformers/tests/models/shieldgemma2/test_processing_shieldgemma2.py/0
{ "file_path": "transformers/tests/models/shieldgemma2/test_processing_shieldgemma2.py", "repo_id": "transformers", "token_count": 3504 }
559
# Copyright 2021 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 tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import ( require_deterministic_for_xpu, require_torch, slow, torch_device, ) from ...test_modeling_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_bert import BertModelTester from ..speech_to_text.test_modeling_speech_to_text import Speech2TextModelTester from ..wav2vec2.test_modeling_wav2vec2 import Wav2Vec2ModelTester if is_torch_available(): import numpy as np import torch from transformers import ( BertLMHeadModel, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, Wav2Vec2Model, ) from transformers.modeling_outputs import BaseModelOutput from transformers.models.speech_to_text.modeling_speech_to_text import Speech2TextEncoder @require_torch class EncoderDecoderMixin: def get_encoder_decoder_model(self, config, decoder_config): pass def prepare_config_and_inputs(self): pass def get_pretrained_model_and_inputs(self): pass def check_encoder_decoder_model_from_pretrained_configs( self, config, attention_mask, decoder_config, decoder_input_ids, decoder_attention_mask, input_values=None, input_features=None, **kwargs, ): encoder_decoder_config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs(config, decoder_config) self.assertTrue(encoder_decoder_config.decoder.is_decoder) enc_dec_model = SpeechEncoderDecoderModel(encoder_decoder_config) enc_dec_model.to(torch_device) enc_dec_model.eval() self.assertTrue(enc_dec_model.config.is_encoder_decoder) self.assertFalse(enc_dec_model.config.tie_word_embeddings) outputs_encoder_decoder = enc_dec_model( input_values=input_values, input_features=input_features, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, ) self.assertEqual( outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) def check_encoder_decoder_model( self, config, attention_mask, decoder_config, decoder_input_ids, decoder_attention_mask, input_values=None, input_features=None, **kwargs, ): encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) self.assertTrue(enc_dec_model.config.decoder.is_decoder) self.assertTrue(enc_dec_model.config.decoder.add_cross_attention) self.assertTrue(enc_dec_model.config.is_encoder_decoder) enc_dec_model.to(torch_device) outputs_encoder_decoder = enc_dec_model( input_values=input_values, input_features=input_features, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, output_hidden_states=True, ) self.assertEqual( outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) encoder_outputs = BaseModelOutput(last_hidden_state=outputs_encoder_decoder.encoder_hidden_states[-1]) outputs_encoder_decoder = enc_dec_model( encoder_outputs=encoder_outputs, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, ) self.assertEqual( outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) def check_encoder_decoder_model_with_inputs( self, config, attention_mask, decoder_config, decoder_input_ids, decoder_attention_mask, input_values=None, input_features=None, **kwargs, ): inputs = input_values if input_features is None else input_features encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) enc_dec_model.to(torch_device) outputs_encoder_decoder = enc_dec_model( inputs, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, output_hidden_states=True, ) self.assertEqual( outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) outputs_encoder_decoder_kwarg = enc_dec_model( inputs=inputs, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, output_hidden_states=True, ) self.assertEqual( outputs_encoder_decoder_kwarg["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) def check_encoder_decoder_model_from_pretrained( self, config, attention_mask, decoder_config, decoder_input_ids, decoder_attention_mask, return_dict, input_values=None, input_features=None, **kwargs, ): encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) kwargs = {"encoder_model": encoder_model, "decoder_model": decoder_model, "return_dict": return_dict} enc_dec_model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained(**kwargs) enc_dec_model.to(torch_device) outputs_encoder_decoder = enc_dec_model( input_values=input_values, input_features=input_features, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, output_hidden_states=True, return_dict=True, ) self.assertEqual( outputs_encoder_decoder["logits"].shape, (decoder_input_ids.shape + (decoder_config.vocab_size,)) ) def check_save_and_load( self, config, attention_mask, decoder_config, decoder_input_ids, decoder_attention_mask, input_values=None, input_features=None, **kwargs, ): encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) enc_dec_model.to(torch_device) enc_dec_model.eval() with torch.no_grad(): outputs = enc_dec_model( input_values=input_values, input_features=input_features, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, ) out_2 = outputs[0].cpu().numpy() out_2[np.isnan(out_2)] = 0 with tempfile.TemporaryDirectory() as tmpdirname: enc_dec_model.save_pretrained(tmpdirname) enc_dec_model = SpeechEncoderDecoderModel.from_pretrained(tmpdirname) enc_dec_model.to(torch_device) after_outputs = enc_dec_model( input_values=input_values, input_features=input_features, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, ) out_1 = after_outputs[0].cpu().numpy() out_1[np.isnan(out_1)] = 0 max_diff = np.amax(np.abs(out_1 - out_2)) self.assertLessEqual(max_diff, 1e-5) def check_save_and_load_encoder_decoder_model( self, config, attention_mask, decoder_config, decoder_input_ids, decoder_attention_mask, input_values=None, input_features=None, **kwargs, ): encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) enc_dec_model.to(torch_device) enc_dec_model.eval() with torch.no_grad(): outputs = enc_dec_model( input_values=input_values, input_features=input_features, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, ) out_2 = outputs[0].cpu().numpy() out_2[np.isnan(out_2)] = 0 with ( tempfile.TemporaryDirectory() as encoder_tmp_dirname, tempfile.TemporaryDirectory() as decoder_tmp_dirname, ): enc_dec_model.encoder.save_pretrained(encoder_tmp_dirname) enc_dec_model.decoder.save_pretrained(decoder_tmp_dirname) SpeechEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=encoder_tmp_dirname, decoder_pretrained_model_name_or_path=decoder_tmp_dirname, ) after_outputs = enc_dec_model( input_values=input_values, input_features=input_features, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, ) out_1 = after_outputs[0].cpu().numpy() out_1[np.isnan(out_1)] = 0 max_diff = np.amax(np.abs(out_1 - out_2)) self.assertLessEqual(max_diff, 1e-5) def check_encoder_decoder_model_output_attentions( self, config, attention_mask, decoder_config, decoder_input_ids, decoder_attention_mask, labels=None, input_values=None, input_features=None, **kwargs, ): # force eager attention to support output attentions config._attn_implementation = "eager" decoder_config._attn_implementation = "eager" # make the decoder inputs a different shape from the encoder inputs to harden the test decoder_input_ids = decoder_input_ids[:, :-1] decoder_attention_mask = decoder_attention_mask[:, :-1] encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) enc_dec_model.to(torch_device) outputs_encoder_decoder = enc_dec_model( input_values=input_values, input_features=input_features, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, output_attentions=True, ) inputs = input_values if input_features is None else input_features encoder_attentions = outputs_encoder_decoder["encoder_attentions"] self.assertEqual(len(encoder_attentions), config.num_hidden_layers) seq_len = enc_dec_model.encoder._get_feat_extract_output_lengths(inputs.shape[1]) self.assertEqual(encoder_attentions[0].shape[-3:], (config.num_attention_heads, seq_len, seq_len)) decoder_attentions = outputs_encoder_decoder["decoder_attentions"] num_decoder_layers = ( decoder_config.num_decoder_layers if hasattr(decoder_config, "num_decoder_layers") else decoder_config.num_hidden_layers ) self.assertEqual(len(decoder_attentions), num_decoder_layers) self.assertEqual( decoder_attentions[0].shape[-3:], (decoder_config.num_attention_heads, decoder_input_ids.shape[-1], decoder_input_ids.shape[-1]), ) cross_attentions = outputs_encoder_decoder["cross_attentions"] self.assertEqual(len(cross_attentions), num_decoder_layers) cross_attention_input_seq_len = decoder_input_ids.shape[-1] self.assertEqual( cross_attentions[0].shape[-3:], (decoder_config.num_attention_heads, cross_attention_input_seq_len, seq_len), ) def check_encoder_decoder_model_generate( self, config, decoder_config, input_values=None, input_features=None, **kwargs ): encoder_model, decoder_model = self.get_encoder_decoder_model(config, decoder_config) enc_dec_model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) enc_dec_model.to(torch_device) # make sure EOS token is set to None to prevent early stopping of generation if hasattr(enc_dec_model.config, "eos_token_id"): enc_dec_model.config.eos_token_id = None if hasattr(enc_dec_model.config, "decoder") and hasattr(enc_dec_model.config.decoder, "eos_token_id"): enc_dec_model.config.decoder.eos_token_id = None if hasattr(enc_dec_model.generation_config, "eos_token_id"): enc_dec_model.generation_config.eos_token_id = None inputs = input_values if input_features is None else input_features # Bert does not have a bos token id, so use pad_token_id instead generated_output = enc_dec_model.generate( inputs, decoder_start_token_id=enc_dec_model.config.decoder.pad_token_id, max_length=decoder_config.max_length, ) self.assertEqual(generated_output.shape, (inputs.shape[0],) + (decoder_config.max_length,)) def test_encoder_decoder_model(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model(**input_ids_dict) def test_encoder_decoder_model_with_inputs(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_with_inputs(**input_ids_dict) def test_encoder_decoder_model_from_pretrained_configs(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_from_pretrained_configs(**input_ids_dict) def test_encoder_decoder_model_from_pretrained(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_from_pretrained(**input_ids_dict, return_dict=False) def test_encoder_decoder_model_from_pretrained_return_dict(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_from_pretrained(**input_ids_dict, return_dict=True) def test_save_and_load_from_pretrained(self): input_ids_dict = self.prepare_config_and_inputs() self.check_save_and_load(**input_ids_dict) def test_save_and_load_from_encoder_decoder_pretrained(self): input_ids_dict = self.prepare_config_and_inputs() self.check_save_and_load_encoder_decoder_model(**input_ids_dict) def test_encoder_decoder_model_output_attentions(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_output_attentions(**input_ids_dict) def test_encoder_decoder_model_generate(self): input_ids_dict = self.prepare_config_and_inputs() self.check_encoder_decoder_model_generate(**input_ids_dict) def test_training_gradient_checkpointing(self): inputs_dict = self.prepare_config_and_inputs() encoder_model, decoder_model = self.get_encoder_decoder_model( inputs_dict["config"], inputs_dict["decoder_config"] ) model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) model.to(torch_device) model.train() model.gradient_checkpointing_enable() model.config.decoder_start_token_id = 0 model.config.pad_token_id = 0 model_inputs = { "attention_mask": inputs_dict["attention_mask"], "labels": inputs_dict["labels"], "decoder_input_ids": inputs_dict["decoder_input_ids"], } inputs = inputs_dict["input_features"] if "input_features" in inputs_dict else inputs_dict["input_values"] loss = model(inputs, **model_inputs).loss loss.backward() @slow @require_deterministic_for_xpu def test_real_model_save_load_from_pretrained(self): model_2, inputs = self.get_pretrained_model_and_inputs() model_2.to(torch_device) with torch.no_grad(): outputs = model_2(**inputs) out_2 = outputs[0].cpu().numpy() out_2[np.isnan(out_2)] = 0 with tempfile.TemporaryDirectory() as tmp_dirname: model_2.save_pretrained(tmp_dirname) model_1 = SpeechEncoderDecoderModel.from_pretrained(tmp_dirname) model_1.to(torch_device) after_outputs = model_1(**inputs) out_1 = after_outputs[0].cpu().numpy() out_1[np.isnan(out_1)] = 0 max_diff = np.amax(np.abs(out_1 - out_2)) self.assertLessEqual(max_diff, 1e-5) @unittest.skip("TODO Arthur I have to skip for now because I don't understand it") def test_sdpa_can_dispatch_composite_models(self): inputs_dict = self.prepare_config_and_inputs() encoder_config, decoder_config = inputs_dict["config"], inputs_dict["decoder_config"] config = SpeechEncoderDecoderConfig.from_encoder_decoder_configs( encoder_config=encoder_config, decoder_config=decoder_config ) model = SpeechEncoderDecoderModel(config=config) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model_sdpa = SpeechEncoderDecoderModel.from_pretrained(tmpdirname) model_sdpa = model_sdpa.eval().to(torch_device) # see https://github.com/huggingface/transformers/pull/32238 # Sub-model will dispatch to SDPA if it can (checked below that `SDPA` layers are present) encoder_attn = "sdpa" if model.encoder._supports_sdpa else "eager" decoder_attn = "sdpa" if model.decoder._supports_sdpa else "eager" self.assertTrue(model_sdpa.config._attn_implementation == "sdpa") self.assertTrue(model_sdpa.encoder.config._attn_implementation == encoder_attn) self.assertTrue(model_sdpa.decoder.config._attn_implementation == decoder_attn) # Also test that nothing break if we request SDPA explicitly, when both sub-parts support it. # If the model supports sdpa (i.e. all of sub-models supports it) we'll dispatch safely # Otherwise we should raise error that SDPA is not supported, as some of the sub-models doesn't support if encoder_attn == "sdpa" and decoder_attn == "sdpa": model_sdpa_explicit = SpeechEncoderDecoderModel.from_pretrained(tmpdirname, attn_implementation="sdpa") model_sdpa_explicit = model_sdpa_explicit.eval().to(torch_device) self.assertTrue(model_sdpa_explicit.config._attn_implementation == "sdpa") else: with self.assertRaises(ValueError): model_sdpa_explicit = SpeechEncoderDecoderModel.from_pretrained( tmpdirname, attn_implementation="sdpa" ) model_eager = SpeechEncoderDecoderModel.from_pretrained( tmpdirname, attn_implementation="eager", ) model_eager = model_eager.eval().to(torch_device) self.assertTrue(model_eager.config._attn_implementation == "eager") self.assertTrue(model_eager.encoder.config._attn_implementation == "eager") self.assertTrue(model_eager.decoder.config._attn_implementation == "eager") for name, submodule in model_eager.named_modules(): class_name = submodule.__class__.__name__ if "SdpaAttention" in class_name or "SdpaSelfAttention" in class_name: raise ValueError("The eager model should not have SDPA attention layers") @require_torch class Wav2Vec2BertModelTest(EncoderDecoderMixin, unittest.TestCase): def get_pretrained_model_and_inputs(self): model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained( "facebook/wav2vec2-base-960h", "google-bert/bert-base-cased" ) batch_size = 13 input_values = floats_tensor([batch_size, 512], scale=1.0) attention_mask = random_attention_mask([batch_size, 512]) decoder_input_ids = ids_tensor([batch_size, 4], model.decoder.config.vocab_size) decoder_attention_mask = random_attention_mask([batch_size, 4]) inputs = { "input_values": input_values, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, } return model, inputs def get_encoder_decoder_model(self, config, decoder_config): encoder_model = Wav2Vec2Model(config).eval() decoder_model = BertLMHeadModel(decoder_config).eval() return encoder_model, decoder_model def prepare_config_and_inputs(self): bert_model_tester = BertModelTester(self) wav2vec2_model_tester = Wav2Vec2ModelTester(self) encoder_config_and_inputs = wav2vec2_model_tester.prepare_config_and_inputs() decoder_config_and_inputs = bert_model_tester.prepare_config_and_inputs_for_decoder() ( config, input_values, input_mask, ) = encoder_config_and_inputs ( decoder_config, decoder_input_ids, decoder_token_type_ids, decoder_input_mask, decoder_sequence_labels, decoder_token_labels, decoder_choice_labels, encoder_attention_mask, _, ) = decoder_config_and_inputs # make sure that cross attention layers are added decoder_config.add_cross_attention = True return { "config": config, "input_values": input_values, "attention_mask": input_mask, "decoder_config": decoder_config, "decoder_input_ids": decoder_input_ids, "decoder_token_type_ids": decoder_token_type_ids, "decoder_attention_mask": decoder_input_mask, "decoder_sequence_labels": decoder_sequence_labels, "decoder_token_labels": decoder_token_labels, "decoder_choice_labels": decoder_choice_labels, "labels": decoder_token_labels, } @require_torch class Speech2TextBertModelTest(EncoderDecoderMixin, unittest.TestCase): def get_pretrained_model_and_inputs(self): model = SpeechEncoderDecoderModel.from_encoder_decoder_pretrained( "facebook/s2t-small-librispeech-asr", "google-bert/bert-base-cased" ) batch_size = 13 input_features = floats_tensor([batch_size, 7, 80], scale=1.0) attention_mask = random_attention_mask([batch_size, 7]) decoder_input_ids = ids_tensor([batch_size, 4], model.decoder.config.vocab_size) decoder_attention_mask = random_attention_mask([batch_size, 4]) inputs = { "input_features": input_features, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, } return model, inputs def get_encoder_decoder_model(self, config, decoder_config): encoder_model = Speech2TextEncoder(config).eval() decoder_model = BertLMHeadModel(decoder_config).eval() return encoder_model, decoder_model def prepare_config_and_inputs(self): bert_model_tester = BertModelTester(self) speech2text_model_tester = Speech2TextModelTester(self) encoder_config_and_inputs = speech2text_model_tester.prepare_config_and_inputs() decoder_config_and_inputs = bert_model_tester.prepare_config_and_inputs_for_decoder() config, inputs = encoder_config_and_inputs input_features = inputs["input_features"] input_mask = inputs["attention_mask"] ( decoder_config, decoder_input_ids, decoder_token_type_ids, decoder_input_mask, decoder_sequence_labels, decoder_token_labels, decoder_choice_labels, encoder_attention_mask, _, ) = decoder_config_and_inputs # make sure that cross attention layers are added decoder_config.add_cross_attention = True return { "config": config, "input_features": input_features, "attention_mask": input_mask, "decoder_config": decoder_config, "decoder_input_ids": decoder_input_ids, "decoder_token_type_ids": decoder_token_type_ids, "decoder_attention_mask": decoder_input_mask, "decoder_sequence_labels": decoder_sequence_labels, "decoder_token_labels": decoder_token_labels, "decoder_choice_labels": decoder_choice_labels, "labels": decoder_token_labels, } @unittest.skip(reason="Cannot save full model as Speech2TextModel != Speech2TextEncoder") def test_encoder_decoder_model_from_pretrained_configs(self): pass @require_deterministic_for_xpu @unittest.skip(reason="Cannot save full model as Speech2TextModel != Speech2TextEncoder") def test_save_and_load_from_pretrained(self): pass @require_deterministic_for_xpu @unittest.skip(reason="Cannot save full model as Speech2TextModel != Speech2TextEncoder") def test_real_model_save_load_from_pretrained(self): pass
transformers/tests/models/speech_encoder_decoder/test_modeling_speech_encoder_decoder.py/0
{ "file_path": "transformers/tests/models/speech_encoder_decoder/test_modeling_speech_encoder_decoder.py", "repo_id": "transformers", "token_count": 12553 }
560
# Copyright 2020 The SqueezeBert authors and 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 from transformers import SqueezeBertTokenizer, SqueezeBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import use_cache_if_possible # Avoid import `BertTokenizationTest` directly as it will run as `test_tokenization_squeezebert.py::BertTokenizationTest` # together with `test_tokenization_bert.py::BertTokenizationTest`. from ..bert import test_tokenization_bert @require_tokenizers class SqueezeBertTokenizationTest(test_tokenization_bert.BertTokenizationTest): tokenizer_class = SqueezeBertTokenizer rust_tokenizer_class = SqueezeBertTokenizerFast test_rust_tokenizer = True from_pretrained_id = "squeezebert/squeezebert-uncased" @classmethod @use_cache_if_possible @lru_cache(maxsize=64) def get_rust_tokenizer(cls, pretrained_name=None, **kwargs): pretrained_name = pretrained_name or cls.tmpdirname return SqueezeBertTokenizerFast.from_pretrained(pretrained_name, **kwargs) @slow def test_sequence_builders(self): tokenizer = SqueezeBertTokenizer.from_pretrained("squeezebert/squeezebert-mnli-headless") text = tokenizer.encode("sequence builders", add_special_tokens=False) text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False) encoded_sentence = tokenizer.build_inputs_with_special_tokens(text) encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_2 + [ tokenizer.sep_token_id ]
transformers/tests/models/squeezebert/test_tokenization_squeezebert.py/0
{ "file_path": "transformers/tests/models/squeezebert/test_tokenization_squeezebert.py", "repo_id": "transformers", "token_count": 816 }
561
# Copyright 2022 HuggingFace Inc. # # 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 unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import Swin2SRImageProcessor if is_torchvision_available(): from transformers import Swin2SRImageProcessorFast from transformers.image_transforms import get_image_size class Swin2SRImageProcessingTester: def __init__( self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_rescale=True, rescale_factor=1 / 255, do_pad=True, pad_size=8, ): self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_rescale = do_rescale self.rescale_factor = rescale_factor self.do_pad = do_pad self.pad_size = pad_size def prepare_image_processor_dict(self): return { "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, "pad_size": self.pad_size, } def expected_output_image_shape(self, images): img = images[0] if isinstance(img, Image.Image): input_width, input_height = img.size elif isinstance(img, np.ndarray): input_height, input_width = img.shape[-3:-1] else: input_height, input_width = img.shape[-2:] pad_height = (input_height // self.pad_size + 1) * self.pad_size - input_height pad_width = (input_width // self.pad_size + 1) * self.pad_size - input_width return self.num_channels, input_height + pad_height, input_width + pad_width def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision class Swin2SRImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = Swin2SRImageProcessor if is_vision_available() else None fast_image_processing_class = Swin2SRImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester = Swin2SRImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processing, "do_rescale")) self.assertTrue(hasattr(image_processing, "rescale_factor")) self.assertTrue(hasattr(image_processing, "do_pad")) self.assertTrue(hasattr(image_processing, "pad_size")) def calculate_expected_size(self, image): old_height, old_width = get_image_size(image) size = self.image_processor_tester.pad_size pad_height = (old_height // size + 1) * size - old_height pad_width = (old_width // size + 1) * size - old_width return old_height + pad_height, old_width + pad_width # Swin2SRImageProcessor does not support batched input def test_call_pil(self): # Initialize image_processing image_processing = self.image_processing_class(**self.image_processor_dict) # create random PIL images image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False) for image in image_inputs: self.assertIsInstance(image, Image.Image) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Swin2SRImageProcessor does not support batched input def test_call_numpy(self): # Initialize image_processing image_processing = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) for image in image_inputs: self.assertIsInstance(image, np.ndarray) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Swin2SRImageProcessor does not support batched input def test_call_numpy_4_channels(self): # Initialize image_processing image_processing = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors self.image_processor_tester.num_channels = 4 image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) for image in image_inputs: self.assertIsInstance(image, np.ndarray) # Test not batched input encoded_images = image_processing( image_inputs[0], return_tensors="pt", input_data_format="channels_last" ).pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) self.image_processor_tester.num_channels = 3 # Swin2SRImageProcessor does not support batched input def test_call_pytorch(self): # Initialize image_processing image_processing = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) for image in image_inputs: self.assertIsInstance(image, torch.Tensor) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) @unittest.skip(reason="No speed gain on CPU due to minimal processing.") def test_fast_is_faster_than_slow(self): pass def test_slow_fast_equivalence_batched(self): image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True) image_processor_slow = self.image_processing_class(**self.image_processor_dict) image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict) encoded_slow = image_processor_slow(image_inputs, return_tensors="pt") encoded_fast = image_processor_fast(image_inputs, return_tensors="pt") self._assert_slow_fast_tensors_equivalence(encoded_slow.pixel_values, encoded_fast.pixel_values)
transformers/tests/models/swin2sr/test_image_processing_swin2sr.py/0
{ "file_path": "transformers/tests/models/swin2sr/test_image_processing_swin2sr.py", "repo_id": "transformers", "token_count": 3344 }
562
import os import shutil import tempfile import unittest import pytest from transformers.models.xlm_roberta.tokenization_xlm_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_vision, ) from transformers.utils import is_vision_available from ...test_processing_common import ProcessorTesterMixin if is_vision_available(): from transformers import TrOCRProcessor, ViTImageProcessor, XLMRobertaTokenizerFast @require_sentencepiece @require_tokenizers @require_vision class TrOCRProcessorTest(ProcessorTesterMixin, unittest.TestCase): text_input_name = "labels" processor_class = TrOCRProcessor @classmethod def setUpClass(cls): cls.tmpdirname = tempfile.mkdtemp() vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"] # fmt: skip cls.vocab_file = os.path.join(cls.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) with open(cls.vocab_file, "w", encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) image_processor = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit") tokenizer = XLMRobertaTokenizerFast.from_pretrained("FacebookAI/xlm-roberta-base") processor = TrOCRProcessor(image_processor=image_processor, tokenizer=tokenizer) processor.save_pretrained(cls.tmpdirname) @classmethod def tearDownClass(cls): shutil.rmtree(cls.tmpdirname, ignore_errors=True) def get_tokenizer(self, **kwargs): return XLMRobertaTokenizerFast.from_pretrained(self.tmpdirname, **kwargs) def get_image_processor(self, **kwargs): return ViTImageProcessor.from_pretrained(self.tmpdirname, **kwargs) def test_save_load_pretrained_default(self): with tempfile.TemporaryDirectory() as tmpdir: image_processor = self.get_image_processor() tokenizer = self.get_tokenizer() processor = TrOCRProcessor(image_processor=image_processor, tokenizer=tokenizer) processor.save_pretrained(tmpdir) processor = TrOCRProcessor.from_pretrained(tmpdir) self.assertIsInstance(processor.tokenizer, XLMRobertaTokenizerFast) self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab()) self.assertIsInstance(processor.image_processor, ViTImageProcessor) self.assertEqual(processor.image_processor.to_json_string(), image_processor.to_json_string()) def test_save_load_pretrained_additional_features(self): with tempfile.TemporaryDirectory() as tmpdir: processor = TrOCRProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor()) processor.save_pretrained(tmpdir) tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)") image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0) processor = TrOCRProcessor.from_pretrained( tmpdir, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0 ) self.assertIsInstance(processor.tokenizer, XLMRobertaTokenizerFast) self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor, ViTImageProcessor) def test_image_processor(self): image_processor = self.get_image_processor() tokenizer = self.get_tokenizer() processor = TrOCRProcessor(tokenizer=tokenizer, image_processor=image_processor) image_input = self.prepare_image_inputs() input_feat_extract = image_processor(image_input, return_tensors="np") input_processor = processor(images=image_input, return_tensors="np") for key in input_feat_extract: self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) def test_tokenizer(self): image_processor = self.get_image_processor() tokenizer = self.get_tokenizer() processor = TrOCRProcessor(tokenizer=tokenizer, image_processor=image_processor) input_str = "lower newer" encoded_processor = processor(text=input_str) encoded_tok = tokenizer(input_str) for key in encoded_tok: self.assertListEqual(encoded_tok[key], encoded_processor[key]) def test_processor_text(self): image_processor = self.get_image_processor() tokenizer = self.get_tokenizer() processor = TrOCRProcessor(tokenizer=tokenizer, image_processor=image_processor) input_str = "lower newer" image_input = self.prepare_image_inputs() inputs = processor(text=input_str, images=image_input) self.assertListEqual(list(inputs.keys()), ["pixel_values", "labels"]) # test if it raises when no input is passed with pytest.raises(ValueError): processor() def test_tokenizer_decode(self): image_processor = self.get_image_processor() tokenizer = self.get_tokenizer() processor = TrOCRProcessor(tokenizer=tokenizer, image_processor=image_processor) predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] decoded_processor = processor.batch_decode(predicted_ids) decoded_tok = tokenizer.batch_decode(predicted_ids) self.assertListEqual(decoded_tok, decoded_processor)
transformers/tests/models/trocr/test_processing_trocr.py/0
{ "file_path": "transformers/tests/models/trocr/test_processing_trocr.py", "repo_id": "transformers", "token_count": 2276 }
563
# 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 inspect import random import unittest from datasets import Audio, load_dataset from transformers import UnivNetConfig, UnivNetFeatureExtractor from transformers.testing_utils import ( cleanup, is_torch_available, require_torch, require_torch_accelerator, slow, torch_device, ) from ...test_configuration_common import ConfigTester from ...test_modeling_common import ( ModelTesterMixin, floats_tensor, ) if is_torch_available(): import torch from transformers import UnivNetModel class UnivNetModelTester: def __init__( self, parent, batch_size=2, seq_length=7, in_channels=8, hidden_channels=8, num_mel_bins=20, kernel_predictor_hidden_channels=8, seed=0, is_training=False, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.in_channels = in_channels self.hidden_channels = hidden_channels self.num_mel_bins = num_mel_bins self.kernel_predictor_hidden_channels = kernel_predictor_hidden_channels self.seed = seed self.is_training = is_training def prepare_noise_sequence(self): generator = torch.manual_seed(self.seed) noise_shape = (self.batch_size, self.seq_length, self.in_channels) # Create noise on CPU for reproducibility noise_sequence = torch.randn(noise_shape, generator=generator, dtype=torch.float) return noise_sequence def prepare_config_and_inputs(self): spectrogram = floats_tensor([self.batch_size, self.seq_length, self.num_mel_bins], scale=1.0) noise_sequence = self.prepare_noise_sequence() noise_sequence = noise_sequence.to(spectrogram.device) config = self.get_config() return config, spectrogram, noise_sequence def get_config(self): return UnivNetConfig( model_in_channels=self.in_channels, model_hidden_channels=self.hidden_channels, num_mel_bins=self.num_mel_bins, kernel_predictor_hidden_channels=self.kernel_predictor_hidden_channels, ) def create_and_check_model(self, config, spectrogram, noise_sequence): model = UnivNetModel(config=config).to(torch_device).eval() result = model(spectrogram, noise_sequence)[0] self.parent.assertEqual(result.shape, (self.batch_size, self.seq_length * 256)) def prepare_config_and_inputs_for_common(self): config, spectrogram, noise_sequence = self.prepare_config_and_inputs() inputs_dict = {"input_features": spectrogram, "noise_sequence": noise_sequence} return config, inputs_dict @require_torch class UnivNetModelTest(ModelTesterMixin, unittest.TestCase): all_model_classes = (UnivNetModel,) if is_torch_available() else () # UnivNetModel currently cannot be traced with torch.jit.trace. test_torchscript = False # The UnivNetModel is not a transformer and does not use any attention mechanisms, so skip transformer/attention # related tests. test_pruning = False test_resize_embeddings = False test_resize_position_embeddings = False test_head_masking = False # UnivNetModel is not a sequence classification model. test_mismatched_shapes = False # UnivNetModel does not have a base_model_prefix attribute. test_missing_keys = False # UnivNetModel does not implement a parallelize method. test_model_parallel = False is_encoder_decoder = False has_attentions = False def setUp(self): self.model_tester = UnivNetModelTester(self) self.config_tester = ConfigTester( self, config_class=UnivNetConfig, has_text_modality=False, common_properties=["num_mel_bins"] ) @unittest.skip(reason="fix this once it gets more usage") def test_multi_gpu_data_parallel_forward(self): super().test_multi_gpu_data_parallel_forward() def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_forward_signature(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) signature = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic arg_names = [*signature.parameters.keys()] expected_arg_names = [ "input_features", ] self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) @unittest.skip(reason="UnivNetModel does not output hidden_states.") def test_hidden_states_output(self): pass @unittest.skip(reason="UnivNetModel.forward does not accept an inputs_embeds argument.") def test_inputs_embeds(self): pass @unittest.skip(reason="UnivNetModel does not use input embeddings and thus has no get_input_embeddings method.") def test_model_get_set_embeddings(self): pass @unittest.skip(reason="UnivNetModel does not support all arguments tested, such as output_hidden_states.") def test_model_outputs_equivalence(self): pass @unittest.skip(reason="UnivNetModel does not output hidden_states.") def test_retain_grad_hidden_states_attentions(self): pass def test_batched_inputs_outputs(self): config, inputs = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() batched_spectrogram = inputs["input_features"] batched_noise_sequence = inputs["noise_sequence"] with torch.no_grad(): batched_outputs = model( batched_spectrogram.to(torch_device), batched_noise_sequence.to(torch_device), )[0] self.assertEqual( batched_spectrogram.shape[0], batched_outputs.shape[0], msg="Got different batch dims for input and output", ) def test_unbatched_inputs_outputs(self): config, inputs = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model( inputs["input_features"][:1].to(torch_device), inputs["noise_sequence"][:1].to(torch_device) )[0] self.assertTrue(outputs.shape[0] == 1, msg="Unbatched input should create batched output with bsz = 1") @require_torch_accelerator @slow class UnivNetModelIntegrationTests(unittest.TestCase): def tearDown(self): super().tearDown() cleanup(torch_device, gc_collect=True) def _load_datasamples(self, num_samples, sampling_rate=24000): ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") ds = ds.cast_column("audio", Audio(sampling_rate=sampling_rate)) # automatic decoding with librispeech speech_samples = ds.sort("id")[:num_samples]["audio"] return [x["array"] for x in speech_samples], [x["sampling_rate"] for x in speech_samples] def get_inputs(self, device, num_samples: int = 3, noise_length: int = 10, seed: int = 0): generator = torch.manual_seed(seed) # Note: hardcode model_in_channels -> 64 if num_samples == 1: noise_sequence_shape = (64, noise_length) else: noise_sequence_shape = (num_samples, 64, noise_length) # Explicitly generate noise_sequence on CPU for consistency. noise_sequence = torch.randn(noise_sequence_shape, generator=generator, dtype=torch.float32, device="cpu") # Put noise_sequence on the desired device. noise_sequence = noise_sequence.to(device) # Note: hardcode num_mel_channels -> 100 if num_samples == 1: spectrogram_shape = [100, noise_length] else: spectrogram_shape = [num_samples, 100, noise_length] spectrogram = floats_tensor(spectrogram_shape, scale=1.0, rng=random.Random(seed)) # Note: spectrogram should already be on torch_device # Permute to match diffusers implementation if num_samples == 1: noise_sequence = noise_sequence.transpose(1, 0) spectrogram = spectrogram.transpose(1, 0) else: noise_sequence = noise_sequence.transpose(2, 1) spectrogram = spectrogram.transpose(2, 1) inputs = { "input_features": spectrogram, "noise_sequence": noise_sequence, "generator": generator, } return inputs def test_model_inference_batched(self): # Load sample checkpoint from Tortoise TTS model = UnivNetModel.from_pretrained("dg845/univnet-dev") model.eval().to(torch_device) # Get batched noise and spectrogram inputs. input_speech = self.get_inputs(torch_device, num_samples=3) with torch.no_grad(): waveform = model(**input_speech)[0] waveform = waveform.cpu() waveform_mean = torch.mean(waveform) waveform_stddev = torch.std(waveform) waveform_slice = waveform[-1, -9:].flatten() EXPECTED_MEAN = torch.tensor(-0.19989729) EXPECTED_STDDEV = torch.tensor(0.35230172) EXPECTED_SLICE = torch.tensor([-0.3408, -0.6045, -0.5052, 0.1160, -0.1556, -0.0405, -0.3024, -0.5290, -0.5019]) torch.testing.assert_close(waveform_mean, EXPECTED_MEAN, rtol=1e-4, atol=1e-4) torch.testing.assert_close(waveform_stddev, EXPECTED_STDDEV, rtol=1e-4, atol=1e-4) torch.testing.assert_close(waveform_slice, EXPECTED_SLICE, rtol=5e-4, atol=5e-4) def test_model_inference_unbatched(self): # Load sample checkpoint from Tortoise TTS model = UnivNetModel.from_pretrained("dg845/univnet-dev") model.eval().to(torch_device) # Get unbatched noise and spectrogram inputs. input_speech = self.get_inputs(torch_device, num_samples=1) with torch.no_grad(): waveform = model(**input_speech)[0] waveform = waveform.cpu() waveform_mean = torch.mean(waveform) waveform_stddev = torch.std(waveform) waveform_slice = waveform[-1, -9:].flatten() EXPECTED_MEAN = torch.tensor(-0.22895093) EXPECTED_STDDEV = torch.tensor(0.33986747) EXPECTED_SLICE = torch.tensor([-0.3276, -0.5504, -0.3484, 0.3574, -0.0373, -0.1826, -0.4880, -0.6431, -0.5162]) torch.testing.assert_close(waveform_mean, EXPECTED_MEAN, rtol=1e-4, atol=1e-4) torch.testing.assert_close(waveform_stddev, EXPECTED_STDDEV, rtol=1e-4, atol=1e-4) torch.testing.assert_close(waveform_slice, EXPECTED_SLICE, rtol=1e-3, atol=1e-3) def test_integration(self): feature_extractor = UnivNetFeatureExtractor.from_pretrained("dg845/univnet-dev") model = UnivNetModel.from_pretrained("dg845/univnet-dev") model.eval().to(torch_device) audio, sr = self._load_datasamples(1, sampling_rate=feature_extractor.sampling_rate) input_features = feature_extractor(audio, sampling_rate=sr[0], return_tensors="pt").input_features input_features = input_features.to(device=torch_device) input_speech = self.get_inputs(torch_device, num_samples=1, noise_length=input_features.shape[1]) input_speech["input_features"] = input_features with torch.no_grad(): waveform = model(**input_speech)[0] waveform = waveform.cpu() waveform_mean = torch.mean(waveform) waveform_stddev = torch.std(waveform) waveform_slice = waveform[-1, -9:].flatten() EXPECTED_MEAN = torch.tensor(0.00051374) EXPECTED_STDDEV = torch.tensor(0.058105603) # fmt: off EXPECTED_SLICE = torch.tensor([-4.3934e-04, -1.8203e-04, -3.3033e-04, -3.8716e-04, -1.6125e-04, 3.5389e-06, -3.3149e-04, -3.7613e-04, -2.3331e-04]) # fmt: on torch.testing.assert_close(waveform_mean, EXPECTED_MEAN, rtol=5e-6, atol=5e-6) torch.testing.assert_close(waveform_stddev, EXPECTED_STDDEV, rtol=1e-4, atol=1e-4) torch.testing.assert_close(waveform_slice, EXPECTED_SLICE, rtol=5e-6, atol=5e-6)
transformers/tests/models/univnet/test_modeling_univnet.py/0
{ "file_path": "transformers/tests/models/univnet/test_modeling_univnet.py", "repo_id": "transformers", "token_count": 5739 }
564
# Copyright 2023 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. """Testing suite for the PyTorch VitMatte model.""" import unittest from huggingface_hub import hf_hub_download from transformers import VitMatteConfig from transformers.testing_utils import ( require_timm, require_torch, slow, torch_device, ) from transformers.utils import is_torch_available, is_vision_available from transformers.utils.import_utils import get_torch_major_and_minor_version from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import VitDetConfig, VitMatteForImageMatting if is_vision_available(): from PIL import Image from transformers import VitMatteImageProcessor class VitMatteModelTester: def __init__( self, parent, batch_size=13, image_size=32, patch_size=16, num_channels=4, is_training=True, use_labels=False, hidden_size=2, num_hidden_layers=2, num_attention_heads=2, hidden_act="gelu", type_sequence_label_size=10, initializer_range=0.02, scope=None, out_features=["stage1"], fusion_hidden_sizes=[128, 64, 32, 16], ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.is_training = is_training self.use_labels = use_labels self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.scope = scope self.out_features = out_features self.fusion_hidden_sizes = fusion_hidden_sizes self.seq_length = (self.image_size // self.patch_size) ** 2 def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) labels = None if self.use_labels: raise NotImplementedError("Training is not yet supported") config = self.get_config() return config, pixel_values, labels def get_backbone_config(self): return VitDetConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, hidden_size=self.hidden_size, is_training=self.is_training, hidden_act=self.hidden_act, out_features=self.out_features, ) def get_config(self): return VitMatteConfig( backbone_config=self.get_backbone_config(), backbone=None, hidden_size=self.hidden_size, fusion_hidden_sizes=self.fusion_hidden_sizes, ) def create_and_check_model(self, config, pixel_values, labels): model = VitMatteForImageMatting(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertEqual(result.alphas.shape, (self.batch_size, 1, self.image_size, self.image_size)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values, labels = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class VitMatteModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as VitMatte does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (VitMatteForImageMatting,) if is_torch_available() else () pipeline_model_mapping = {} fx_compatible = False test_pruning = False test_resize_embeddings = False test_head_masking = False test_torch_exportable = True test_torch_exportable_strictly = get_torch_major_and_minor_version() != "2.7" def setUp(self): self.model_tester = VitMatteModelTester(self) self.config_tester = ConfigTester( self, config_class=VitMatteConfig, has_text_modality=False, hidden_size=37, common_properties=["hidden_size"], ) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="VitMatte does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="Training is not yet supported") def test_training(self): pass @unittest.skip(reason="Training is not yet supported") def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant_false(self): pass @unittest.skip(reason="ViTMatte does not support input and output embeddings") def test_model_get_set_embeddings(self): pass def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) @slow def test_model_from_pretrained(self): model_name = "hustvl/vitmatte-small-composition-1k" model = VitMatteForImageMatting.from_pretrained(model_name) self.assertIsNotNone(model) @unittest.skip(reason="ViTMatte does not support retaining gradient on attention logits") def test_retain_grad_hidden_states_attentions(self): pass def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states expected_num_layers = getattr( self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(hidden_states), expected_num_layers) self.assertListEqual( list(hidden_states[0].shape[-2:]), [2, 2], ) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True print("Hello we're here") check_hidden_states_output(inputs_dict, config, model_class) @require_timm def test_backbone_selection(self): def _validate_backbone_init(): for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() if model.__class__.__name__ == "VitMatteForImageMatting": # Confirm out_indices propagated to backbone self.assertEqual(len(model.backbone.out_indices), 2) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.use_pretrained_backbone = True config.backbone_config = None config.backbone_kwargs = {"out_indices": [-2, -1]} # Force load_backbone path config.is_hybrid = False # Load a timm backbone config.backbone = "resnet18" config.use_timm_backbone = True _validate_backbone_init() # Load a HF backbone config.backbone = "facebook/dinov2-small" config.use_timm_backbone = False _validate_backbone_init() @require_torch class VitMatteModelIntegrationTest(unittest.TestCase): @slow def test_inference(self): processor = VitMatteImageProcessor.from_pretrained("hustvl/vitmatte-small-composition-1k") model = VitMatteForImageMatting.from_pretrained("hustvl/vitmatte-small-composition-1k").to(torch_device) filepath = hf_hub_download( repo_id="hf-internal-testing/image-matting-fixtures", filename="image.png", repo_type="dataset" ) image = Image.open(filepath).convert("RGB") filepath = hf_hub_download( repo_id="hf-internal-testing/image-matting-fixtures", filename="trimap.png", repo_type="dataset" ) trimap = Image.open(filepath).convert("L") # prepare image + trimap for the model inputs = processor(images=image, trimaps=trimap, return_tensors="pt").to(torch_device) with torch.no_grad(): alphas = model(**inputs).alphas expected_shape = torch.Size((1, 1, 640, 960)) self.assertEqual(alphas.shape, expected_shape) expected_slice = torch.tensor( [[0.9977, 0.9987, 0.9990], [0.9980, 0.9998, 0.9998], [0.9983, 0.9998, 0.9998]], device=torch_device ) torch.testing.assert_close(alphas[0, 0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
transformers/tests/models/vitmatte/test_modeling_vitmatte.py/0
{ "file_path": "transformers/tests/models/vitmatte/test_modeling_vitmatte.py", "repo_id": "transformers", "token_count": 4527 }
565
# 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 unittest from transformers import is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, ) if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_tokenizers @require_torch class XLMRobertaModelIntegrationTest(unittest.TestCase): @slow def test_xlm_roberta_base(self): model = XLMRobertaModel.from_pretrained("FacebookAI/xlm-roberta-base", attn_implementation="eager") input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) # The dog is cute and lives in the garden house expected_output_shape = torch.Size((1, 12, 768)) # batch_size, sequence_length, embedding_vector_dim expected_output_values_last_dim = torch.tensor( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): output = model(input_ids)["last_hidden_state"].detach() self.assertEqual(output.shape, expected_output_shape) # compare the actual values for a slice of last dim torch.testing.assert_close(output[:, :, -1], expected_output_values_last_dim, rtol=1e-3, atol=1e-3) def test_xlm_roberta_base_sdpa(self): input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) # The dog is cute and lives in the garden house expected_output_shape = torch.Size((1, 12, 768)) # batch_size, sequence_length, embedding_vector_dim expected_output_values_last_dim = torch.tensor( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) model = XLMRobertaModel.from_pretrained("FacebookAI/xlm-roberta-base", attn_implementation="sdpa") with torch.no_grad(): output = model(input_ids)["last_hidden_state"].detach() self.assertEqual(output.shape, expected_output_shape) # compare the actual values for a slice of last dim torch.testing.assert_close(output[:, :, -1], expected_output_values_last_dim, rtol=1e-3, atol=1e-3) @slow def test_xlm_roberta_large(self): model = XLMRobertaModel.from_pretrained("FacebookAI/xlm-roberta-large") input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) # The dog is cute and lives in the garden house expected_output_shape = torch.Size((1, 12, 1024)) # batch_size, sequence_length, embedding_vector_dim expected_output_values_last_dim = torch.tensor( [[-0.0699, -0.0318, 0.0705, -0.1241, 0.0999, -0.0520, 0.1004, -0.1838, -0.4704, 0.1437, 0.0821, 0.0126]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): output = model(input_ids)["last_hidden_state"].detach() self.assertEqual(output.shape, expected_output_shape) # compare the actual values for a slice of last dim torch.testing.assert_close(output[:, :, -1], expected_output_values_last_dim, rtol=1e-3, atol=1e-3)
transformers/tests/models/xlm_roberta/test_modeling_xlm_roberta.py/0
{ "file_path": "transformers/tests/models/xlm_roberta/test_modeling_xlm_roberta.py", "repo_id": "transformers", "token_count": 1740 }
566
# 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 unittest import numpy as np from transformers import ( MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING, AutoProcessor, TextToAudioPipeline, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, require_torch, require_torch_accelerator, require_torch_or_tf, slow, torch_device, ) from transformers.trainer_utils import set_seed from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class TextToAudioPipelineTests(unittest.TestCase): model_mapping = MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING # for now only test text_to_waveform and not text_to_spectrogram @require_torch def test_small_musicgen_pt(self): music_generator = pipeline( task="text-to-audio", model="facebook/musicgen-small", framework="pt", do_sample=False, max_new_tokens=5 ) outputs = music_generator("This is a test") self.assertEqual({"audio": ANY(np.ndarray), "sampling_rate": 32000}, outputs) # test two examples side-by-side outputs = music_generator(["This is a test", "This is a second test"]) audio = [output["audio"] for output in outputs] self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) # test batching, this time with parameterization in the forward pass music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small", framework="pt") forward_params = {"do_sample": False, "max_new_tokens": 5} outputs = music_generator( ["This is a test", "This is a second test"], forward_params=forward_params, batch_size=2 ) audio = [output["audio"] for output in outputs] self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) @slow @require_torch def test_medium_seamless_m4t_pt(self): speech_generator = pipeline( task="text-to-audio", model="facebook/hf-seamless-m4t-medium", framework="pt", max_new_tokens=5 ) for forward_params in [{"tgt_lang": "eng"}, {"return_intermediate_token_ids": True, "tgt_lang": "eng"}]: outputs = speech_generator("This is a test", forward_params=forward_params) self.assertEqual({"audio": ANY(np.ndarray), "sampling_rate": 16000}, outputs) # test two examples side-by-side outputs = speech_generator(["This is a test", "This is a second test"], forward_params=forward_params) audio = [output["audio"] for output in outputs] self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) # test batching outputs = speech_generator( ["This is a test", "This is a second test"], forward_params=forward_params, batch_size=2 ) audio = [output["audio"] for output in outputs] self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) @slow @require_torch def test_small_bark_pt(self): speech_generator = pipeline(task="text-to-audio", model="suno/bark-small", framework="pt") forward_params = { # Using `do_sample=False` to force deterministic output "do_sample": False, "semantic_max_new_tokens": 5, } outputs = speech_generator("This is a test", forward_params=forward_params) self.assertEqual( {"audio": ANY(np.ndarray), "sampling_rate": 24000}, outputs, ) # test two examples side-by-side outputs = speech_generator( ["This is a test", "This is a second test"], forward_params=forward_params, ) audio = [output["audio"] for output in outputs] self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) # test other generation strategy forward_params = { "do_sample": True, "semantic_max_new_tokens": 5, "semantic_num_return_sequences": 2, } outputs = speech_generator("This is a test", forward_params=forward_params) audio = outputs["audio"] self.assertEqual(ANY(np.ndarray), audio) # test using a speaker embedding processor = AutoProcessor.from_pretrained("suno/bark-small") temp_inp = processor("hey, how are you?", voice_preset="v2/en_speaker_5") history_prompt = temp_inp["history_prompt"] forward_params["history_prompt"] = history_prompt outputs = speech_generator( ["This is a test", "This is a second test"], forward_params=forward_params, batch_size=2, ) audio = [output["audio"] for output in outputs] self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) @slow @require_torch_accelerator def test_conversion_additional_tensor(self): speech_generator = pipeline(task="text-to-audio", model="suno/bark-small", framework="pt", device=torch_device) processor = AutoProcessor.from_pretrained("suno/bark-small") forward_params = { "do_sample": True, "semantic_max_new_tokens": 5, } # atm, must do to stay coherent with BarkProcessor preprocess_params = { "max_length": 256, "add_special_tokens": False, "return_attention_mask": True, "return_token_type_ids": False, "padding": "max_length", } outputs = speech_generator( "This is a test", forward_params=forward_params, preprocess_params=preprocess_params, ) temp_inp = processor("hey, how are you?", voice_preset="v2/en_speaker_5") history_prompt = temp_inp["history_prompt"] forward_params["history_prompt"] = history_prompt # history_prompt is a torch.Tensor passed as a forward_param # if generation is successful, it means that it was passed to the right device outputs = speech_generator( "This is a test", forward_params=forward_params, preprocess_params=preprocess_params ) self.assertEqual( {"audio": ANY(np.ndarray), "sampling_rate": 24000}, outputs, ) @require_torch def test_vits_model_pt(self): speech_generator = pipeline(task="text-to-audio", model="facebook/mms-tts-eng", framework="pt") outputs = speech_generator("This is a test") self.assertEqual(outputs["sampling_rate"], 16000) audio = outputs["audio"] self.assertEqual(ANY(np.ndarray), audio) # test two examples side-by-side outputs = speech_generator(["This is a test", "This is a second test"]) audio = [output["audio"] for output in outputs] self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio) # test batching outputs = speech_generator(["This is a test", "This is a second test"], batch_size=2) self.assertEqual(ANY(np.ndarray), outputs[0]["audio"]) @require_torch def test_forward_model_kwargs(self): # use vits - a forward model speech_generator = pipeline(task="text-to-audio", model="kakao-enterprise/vits-vctk", framework="pt") # for reproducibility set_seed(555) outputs = speech_generator("This is a test", forward_params={"speaker_id": 5}) audio = outputs["audio"] with self.assertRaises(TypeError): # assert error if generate parameter outputs = speech_generator("This is a test", forward_params={"speaker_id": 5, "do_sample": True}) forward_params = {"speaker_id": 5} generate_kwargs = {"do_sample": True} with self.assertRaises(ValueError): # assert error if generate_kwargs with forward-only models outputs = speech_generator( "This is a test", forward_params=forward_params, generate_kwargs=generate_kwargs ) self.assertTrue(np.abs(outputs["audio"] - audio).max() < 1e-5) @require_torch def test_generative_model_kwargs(self): # use musicgen - a generative model music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small", framework="pt") forward_params = { "do_sample": True, "max_new_tokens": 20, } # for reproducibility set_seed(555) outputs = music_generator("This is a test", forward_params=forward_params) audio = outputs["audio"] self.assertEqual(ANY(np.ndarray), audio) # make sure generate kwargs get priority over forward params forward_params = { "do_sample": False, "max_new_tokens": 20, } generate_kwargs = {"do_sample": True} # for reproducibility set_seed(555) outputs = music_generator("This is a test", forward_params=forward_params, generate_kwargs=generate_kwargs) self.assertListEqual(outputs["audio"].tolist(), audio.tolist()) def get_test_pipeline( self, model, tokenizer=None, image_processor=None, feature_extractor=None, processor=None, dtype="float32", ): model_test_kwargs = {} if model.can_generate(): # not all models in this pipeline can generate and, therefore, take `generate` kwargs model_test_kwargs["max_new_tokens"] = 5 model.config._attn_implementation = "eager" speech_generator = TextToAudioPipeline( model=model, tokenizer=tokenizer, feature_extractor=feature_extractor, image_processor=image_processor, processor=processor, dtype=dtype, **model_test_kwargs, ) return speech_generator, ["This is a test", "Another test"] def run_pipeline_test(self, speech_generator, _): outputs = speech_generator("This is a test") self.assertEqual(ANY(np.ndarray), outputs["audio"]) forward_params = ( {"num_return_sequences": 2, "do_sample": True} if speech_generator.model.can_generate() else {} ) outputs = speech_generator(["This is great !", "Something else"], forward_params=forward_params) audio = [output["audio"] for output in outputs] self.assertEqual([ANY(np.ndarray), ANY(np.ndarray)], audio)
transformers/tests/pipelines/test_pipelines_text_to_audio.py/0
{ "file_path": "transformers/tests/pipelines/test_pipelines_text_to_audio.py", "repo_id": "transformers", "token_count": 4637 }
567
# 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. import gc import unittest from transformers import ( AutoConfig, AutoModelForCausalLM, AutoTokenizer, BitNetQuantConfig, OPTForCausalLM, ) from transformers.testing_utils import ( backend_empty_cache, require_accelerate, require_torch_gpu, slow, torch_device, ) from transformers.utils import is_accelerate_available, is_torch_available if is_torch_available(): import torch if is_accelerate_available(): from accelerate import init_empty_weights @require_torch_gpu class BitNetQuantConfigTest(unittest.TestCase): def test_to_dict(self): """ Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object """ quantization_config = BitNetQuantConfig() config_to_dict = quantization_config.to_dict() for key in config_to_dict: self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) @slow @require_torch_gpu @require_accelerate class BitNetTest(unittest.TestCase): model_name = "HF1BitLLM/Llama3-8B-1.58-100B-tokens" # called only once for all test in this class @classmethod def setUpClass(cls): """ Load the model """ cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) cls.quantized_model = AutoModelForCausalLM.from_pretrained(cls.model_name, device_map=torch_device) def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() def test_replace_with_bitlinear(self): from transformers.integrations import BitLinear, replace_with_bitnet_linear model_id = "facebook/opt-350m" config = AutoConfig.from_pretrained(model_id) with init_empty_weights(): model = OPTForCausalLM(config) nb_linears = 0 for module in model.modules(): if isinstance(module, torch.nn.Linear): nb_linears += 1 model = replace_with_bitnet_linear(model) nb_bitnet_linear = 0 for module in model.modules(): if isinstance(module, BitLinear): nb_bitnet_linear += 1 self.assertEqual(nb_linears - 1, nb_bitnet_linear) def test_quantized_model(self): """ Simple test that checks if the quantized model is working properly """ input_text = "What are we having for dinner?" expected_output = "What are we having for dinner? What are we going to do for fun this weekend?" input_ids = self.tokenizer(input_text, return_tensors="pt").to(torch_device) output = self.quantized_model.generate(**input_ids, max_new_tokens=11, do_sample=False) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), expected_output) def test_packing_unpacking(self): """ Simple test the packing and unpacking logic """ from transformers.integrations import pack_weights, unpack_weights u = torch.randint(0, 255, (256, 256), dtype=torch.uint8) unpacked_u = unpack_weights(u, dtype=torch.bfloat16) repacked_u = pack_weights(unpacked_u) for i in range(u.shape[0]): for j in range(u.shape[1]): self.assertEqual(repacked_u[i][j], u[i][j]) def test_activation_quant(self): """ test the activation function behaviour """ from transformers.integrations import BitLinear layer = BitLinear(in_features=4, out_features=2, bias=False, dtype=torch.float32) layer.to(torch_device) input_tensor = torch.tensor([1.0, -1.0, -1.0, 1.0], dtype=torch.float32).to(torch_device) # Quantize the input tensor quantized_tensor, scale = layer.activation_quant(input_tensor) # Verify the output quantized tensor for i in range(input_tensor.shape[0]): self.assertEqual(quantized_tensor[i] / scale, input_tensor[i]) # Verify the scale tensor self.assertEqual(scale, 127) def test_weights_dtype(self): """ test the weights dtype after loading """ self_attn_q = self.quantized_model.model.layers[0].self_attn.q_proj.weight self_attn_k = self.quantized_model.model.layers[0].self_attn.k_proj.weight self_attn_v = self.quantized_model.model.layers[0].self_attn.v_proj.weight self_attn_o = self.quantized_model.model.layers[0].self_attn.o_proj.weight mlp_gate = self.quantized_model.model.layers[0].mlp.gate_proj.weight mlp_up = self.quantized_model.model.layers[0].mlp.up_proj.weight mlp_down = self.quantized_model.model.layers[0].mlp.down_proj.weight self.assertEqual(self_attn_q.dtype, torch.uint8) self.assertEqual(self_attn_k.dtype, torch.uint8) self.assertEqual(self_attn_v.dtype, torch.uint8) self.assertEqual(self_attn_o.dtype, torch.uint8) self.assertEqual(mlp_up.dtype, torch.uint8) self.assertEqual(mlp_gate.dtype, torch.uint8) self.assertEqual(mlp_down.dtype, torch.uint8) def test_replace_with_bitlinear_shape(self): """ test that the BitNet layer weight shapes are correct, and the weight_scale is correctly initialized to 1 """ from transformers.integrations import replace_with_bitnet_linear out_features = 1024 in_features = 512 class SimpleLinearModule(torch.nn.Module): """ Simple class to test BitLinear """ def __init__( self, in_features: int = in_features, out_features: int = out_features, bias: bool = False, ): super().__init__() self.linear = torch.nn.Linear(in_features=in_features, out_features=out_features, bias=bias) def forward(self, x): return self.linear(x) model = SimpleLinearModule() replace_with_bitnet_linear(model) self.assertEqual(list(model.linear.weight.shape), [out_features // 4, in_features]) self.assertEqual(model.linear.weight_scale, 1) @slow @require_torch_gpu @require_accelerate class BitNetSerializationTest(unittest.TestCase): def test_model_serialization(self): model_name = "HF1BitLLM/Llama3-8B-1.58-100B-tokens" quantized_model = AutoModelForCausalLM.from_pretrained(model_name, device_map=torch_device) input_tensor = torch.zeros((1, 8), dtype=torch.int32, device=torch_device) with torch.no_grad(): logits_ref = quantized_model.forward(input_tensor).logits # Save saved_model_id = "quant_model" quantized_model.save_pretrained(saved_model_id) # Remove old model del quantized_model backend_empty_cache(torch_device) # Load and check if the logits match model_loaded = AutoModelForCausalLM.from_pretrained("quant_model", device_map=torch_device) with torch.no_grad(): logits_loaded = model_loaded.forward(input_tensor).logits self.assertEqual((logits_loaded - logits_ref).abs().mean().item(), 0)
transformers/tests/quantization/bitnet_integration/test_bitnet.py/0
{ "file_path": "transformers/tests/quantization/bitnet_integration/test_bitnet.py", "repo_id": "transformers", "token_count": 3337 }
568
# 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. import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig from transformers.testing_utils import ( Expectations, backend_empty_cache, get_device_properties, require_torch_accelerator, require_torch_multi_accelerator, require_torchao, require_torchao_version_greater_or_equal, torch_device, ) from transformers.utils import is_torch_available, is_torchao_available if is_torch_available(): import torch if is_torchao_available(): # renamed in torchao 0.7.0, please install the latest torchao from torchao.dtypes import ( AffineQuantizedTensor, TensorCoreTiledLayout, ) from torchao.quantization import ( Int8WeightOnlyConfig, IntxWeightOnlyConfig, MappingType, ModuleFqnToConfig, PerAxis, ) from torchao.quantization.autoquant import AQMixin if version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0"): from torchao.dtypes import Int4CPULayout if version.parse(importlib.metadata.version("torchao")) >= version.parse("0.11.0"): from torchao.dtypes import Int4XPULayout def check_torchao_int4_wo_quantized(test_module, qlayer): weight = qlayer.weight test_module.assertEqual(weight.quant_min, 0) test_module.assertEqual(weight.quant_max, 15) test_module.assertTrue(isinstance(weight, AffineQuantizedTensor)) layout = None if weight.device.type == "cpu": layout = Int4CPULayout elif weight.device.type == "xpu": layout = Int4XPULayout elif weight.device.type == "cuda": layout = TensorCoreTiledLayout test_module.assertTrue(isinstance(weight.tensor_impl._layout, layout)) def check_autoquantized(test_module, qlayer): weight = qlayer.weight test_module.assertTrue(isinstance(weight, AQMixin)) def check_forward(test_module, model, batch_size=1, context_size=1024): # Test forward pass with torch.no_grad(): out = model(torch.zeros([batch_size, context_size], device=model.device, dtype=torch.int32)).logits test_module.assertEqual(out.shape[0], batch_size) test_module.assertEqual(out.shape[1], context_size) @require_torchao @require_torchao_version_greater_or_equal("0.8.0") class TorchAoConfigTest(unittest.TestCase): def test_to_dict(self): """ Makes sure the config format is properly set """ quantization_config = TorchAoConfig("int4_weight_only") torchao_orig_config = quantization_config.to_dict() for key in torchao_orig_config: self.assertEqual(getattr(quantization_config, key), torchao_orig_config[key]) def test_post_init_check(self): """ Test kwargs validations in TorchAoConfig """ _ = TorchAoConfig("int4_weight_only") with self.assertRaisesRegex(ValueError, "Unsupported string quantization type"): _ = TorchAoConfig("fp6") with self.assertRaisesRegex(ValueError, "Unexpected keyword arg"): _ = TorchAoConfig("int4_weight_only", group_size1=32) def test_repr(self): """ Check that there is no error in the repr """ quantization_config = TorchAoConfig("int4_weight_only", modules_to_not_convert=["conv"], group_size=8) repr(quantization_config) def test_json_serializable(self): """ Check that the config dict can be JSON serialized. """ quantization_config = TorchAoConfig("int4_weight_only", group_size=32, layout=TensorCoreTiledLayout()) d = quantization_config.to_dict() self.assertIsInstance(d["quant_type_kwargs"]["layout"], list) self.assertTrue("inner_k_tiles" in d["quant_type_kwargs"]["layout"][1]) quantization_config.to_json_string(use_diff=False) @require_torchao @require_torchao_version_greater_or_equal("0.8.0") class TorchAoTest(unittest.TestCase): input_text = "What are we having for dinner?" max_new_tokens = 10 model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" device = "cpu" quant_scheme_kwargs = ( {"group_size": 32, "layout": Int4CPULayout()} if is_torchao_available() and version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0") else {"group_size": 32} ) # called only once for all test in this class @classmethod def setUpClass(cls): cls.EXPECTED_OUTPUT = "What are we having for dinner?\n- 1. What is the temperature outside" def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() def test_int4wo_quant(self): """ Simple LLM model testing int4 weight only quantization """ quant_config = TorchAoConfig("int4_weight_only", **self.quant_scheme_kwargs) # Note: we quantize the bfloat16 model on the fly to int4 quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, dtype=torch.bfloat16, device_map=self.device, quantization_config=quant_config, ) tokenizer = AutoTokenizer.from_pretrained(self.model_name) check_torchao_int4_wo_quantized(self, quantized_model.model.layers[0].self_attn.v_proj) input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) def test_int4wo_quant_bfloat16_conversion(self): """ Testing the dtype of model will be modified to be bfloat16 for int4 weight only quantization """ quant_config = TorchAoConfig("int4_weight_only", **self.quant_scheme_kwargs) # Note: we quantize the bfloat16 model on the fly to int4 quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, dtype=torch.bfloat16, device_map=self.device, quantization_config=quant_config, ) tokenizer = AutoTokenizer.from_pretrained(self.model_name) check_torchao_int4_wo_quantized(self, quantized_model.model.layers[0].self_attn.v_proj) input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) def test_int8_dynamic_activation_int8_weight_quant(self): """ Simple LLM model testing int8_dynamic_activation_int8_weight """ quant_config = TorchAoConfig("int8_dynamic_activation_int8_weight") quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, device_map=self.device, quantization_config=quant_config, ) tokenizer = AutoTokenizer.from_pretrained(self.model_name) input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) EXPECTED_OUTPUT = [ "What are we having for dinner?\n\nJessica: (smiling)", "What are we having for dinner?\n\nJess: (smiling) I", ] self.assertTrue(tokenizer.decode(output[0], skip_special_tokens=True) in EXPECTED_OUTPUT) @require_torchao_version_greater_or_equal("0.11.0") def test_include_input_output_embeddings(self): weight_dtype = torch.int8 granularity = PerAxis(0) mapping_type = MappingType.ASYMMETRIC embedding_config = IntxWeightOnlyConfig( weight_dtype=weight_dtype, granularity=granularity, mapping_type=mapping_type, ) config = ModuleFqnToConfig( {"_default": None, "model.embed_tokens": embedding_config, "lm_head": embedding_config} ) # need set `include_input_output_embeddings` to True quant_config = TorchAoConfig(quant_type=config, include_input_output_embeddings=True) quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, device_map=self.device, quantization_config=quant_config, ) # making sure embedding is quantized self.assertTrue(isinstance(quantized_model.model.embed_tokens.weight, AffineQuantizedTensor)) self.assertTrue(isinstance(quantized_model.lm_head.weight, AffineQuantizedTensor)) tokenizer = AutoTokenizer.from_pretrained(self.model_name) input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) EXPECTED_OUTPUT = [ "What are we having for dinner?\n\nJessica: (smiling)", "What are we having for dinner?\n\nJess: (smiling) I", ] self.assertTrue(tokenizer.decode(output[0], skip_special_tokens=True) in EXPECTED_OUTPUT) @require_torchao_version_greater_or_equal("0.11.0") def test_per_module_config_skip(self): linear_config = Int8WeightOnlyConfig() config = ModuleFqnToConfig({"_default": linear_config, "model.layers.0.self_attn.q_proj": None}) quant_config = TorchAoConfig(quant_type=config) quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, device_map=self.device, quantization_config=quant_config, ) # making sure `model.layers.0.self_attn.q_proj` is skipped self.assertTrue(not isinstance(quantized_model.model.layers[0].self_attn.q_proj.weight, AffineQuantizedTensor)) tokenizer = AutoTokenizer.from_pretrained(self.model_name) input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) EXPECTED_OUTPUT = [ "What are we having for dinner?\n\nJessica: (smiling)", "What are we having for dinner?\n\nJess: (smiling) I", ] self.assertTrue(tokenizer.decode(output[0], skip_special_tokens=True) in EXPECTED_OUTPUT) @require_torch_accelerator class TorchAoAcceleratorTest(TorchAoTest): device = torch_device quant_scheme_kwargs = {"group_size": 32} # called only once for all test in this class @classmethod def setUpClass(cls): super().setUpClass() # fmt: off EXPECTED_OUTPUTS = Expectations( { ("xpu", 3): "What are we having for dinner?\n\nJessica: (smiling)", ("cuda", 7): "What are we having for dinner?\n- 1. What is the temperature outside", } ) # fmt: on cls.EXPECTED_OUTPUT = EXPECTED_OUTPUTS.get_expectation() def test_int4wo_offload(self): """ Simple test that checks if the quantized model int4 weight only is working properly with cpu/disk offload """ device_map_offload = { "model.embed_tokens": 0, "model.layers.0": 0, "model.layers.1": 0, "model.layers.2": 0, "model.layers.3": 0, "model.layers.4": 0, "model.layers.5": 0, "model.layers.6": 0, "model.layers.7": 0, "model.layers.8": 0, "model.layers.9": 0, "model.layers.10": 0, "model.layers.11": 0, "model.layers.12": 0, "model.layers.13": 0, "model.layers.14": 0, "model.layers.15": 0, "model.layers.16": 0, "model.layers.17": 0, "model.layers.18": 0, "model.layers.19": "cpu", "model.layers.20": "cpu", "model.layers.21": "disk", "model.norm": 0, "model.rotary_emb": 0, "lm_head": 0, } quant_config = TorchAoConfig("int4_weight_only", group_size=32) quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, dtype=torch.bfloat16, device_map=device_map_offload, quantization_config=quant_config, ) tokenizer = AutoTokenizer.from_pretrained(self.model_name) input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) # fmt: off EXPECTED_OUTPUTS = Expectations( { ("xpu", 3): "What are we having for dinner?\n\nJessica: (smiling)", ("cuda", 7): "What are we having for dinner?\n- 2. What is the temperature outside", } ) # fmt: on EXPECTED_OUTPUT = EXPECTED_OUTPUTS.get_expectation() output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) generated_text = tokenizer.decode(output[0], skip_special_tokens=True) self.assertEqual(generated_text, EXPECTED_OUTPUT) @require_torch_multi_accelerator def test_int4wo_quant_multi_accelerator(self): """ Simple test that checks if the quantized model int4 weight only is working properly with multiple accelerators set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 CUDA GPUs set ZE_AFFINITY_MASK=0,1 if you have more than 2 Intel XPUs """ quant_config = TorchAoConfig("int4_weight_only", **self.quant_scheme_kwargs) quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, dtype=torch.bfloat16, device_map="auto", quantization_config=quant_config, ) tokenizer = AutoTokenizer.from_pretrained(self.model_name) self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) def test_autoquant(self): """ Simple LLM model testing autoquant """ quant_config = TorchAoConfig("autoquant") quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, dtype="auto", device_map=self.device, quantization_config=quant_config, ) tokenizer = AutoTokenizer.from_pretrained(self.model_name) input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) output = quantized_model.generate( **input_ids, max_new_tokens=self.max_new_tokens, cache_implementation="static" ) quantized_model.finalize_autoquant() check_autoquantized(self, quantized_model.model.layers[0].self_attn.v_proj) EXPECTED_OUTPUT = "What are we having for dinner?\n\nJane: (sighs)" output = quantized_model.generate( **input_ids, max_new_tokens=self.max_new_tokens, cache_implementation="static" ) self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), EXPECTED_OUTPUT) @require_torchao @require_torchao_version_greater_or_equal("0.8.0") class TorchAoSerializationTest(unittest.TestCase): input_text = "What are we having for dinner?" max_new_tokens = 10 model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" quant_scheme = "int4_weight_only" quant_scheme_kwargs = ( {"group_size": 32, "layout": Int4CPULayout()} if is_torchao_available() and version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0") else {"group_size": 32} ) device = "cpu" # called only once for all test in this class @classmethod def setUpClass(cls): cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) cls.EXPECTED_OUTPUT = "What are we having for dinner?\n- 1. What is the temperature outside" def setUp(self): self.quant_config = TorchAoConfig(self.quant_scheme, **self.quant_scheme_kwargs) dtype = torch.bfloat16 if self.quant_scheme == "int4_weight_only" else "auto" self.quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, dtype=dtype, device_map=self.device, quantization_config=self.quant_config, ) def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() def test_original_model_expected_output(self): input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device) output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) def check_serialization_expected_output(self, device, expected_output): """ Test if we can serialize and load/infer the model again on the same device """ dtype = torch.bfloat16 if self.quant_scheme == "int4_weight_only" else "auto" with tempfile.TemporaryDirectory() as tmpdirname: self.quantized_model.save_pretrained(tmpdirname, safe_serialization=False) loaded_quantized_model = AutoModelForCausalLM.from_pretrained(tmpdirname, dtype=dtype, device_map=device) input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(device) output = loaded_quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), expected_output) def test_serialization_expected_output(self): self.check_serialization_expected_output(self.device, self.EXPECTED_OUTPUT) class TorchAoSerializationW8A8CPUTest(TorchAoSerializationTest): quant_scheme, quant_scheme_kwargs = "int8_dynamic_activation_int8_weight", {} # called only once for all test in this class @classmethod def setUpClass(cls): super().setUpClass() cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" @require_torch_accelerator def test_serialization_expected_output_on_accelerator(self): """ Test if we can serialize on device (cpu) and load/infer the model on accelerator """ self.check_serialization_expected_output(torch_device, self.EXPECTED_OUTPUT) class TorchAoSerializationW8CPUTest(TorchAoSerializationTest): quant_scheme, quant_scheme_kwargs = "int8_weight_only", {} # called only once for all test in this class @classmethod def setUpClass(cls): super().setUpClass() cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" @require_torch_accelerator def test_serialization_expected_output_on_accelerator(self): """ Test if we can serialize on device (cpu) and load/infer the model on accelerator """ self.check_serialization_expected_output(torch_device, self.EXPECTED_OUTPUT) @require_torch_accelerator class TorchAoSerializationAcceleratorTest(TorchAoSerializationTest): quant_scheme, quant_scheme_kwargs = "int4_weight_only", {"group_size": 32} device = f"{torch_device}:0" # called only once for all test in this class @classmethod def setUpClass(cls): super().setUpClass() # fmt: off EXPECTED_OUTPUTS = Expectations( { ("xpu", 3): "What are we having for dinner?\n\nJessica: (smiling)", ("cuda", 7): "What are we having for dinner?\n- 1. What is the temperature outside", } ) # fmt: on cls.EXPECTED_OUTPUT = EXPECTED_OUTPUTS.get_expectation() @require_torch_accelerator class TorchAoSerializationW8A8AcceleratorTest(TorchAoSerializationTest): quant_scheme, quant_scheme_kwargs = "int8_dynamic_activation_int8_weight", {} device = f"{torch_device}:0" # called only once for all test in this class @classmethod def setUpClass(cls): super().setUpClass() cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" @require_torch_accelerator class TorchAoSerializationW8AcceleratorTest(TorchAoSerializationTest): quant_scheme, quant_scheme_kwargs = "int8_weight_only", {} device = f"{torch_device}:0" # called only once for all test in this class @classmethod def setUpClass(cls): super().setUpClass() cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" @require_torch_accelerator @require_torchao_version_greater_or_equal("0.10.0") class TorchAoSerializationFP8AcceleratorTest(TorchAoSerializationTest): device = f"{torch_device}:0" # called only once for all test in this class @classmethod def setUpClass(cls): device_type, major, minor = get_device_properties() if device_type == "cuda" and major < 9: raise unittest.SkipTest("CUDA compute capability 9.0 or higher required for FP8 tests") from torchao.quantization import Float8WeightOnlyConfig cls.quant_scheme = Float8WeightOnlyConfig() cls.quant_scheme_kwargs = {} super().setUpClass() cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" @require_torch_accelerator @require_torchao_version_greater_or_equal("0.10.0") class TorchAoSerializationA8W4Test(TorchAoSerializationTest): device = f"{torch_device}:0" # called only once for all test in this class @classmethod def setUpClass(cls): device_type, major, minor = get_device_properties() if device_type == "cuda" and major < 9: raise unittest.SkipTest("CUDA compute capability 9.0 or higher required for FP8 tests") from torchao.quantization import Int8DynamicActivationInt4WeightConfig cls.quant_scheme = Int8DynamicActivationInt4WeightConfig() cls.quant_scheme_kwargs = {} super().setUpClass() cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" if __name__ == "__main__": unittest.main()
transformers/tests/quantization/torchao_integration/test_torchao.py/0
{ "file_path": "transformers/tests/quantization/torchao_integration/test_torchao.py", "repo_id": "transformers", "token_count": 9928 }
569
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("TEST_SAGEMAKER", "False")) is not True, reason="Skipping test because should only be run when releasing minor transformers version", ) @pytest.mark.usefixtures("sm_env") @parameterized_class( [ { "framework": "pytorch", "script": "run_glue.py", "model_name_or_path": "distilbert/distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 650, "eval_accuracy": 0.7, "eval_loss": 0.6}, }, { "framework": "pytorch", "script": "run_ddp.py", "model_name_or_path": "distilbert/distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 600, "eval_accuracy": 0.7, "eval_loss": 0.6}, }, { "framework": "tensorflow", "script": "run_tf_dist.py", "model_name_or_path": "distilbert/distilbert-base-cased", "instance_type": "ml.p3.16xlarge", "results": {"train_runtime": 600, "eval_accuracy": 0.6, "eval_loss": 0.7}, }, ] ) class MultiNodeTest(unittest.TestCase): def setUp(self): if self.framework == "pytorch": subprocess.run( f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(), encoding="utf-8", check=True, ) assert hasattr(self, "env") def create_estimator(self, instance_count): job_name = f"{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}" # distributed data settings distribution = {"smdistributed": {"dataparallel": {"enabled": True}}} if self.script != "run_ddp.py" else None # creates estimator return HuggingFace( entry_point=self.script, source_dir=self.env.test_path, role=self.env.role, image_uri=self.env.image_uri, base_job_name=job_name, instance_count=instance_count, instance_type=self.instance_type, debugger_hook_config=False, hyperparameters={**self.env.distributed_hyperparameters, "model_name_or_path": self.model_name_or_path}, metric_definitions=self.env.metric_definitions, distribution=distribution, py_version="py36", ) def save_results_as_csv(self, job_name): TrainingJobAnalytics(job_name).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv") # @parameterized.expand([(2,), (4,),]) @parameterized.expand([(2,)]) def test_script(self, instance_count): # create estimator estimator = self.create_estimator(instance_count) # run training estimator.fit() # result dataframe result_metrics_df = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis eval_accuracy = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]) eval_loss = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]) # get train time from SageMaker job, this includes starting, preprocessing, stopping train_runtime = ( Session().describe_training_job(estimator.latest_training_job.name).get("TrainingTimeInSeconds", 999999) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy) assert all(t <= self.results["eval_loss"] for t in eval_loss) # dump tests result into json file to share in PR with open(f"{estimator.latest_training_job.name}.json", "w") as outfile: json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}, outfile)
transformers/tests/sagemaker/test_multi_node_data_parallel.py/0
{ "file_path": "transformers/tests/sagemaker/test_multi_node_data_parallel.py", "repo_id": "transformers", "token_count": 1917 }
570
import os import tempfile import unittest from transformers import TrainingArguments class TestTrainingArguments(unittest.TestCase): def test_default_output_dir(self): """Test that output_dir defaults to 'trainer_output' when not specified.""" args = TrainingArguments(output_dir=None) self.assertEqual(args.output_dir, "trainer_output") def test_custom_output_dir(self): """Test that output_dir is respected when specified.""" with tempfile.TemporaryDirectory() as tmp_dir: args = TrainingArguments(output_dir=tmp_dir) self.assertEqual(args.output_dir, tmp_dir) def test_output_dir_creation(self): """Test that output_dir is created only when needed.""" with tempfile.TemporaryDirectory() as tmp_dir: output_dir = os.path.join(tmp_dir, "test_output") # Directory should not exist before creating args self.assertFalse(os.path.exists(output_dir)) # Create args with save_strategy="no" - should not create directory args = TrainingArguments( output_dir=output_dir, do_train=True, save_strategy="no", report_to=None, ) self.assertFalse(os.path.exists(output_dir)) # Now set save_strategy="steps" - should create directory when needed args.save_strategy = "steps" args.save_steps = 1 self.assertFalse(os.path.exists(output_dir)) # Still shouldn't exist # Directory should be created when actually needed (e.g. in Trainer) def test_torch_empty_cache_steps_requirements(self): """Test that torch_empty_cache_steps is a positive integer or None.""" # None is acceptable (feature is disabled): args = TrainingArguments(torch_empty_cache_steps=None) self.assertIsNone(args.torch_empty_cache_steps) # non-int is unacceptable: with self.assertRaises(ValueError): TrainingArguments(torch_empty_cache_steps=1.0) with self.assertRaises(ValueError): TrainingArguments(torch_empty_cache_steps="none") # negative int is unacceptable: with self.assertRaises(ValueError): TrainingArguments(torch_empty_cache_steps=-1) # zero is unacceptable: with self.assertRaises(ValueError): TrainingArguments(torch_empty_cache_steps=0) # positive int is acceptable: args = TrainingArguments(torch_empty_cache_steps=1) self.assertEqual(args.torch_empty_cache_steps, 1)
transformers/tests/test_training_args.py/0
{ "file_path": "transformers/tests/test_training_args.py", "repo_id": "transformers", "token_count": 1083 }
571
import unittest import warnings from dataclasses import dataclass from transformers.convert_slow_tokenizer import SpmConverter from transformers.testing_utils import get_tests_dir @dataclass class FakeOriginalTokenizer: vocab_file: str class ConvertSlowTokenizerTest(unittest.TestCase): def test_spm_converter_bytefallback_warning(self): spm_model_file_without_bytefallback = get_tests_dir("fixtures/test_sentencepiece.model") spm_model_file_with_bytefallback = get_tests_dir("fixtures/test_sentencepiece_with_bytefallback.model") original_tokenizer_without_bytefallback = FakeOriginalTokenizer(vocab_file=spm_model_file_without_bytefallback) with warnings.catch_warnings(record=True) as w: _ = SpmConverter(original_tokenizer_without_bytefallback) # We are looking for if there is any `UserWarning` with # `The sentencepiece tokenizer that you are converting to a fast tokenizer uses the byte fallback option which is not implemented in the fast tokenizers.` w = [x for x in w if x.category.__name__ != "DeprecationWarning"] self.assertEqual(len(w), 0) original_tokenizer_with_bytefallback = FakeOriginalTokenizer(vocab_file=spm_model_file_with_bytefallback) with warnings.catch_warnings(record=True) as w: _ = SpmConverter(original_tokenizer_with_bytefallback) w = [x for x in w if x.category.__name__ != "DeprecationWarning"] self.assertEqual(len(w), 1) self.assertIn( "The sentencepiece tokenizer that you are converting to a fast tokenizer uses the byte fallback option" " which is not implemented in the fast tokenizers.", str(w[0].message), )
transformers/tests/utils/test_convert_slow_tokenizer.py/0
{ "file_path": "transformers/tests/utils/test_convert_slow_tokenizer.py", "repo_id": "transformers", "token_count": 649 }
572
# Copyright 2019 HuggingFace Inc. # # 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 json import os import tempfile import unittest from transformers.modelcard import ModelCard, TrainingSummary class ModelCardTester(unittest.TestCase): def setUp(self): self.inputs_dict = { "model_details": { "Organization": "testing", "Model date": "today", "Model version": "v2.1, Developed by Test Corp in 2019.", "Architecture": "Convolutional Neural Network.", }, "metrics": "BLEU and ROUGE-1", "evaluation_data": { "Datasets": {"BLEU": "My-great-dataset-v1", "ROUGE-1": "My-short-dataset-v2.1"}, "Preprocessing": "See details on https://huggingface.co/papers/1810.03993", }, "training_data": { "Dataset": "English Wikipedia dump dated 2018-12-01", "Preprocessing": ( "Using SentencePiece vocabulary of size 52k tokens. See details on" " https://huggingface.co/papers/1810.03993" ), }, "quantitative_analyses": {"BLEU": 55.1, "ROUGE-1": 76}, } def test_model_card_common_properties(self): modelcard = ModelCard.from_dict(self.inputs_dict) self.assertTrue(hasattr(modelcard, "model_details")) self.assertTrue(hasattr(modelcard, "intended_use")) self.assertTrue(hasattr(modelcard, "factors")) self.assertTrue(hasattr(modelcard, "metrics")) self.assertTrue(hasattr(modelcard, "evaluation_data")) self.assertTrue(hasattr(modelcard, "training_data")) self.assertTrue(hasattr(modelcard, "quantitative_analyses")) self.assertTrue(hasattr(modelcard, "ethical_considerations")) self.assertTrue(hasattr(modelcard, "caveats_and_recommendations")) def test_model_card_to_json_string(self): modelcard = ModelCard.from_dict(self.inputs_dict) obj = json.loads(modelcard.to_json_string()) for key, value in self.inputs_dict.items(): self.assertEqual(obj[key], value) def test_model_card_to_json_file(self): model_card_first = ModelCard.from_dict(self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: filename = os.path.join(tmpdirname, "modelcard.json") model_card_first.to_json_file(filename) model_card_second = ModelCard.from_json_file(filename) self.assertEqual(model_card_second.to_dict(), model_card_first.to_dict()) def test_model_card_from_and_save_pretrained(self): model_card_first = ModelCard.from_dict(self.inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: model_card_first.save_pretrained(tmpdirname) model_card_second = ModelCard.from_pretrained(tmpdirname) self.assertEqual(model_card_second.to_dict(), model_card_first.to_dict()) def test_model_summary_modelcard_base_metadata(self): metadata = TrainingSummary("Model name").create_metadata() self.assertTrue("library_name" in metadata) self.assertTrue(metadata["library_name"] == "transformers")
transformers/tests/utils/test_model_card.py/0
{ "file_path": "transformers/tests/utils/test_model_card.py", "repo_id": "transformers", "token_count": 1553 }
573
# 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 inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py PATH_TO_TRANSFORMERS = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) CONFIG_MAPPING = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased)` _re_checkpoint = re.compile(r"\[(.+?)\]\((https://huggingface\.co/.+?)\)") CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK = { "DecisionTransformerConfig", "EncoderDecoderConfig", "MusicgenConfig", "RagConfig", "SpeechEncoderDecoderConfig", "TimmBackboneConfig", "TimmWrapperConfig", "VisionEncoderDecoderConfig", "VisionTextDualEncoderConfig", "LlamaConfig", "GraniteConfig", "GraniteMoeConfig", "GraniteMoeHybridConfig", "Qwen3MoeConfig", "GraniteSpeechConfig", } def get_checkpoint_from_config_class(config_class): checkpoint = None # source code of `config_class` config_source = inspect.getsource(config_class) checkpoints = _re_checkpoint.findall(config_source) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('google-bert/bert-base-uncased', 'https://huggingface.co/google-bert/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith("/"): ckpt_link = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link ckpt_link_from_name = f"https://huggingface.co/{ckpt_name}" if ckpt_link == ckpt_link_from_name: checkpoint = ckpt_name break return checkpoint def check_config_docstrings_have_checkpoints(): configs_without_checkpoint = [] for config_class in list(CONFIG_MAPPING.values()): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue checkpoint = get_checkpoint_from_config_class(config_class) name = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(name) if len(configs_without_checkpoint) > 0: message = "\n".join(sorted(configs_without_checkpoint)) raise ValueError( f"The following configurations don't contain any valid checkpoint:\n{message}\n\n" "The requirement is to include a link pointing to one of the models of this architecture in the " "docstring of the config classes listed above. The link should have be a markdown format like " "[myorg/mymodel](https://huggingface.co/myorg/mymodel)." ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
transformers/utils/check_config_docstrings.py/0
{ "file_path": "transformers/utils/check_config_docstrings.py", "repo_id": "transformers", "token_count": 1364 }
574
# coding=utf-8 # Copyright 2022 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. import argparse import collections.abc import copy import inspect import json import multiprocessing import os import shutil import tempfile import traceback from pathlib import Path from check_config_docstrings import get_checkpoint_from_config_class from datasets import load_dataset from get_test_info import get_model_to_tester_mapping, get_tester_classes_for_model from huggingface_hub import Repository, create_repo, hf_api, upload_folder from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, IMAGE_PROCESSOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoTokenizer, LayoutLMv3TokenizerFast, PreTrainedTokenizer, PreTrainedTokenizerFast, logging, ) from transformers.feature_extraction_utils import FeatureExtractionMixin from transformers.file_utils import is_tf_available, is_torch_available from transformers.image_processing_utils import BaseImageProcessor from transformers.models.auto.configuration_auto import AutoConfig, model_type_to_module_name from transformers.models.fsmt import configuration_fsmt from transformers.processing_utils import ProcessorMixin, transformers_module from transformers.tokenization_utils_base import PreTrainedTokenizerBase # make sure tokenizer plays nice with multiprocessing os.environ["TOKENIZERS_PARALLELISM"] = "false" logging.set_verbosity_error() logging.disable_progress_bar() logger = logging.get_logger(__name__) os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" if not is_torch_available(): raise ValueError("Please install PyTorch.") if not is_tf_available(): raise ValueError("Please install TensorFlow.") FRAMEWORKS = ["pytorch", "tensorflow"] INVALID_ARCH = [] TARGET_VOCAB_SIZE = 1024 data = {"training_ds": None, "testing_ds": None} COMPOSITE_MODELS = { "EncoderDecoderModel": "EncoderDecoderModel-bert-bert", "SpeechEncoderDecoderModel": "SpeechEncoderDecoderModel-wav2vec2-bert", "VisionEncoderDecoderModel": "VisionEncoderDecoderModel-vit-gpt2", "VisionTextDualEncoderModel": "VisionTextDualEncoderModel-vit-bert", } # This list contains the model architectures for which a tiny version could not be created. # Avoid to add new architectures here - unless we have verified carefully that it's (almost) impossible to create them. # One such case is: no model tester class is implemented for a model type (like `MT5`) because its architecture is # identical to another one (`MT5` is based on `T5`), but trained on different datasets or with different techniques. UNCONVERTIBLE_MODEL_ARCHITECTURES = { "BertGenerationEncoder", "BertGenerationDecoder", "CamembertForSequenceClassification", "CamembertForMultipleChoice", "CamembertForMaskedLM", "CamembertForCausalLM", "CamembertForTokenClassification", "CamembertForQuestionAnswering", "CamembertModel", "TFCamembertForMultipleChoice", "TFCamembertForTokenClassification", "TFCamembertForQuestionAnswering", "TFCamembertForSequenceClassification", "TFCamembertForMaskedLM", "TFCamembertModel", "TFCamembertForCausalLM", "DecisionTransformerModel", "GraphormerModel", "InformerModel", "JukeboxModel", "MarianForCausalLM", "MaskFormerSwinModel", "MaskFormerSwinBackbone", "MT5Model", "MT5ForConditionalGeneration", "UMT5ForConditionalGeneration", "TFMT5ForConditionalGeneration", "TFMT5Model", "QDQBertForSequenceClassification", "QDQBertForMaskedLM", "QDQBertModel", "QDQBertForTokenClassification", "QDQBertLMHeadModel", "QDQBertForMultipleChoice", "QDQBertForQuestionAnswering", "QDQBertForNextSentencePrediction", "ReformerModelWithLMHead", "RetriBertModel", "Speech2Text2ForCausalLM", "TimeSeriesTransformerModel", "TrajectoryTransformerModel", "TrOCRForCausalLM", "XLMProphetNetForConditionalGeneration", "XLMProphetNetForCausalLM", "XLMProphetNetModel", "XLMRobertaModel", "XLMRobertaForTokenClassification", "XLMRobertaForMultipleChoice", "XLMRobertaForMaskedLM", "XLMRobertaForCausalLM", "XLMRobertaForSequenceClassification", "XLMRobertaForQuestionAnswering", "TFXLMRobertaForSequenceClassification", "TFXLMRobertaForMaskedLM", "TFXLMRobertaForCausalLM", "TFXLMRobertaForQuestionAnswering", "TFXLMRobertaModel", "TFXLMRobertaForMultipleChoice", "TFXLMRobertaForTokenClassification", } def get_processor_types_from_config_class(config_class, allowed_mappings=None): """Return a tuple of processors for `config_class`. We use `tuple` here to include (potentially) both slow & fast tokenizers. """ # To make a uniform return type def _to_tuple(x): if not isinstance(x, collections.abc.Sequence): x = (x,) else: x = tuple(x) return x if allowed_mappings is None: allowed_mappings = ["processor", "tokenizer", "image_processor", "feature_extractor"] processor_types = () # Check first if a model has `ProcessorMixin`. Otherwise, check if it has tokenizers, and/or an image processor or # a feature extractor if config_class in PROCESSOR_MAPPING and "processor" in allowed_mappings: processor_types = _to_tuple(PROCESSOR_MAPPING[config_class]) else: if config_class in TOKENIZER_MAPPING and "tokenizer" in allowed_mappings: processor_types = TOKENIZER_MAPPING[config_class] if config_class in IMAGE_PROCESSOR_MAPPING and "image_processor" in allowed_mappings: processor_types += _to_tuple(IMAGE_PROCESSOR_MAPPING[config_class]) elif config_class in FEATURE_EXTRACTOR_MAPPING and "feature_extractor" in allowed_mappings: processor_types += _to_tuple(FEATURE_EXTRACTOR_MAPPING[config_class]) # Remark: some configurations have no processor at all. For example, generic composite models like # `EncoderDecoderModel` is used for any (compatible) text models. Also, `DecisionTransformer` doesn't # require any processor. # We might get `None` for some tokenizers - remove them here. processor_types = tuple(p for p in processor_types if p is not None) return processor_types def get_architectures_from_config_class(config_class, arch_mappings, models_to_skip=None): """Return a tuple of all possible architectures attributed to a configuration class `config_class`. For example, BertConfig -> [BertModel, BertForMaskedLM, ..., BertForQuestionAnswering]. """ # A model architecture could appear in several mappings. For example, `BartForConditionalGeneration` is in # - MODEL_FOR_PRETRAINING_MAPPING_NAMES # - MODEL_WITH_LM_HEAD_MAPPING_NAMES # - MODEL_FOR_MASKED_LM_MAPPING_NAMES # - MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES # We avoid the duplication. architectures = set() if models_to_skip is None: models_to_skip = [] models_to_skip = UNCONVERTIBLE_MODEL_ARCHITECTURES.union(models_to_skip) for mapping in arch_mappings: if config_class in mapping: models = mapping[config_class] models = tuple(models) if isinstance(models, collections.abc.Sequence) else (models,) for model in models: if model.__name__ not in models_to_skip: architectures.add(model) architectures = tuple(architectures) return architectures def get_config_class_from_processor_class(processor_class): """Get the config class from a processor class. Some config/model classes use tokenizers/feature_extractors from other models. For example, `GPT-J` uses `GPT2Tokenizer`. If no checkpoint is found for a config class, or a checkpoint is found without necessary file(s) to create the processor for `processor_class`, we get the config class that corresponds to `processor_class` and use it to find a checkpoint in order to create the processor. """ processor_prefix = processor_class.__name__ for postfix in ["TokenizerFast", "Tokenizer", "ImageProcessor", "FeatureExtractor", "Processor"]: processor_prefix = processor_prefix.replace(postfix, "") # `Wav2Vec2CTCTokenizer` -> `Wav2Vec2Config` if processor_prefix == "Wav2Vec2CTC": processor_prefix = "Wav2Vec2" # Find the new configuration class new_config_name = f"{processor_prefix}Config" new_config_class = getattr(transformers_module, new_config_name) return new_config_class def build_processor(config_class, processor_class, allow_no_checkpoint=False): """Create a processor for `processor_class`. If a processor is not able to be built with the original arguments, this method tries to change the arguments and call itself recursively, by inferring a new `config_class` or a new `processor_class` from another one, in order to find a checkpoint containing the necessary files to build a processor. The processor is not saved here. Instead, it will be saved in `convert_processors` after further changes in `convert_processors`. For each model architecture`, a copy will be created and saved along the built model. """ # Currently, this solely uses the docstring in the source file of `config_class` to find a checkpoint. checkpoint = get_checkpoint_from_config_class(config_class) if checkpoint is None: # try to get the checkpoint from the config class for `processor_class`. # This helps cases like `XCLIPConfig` and `VideoMAEFeatureExtractor` to find a checkpoint from `VideoMAEConfig`. config_class_from_processor_class = get_config_class_from_processor_class(processor_class) checkpoint = get_checkpoint_from_config_class(config_class_from_processor_class) processor = None try: processor = processor_class.from_pretrained(checkpoint) except Exception as e: logger.error(f"{e.__class__.__name__}: {e}") # Try to get a new processor class from checkpoint. This is helpful for a checkpoint without necessary file to load # processor while `processor_class` is an Auto class. For example, `sew` has `Wav2Vec2Processor` in # `PROCESSOR_MAPPING_NAMES`, its `tokenizer_class` is `AutoTokenizer`, and the checkpoint # `https://huggingface.co/asapp/sew-tiny-100k` has no tokenizer file, but we can get # `tokenizer_class: Wav2Vec2CTCTokenizer` from the config file. (The new processor class won't be able to load from # `checkpoint`, but it helps this recursive method to find a way to build a processor). if ( processor is None and checkpoint is not None and issubclass(processor_class, (PreTrainedTokenizerBase, AutoTokenizer)) ): try: config = AutoConfig.from_pretrained(checkpoint) except Exception as e: logger.error(f"{e.__class__.__name__}: {e}") config = None if config is not None: if not isinstance(config, config_class): raise ValueError( f"`config` (which is of type {config.__class__.__name__}) should be an instance of `config_class`" f" ({config_class.__name__})!" ) tokenizer_class = config.tokenizer_class new_processor_class = None if tokenizer_class is not None: new_processor_class = getattr(transformers_module, tokenizer_class) if new_processor_class != processor_class: processor = build_processor(config_class, new_processor_class) # If `tokenizer_class` is not specified in `config`, let's use `config` to get the process class via auto # mappings, but only allow the tokenizer mapping being used. This is to make `Wav2Vec2Conformer` build if processor is None: new_processor_classes = get_processor_types_from_config_class( config.__class__, allowed_mappings=["tokenizer"] ) # Used to avoid infinite recursion between a pair of fast/slow tokenizer types names = [ x.__name__.replace("Fast", "") for x in [processor_class, new_processor_class] if x is not None ] new_processor_classes = [ x for x in new_processor_classes if x is not None and x.__name__.replace("Fast", "") not in names ] if len(new_processor_classes) > 0: new_processor_class = new_processor_classes[0] # Let's use fast tokenizer if there is any for x in new_processor_classes: if x.__name__.endswith("Fast"): new_processor_class = x break processor = build_processor(config_class, new_processor_class) if processor is None: # Try to build each component (tokenizer & feature extractor) of a `ProcessorMixin`. if issubclass(processor_class, ProcessorMixin): attrs = {} for attr_name in processor_class.attributes: attrs[attr_name] = [] # This could be a tuple (for tokenizers). For example, `CLIPProcessor` has # - feature_extractor_class = "CLIPFeatureExtractor" # - tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast") attr_class_names = getattr(processor_class, f"{attr_name}_class") if not isinstance(attr_class_names, tuple): attr_class_names = (attr_class_names,) for name in attr_class_names: attr_class = getattr(transformers_module, name) attr = build_processor(config_class, attr_class) if attr is not None: attrs[attr_name].append(attr) # try to build a `ProcessorMixin`, so we can return a single value if all(len(v) > 0 for v in attrs.values()): try: processor = processor_class(**{k: v[0] for k, v in attrs.items()}) except Exception as e: logger.error(f"{e.__class__.__name__}: {e}") else: # `checkpoint` might lack some file(s) to load a processor. For example, `facebook/hubert-base-ls960` # has no tokenizer file to load `Wav2Vec2CTCTokenizer`. In this case, we try to build a processor # with the configuration class (for example, `Wav2Vec2Config`) corresponding to `processor_class`. config_class_from_processor_class = get_config_class_from_processor_class(processor_class) if config_class_from_processor_class != config_class: processor = build_processor(config_class_from_processor_class, processor_class) # Try to create an image processor or a feature extractor without any checkpoint if ( processor is None and allow_no_checkpoint and (issubclass(processor_class, BaseImageProcessor) or issubclass(processor_class, FeatureExtractionMixin)) ): try: processor = processor_class() except Exception as e: logger.error(f"{e.__class__.__name__}: {e}") # validation if processor is not None: if not (isinstance(processor, processor_class) or processor_class.__name__.startswith("Auto")): raise ValueError( f"`processor` (which is of type {processor.__class__.__name__}) should be an instance of" f" {processor_class.__name__} or an Auto class!" ) return processor def get_tiny_config(config_class, model_class=None, **model_tester_kwargs): """Retrieve a tiny configuration from `config_class` using each model's `ModelTester`. Args: config_class: Subclass of `PreTrainedConfig`. Returns: An instance of `config_class` with tiny hyperparameters """ model_type = config_class.model_type # For model type like `data2vec-vision` and `donut-swin`, we can't get the config/model file name directly via # `model_type` as it would be sth. like `configuration_data2vec_vision.py`. # A simple way is to use `inspect.getsourcefile(config_class)`. config_source_file = inspect.getsourcefile(config_class) # The modeling file name without prefix (`modeling_`) and postfix (`.py`) modeling_name = config_source_file.split(os.path.sep)[-1].replace("configuration_", "").replace(".py", "") try: print("Importing", model_type_to_module_name(model_type)) module_name = model_type_to_module_name(model_type) if not modeling_name.startswith(module_name): raise ValueError(f"{modeling_name} doesn't start with {module_name}!") test_file = os.path.join("tests", "models", module_name, f"test_modeling_{modeling_name}.py") models_to_model_testers = get_model_to_tester_mapping(test_file) # Find the model tester class model_tester_class = None tester_classes = [] if model_class is not None: tester_classes = get_tester_classes_for_model(test_file, model_class) else: for _tester_classes in models_to_model_testers.values(): tester_classes.extend(_tester_classes) if len(tester_classes) > 0: # sort with the length of the class names first, then the alphabetical order # This is to avoid `T5EncoderOnlyModelTest` is used instead of `T5ModelTest`, which has # `is_encoder_decoder=False` and causes some pipeline tests failing (also failures in `Optimum` CI). # TODO: More fine grained control of the desired tester class. model_tester_class = sorted(tester_classes, key=lambda x: (len(x.__name__), x.__name__))[0] except ModuleNotFoundError: error = f"Tiny config not created for {model_type} - cannot find the testing module from the model name." raise ValueError(error) if model_tester_class is None: error = f"Tiny config not created for {model_type} - no model tester is found in the testing module." raise ValueError(error) # CLIP-like models have `text_model_tester` and `vision_model_tester`, and we need to pass `vocab_size` to # `text_model_tester` via `text_kwargs`. The same trick is also necessary for `Flava`. if "vocab_size" in model_tester_kwargs: if "text_kwargs" in inspect.signature(model_tester_class.__init__).parameters: vocab_size = model_tester_kwargs.pop("vocab_size") model_tester_kwargs["text_kwargs"] = {"vocab_size": vocab_size} # `parent` is an instance of `unittest.TestCase`, but we don't need it here. model_tester = model_tester_class(parent=None, **model_tester_kwargs) if hasattr(model_tester, "get_pipeline_config"): config = model_tester.get_pipeline_config() elif hasattr(model_tester, "prepare_config_and_inputs"): # `PoolFormer` has no `get_config` defined. Furthermore, it's better to use `prepare_config_and_inputs` even if # `get_config` is defined, since there might be some extra changes in `prepare_config_and_inputs`. config = model_tester.prepare_config_and_inputs()[0] elif hasattr(model_tester, "get_config"): config = model_tester.get_config() else: error = ( f"Tiny config not created for {model_type} - the model tester {model_tester_class.__name__} lacks" " necessary method to create config." ) raise ValueError(error) # make sure this is long enough (some model tester has `20` for this attr.) to pass `text-generation` # pipeline tests. max_positions = [] for key in ["max_position_embeddings", "max_source_positions", "max_target_positions"]: if getattr(config, key, 0) > 0: max_positions.append(getattr(config, key)) if getattr(config, "text_config", None) is not None: if getattr(config.text_config, key, None) is not None: max_positions.append(getattr(config.text_config, key)) if len(max_positions) > 0: max_position = max(200, min(max_positions)) for key in ["max_position_embeddings", "max_source_positions", "max_target_positions"]: if getattr(config, key, 0) > 0: setattr(config, key, max_position) if getattr(config, "text_config", None) is not None: if getattr(config.text_config, key, None) is not None: setattr(config.text_config, key, max_position) return config def convert_tokenizer(tokenizer_fast: PreTrainedTokenizerFast): new_tokenizer = tokenizer_fast.train_new_from_iterator( data["training_ds"]["text"], TARGET_VOCAB_SIZE, show_progress=False ) # Make sure it at least runs if not isinstance(new_tokenizer, LayoutLMv3TokenizerFast): new_tokenizer(data["testing_ds"]["text"]) return new_tokenizer def convert_feature_extractor(feature_extractor, tiny_config): to_convert = False kwargs = {} if hasattr(tiny_config, "image_size"): kwargs["size"] = tiny_config.image_size kwargs["crop_size"] = tiny_config.image_size to_convert = True elif ( hasattr(tiny_config, "vision_config") and tiny_config.vision_config is not None and hasattr(tiny_config.vision_config, "image_size") ): kwargs["size"] = tiny_config.vision_config.image_size kwargs["crop_size"] = tiny_config.vision_config.image_size to_convert = True # Speech2TextModel specific. if hasattr(tiny_config, "input_feat_per_channel"): kwargs["feature_size"] = tiny_config.input_feat_per_channel kwargs["num_mel_bins"] = tiny_config.input_feat_per_channel to_convert = True if to_convert: feature_extractor = feature_extractor.__class__(**kwargs) # Sanity check: on tiny image feature extractors, a large image size results in slow CI -- up to the point where it # can result in timeout issues. if ( isinstance(feature_extractor, BaseImageProcessor) and hasattr(feature_extractor, "size") and isinstance(feature_extractor.size, dict) ): largest_image_size = max(feature_extractor.size.values()) if largest_image_size > 64: # hardcoded exceptions models_with_large_image_size = ("deformable_detr", "flava", "grounding_dino", "mgp_str", "swiftformer") if any(model_name in tiny_config.model_type for model_name in models_with_large_image_size): pass else: raise ValueError( f"Image size of {tiny_config.model_type} is too large ({feature_extractor.size}). " "Please reduce it to 64 or less on each dimension. The following steps are usually the " "easiest solution: 1) confirm that you're setting `image_size` in your ModelTester class; " "2) ensure that it gets passed to the tester config init, `get_config()`." ) return feature_extractor def convert_processors(processors, tiny_config, output_folder, result): """Change a processor to work with smaller inputs. For tokenizers, we try to reduce their vocabulary size. For feature extractor, we use smaller image size or change other attributes using the values from `tiny_config`. See `convert_feature_extractor`. This method should not fail: we catch the errors and put them in `result["warnings"]` with descriptive messages. """ def _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False): """Set tokenizer(s) to `None` if the fast/slow tokenizers have different values for `vocab_size` or `length`. If `keep_fast_tokenizer=True`, the fast tokenizer will be kept. """ # sanity check 1: fast and slow tokenizers should be compatible (vocab_size) if fast_tokenizer is not None and slow_tokenizer is not None: if fast_tokenizer.vocab_size != slow_tokenizer.vocab_size: warning_message = ( "The fast/slow tokenizers " f"({fast_tokenizer.__class__.__name__}/{slow_tokenizer.__class__.__name__}) have different " "vocabulary size: " f"fast_tokenizer.vocab_size = {fast_tokenizer.vocab_size} and " f"slow_tokenizer.vocab_size = {slow_tokenizer.vocab_size}." ) result["warnings"].append(warning_message) if not keep_fast_tokenizer: fast_tokenizer = None slow_tokenizer = None # sanity check 2: fast and slow tokenizers should be compatible (length) if fast_tokenizer is not None and slow_tokenizer is not None: if len(fast_tokenizer) != len(slow_tokenizer): warning_message = ( f"The fast/slow tokenizers () have different length: " f"len(fast_tokenizer) = {len(fast_tokenizer)} and " f"len(slow_tokenizer) = {len(slow_tokenizer)}." ) result["warnings"].append(warning_message) if not keep_fast_tokenizer: fast_tokenizer = None slow_tokenizer = None return fast_tokenizer, slow_tokenizer tokenizers = [] feature_extractors = [] for processor in processors: if isinstance(processor, PreTrainedTokenizerBase): if processor.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}: tokenizers.append(processor) elif isinstance(processor, BaseImageProcessor): if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}: feature_extractors.append(processor) elif isinstance(processor, FeatureExtractionMixin): if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}: feature_extractors.append(processor) elif isinstance(processor, ProcessorMixin): if hasattr(processor, "tokenizer"): if processor.tokenizer.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}: tokenizers.append(processor.tokenizer) # Currently, we only have these 2 possibilities if hasattr(processor, "image_processor"): if processor.image_processor.__class__.__name__ not in { x.__class__.__name__ for x in feature_extractors }: feature_extractors.append(processor.image_processor) elif hasattr(processor, "feature_extractor"): if processor.feature_extractor.__class__.__name__ not in { x.__class__.__name__ for x in feature_extractors }: feature_extractors.append(processor.feature_extractor) # check the built processors have the unique type num_types = len({x.__class__.__name__ for x in feature_extractors}) if num_types >= 2: raise ValueError(f"`feature_extractors` should contain at most 1 type, but it contains {num_types} types!") num_types = len({x.__class__.__name__.replace("Fast", "") for x in tokenizers}) if num_types >= 2: raise ValueError(f"`tokenizers` should contain at most 1 tokenizer type, but it contains {num_types} types!") fast_tokenizer = None slow_tokenizer = None for tokenizer in tokenizers: if isinstance(tokenizer, PreTrainedTokenizerFast): fast_tokenizer = tokenizer else: slow_tokenizer = tokenizer # If the (original) fast/slow tokenizers don't correspond, keep only the fast tokenizer. # This doesn't necessarily imply the fast/slow tokenizers in a single Hub repo. has issues. # It's more of an issue in `build_processor` which tries to get a checkpoint with as much effort as possible. # For `YosoModel` (which uses `AlbertTokenizer(Fast)`), its real (Hub) checkpoint doesn't contain valid files to # load the slower tokenizer (`AlbertTokenizer`), and it ends up finding the (canonical) checkpoint of `AlbertModel`, # which has different vocabulary. # TODO: Try to improve `build_processor`'s definition and/or usage to avoid the above situation in the first place. fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=True) original_fast_tokenizer, original_slow_tokenizer = fast_tokenizer, slow_tokenizer if fast_tokenizer: try: # Wav2Vec2ForCTC , ByT5Tokenizer etc. all are already small enough and have no fast version that can # be retrained if fast_tokenizer.vocab_size > TARGET_VOCAB_SIZE: fast_tokenizer = convert_tokenizer(fast_tokenizer) except Exception: result["warnings"].append( ( f"Failed to convert the fast tokenizer for {fast_tokenizer.__class__.__name__}.", traceback.format_exc(), ) ) # If `fast_tokenizer` exists, `slow_tokenizer` should correspond to it. if fast_tokenizer: # Make sure the fast tokenizer can be saved try: # We don't save it to `output_folder` at this moment - only at the end of this function. with tempfile.TemporaryDirectory() as tmpdir: fast_tokenizer.save_pretrained(tmpdir) try: slow_tokenizer = AutoTokenizer.from_pretrained(tmpdir, use_fast=False) except Exception: result["warnings"].append( ( f"Failed to load the slow tokenizer saved from {fast_tokenizer.__class__.__name__}.", traceback.format_exc(), ) ) # Let's just keep the fast version slow_tokenizer = None except Exception: result["warnings"].append( ( f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.", traceback.format_exc(), ) ) fast_tokenizer = None # If the (possibly converted) fast/slow tokenizers don't correspond, set them to `None`, and use the original # tokenizers. fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False) # If there is any conversion failed, we keep the original tokenizers. if (original_fast_tokenizer is not None and fast_tokenizer is None) or ( original_slow_tokenizer is not None and slow_tokenizer is None ): warning_messagae = ( "There are some issues when converting the fast/slow tokenizers. The original tokenizers from the Hub " " will be used instead." ) result["warnings"].append(warning_messagae) # Let's use the original version at the end (`original_fast_tokenizer` and `original_slow_tokenizer`) fast_tokenizer = original_fast_tokenizer slow_tokenizer = original_slow_tokenizer # Make sure the fast tokenizer can be saved if fast_tokenizer: # We don't save it to `output_folder` at this moment - only at the end of this function. with tempfile.TemporaryDirectory() as tmpdir: try: fast_tokenizer.save_pretrained(tmpdir) except Exception: result["warnings"].append( ( f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.", traceback.format_exc(), ) ) fast_tokenizer = None # Make sure the slow tokenizer can be saved if slow_tokenizer: # We don't save it to `output_folder` at this moment - only at the end of this function. with tempfile.TemporaryDirectory() as tmpdir: try: slow_tokenizer.save_pretrained(tmpdir) except Exception: result["warnings"].append( ( f"Failed to save the slow tokenizer for {slow_tokenizer.__class__.__name__}.", traceback.format_exc(), ) ) slow_tokenizer = None # update feature extractors using the tiny config try: feature_extractors = [convert_feature_extractor(p, tiny_config) for p in feature_extractors] except Exception: result["warnings"].append( ( "Failed to convert feature extractors.", traceback.format_exc(), ) ) feature_extractors = [] if hasattr(tiny_config, "max_position_embeddings") and tiny_config.max_position_embeddings > 0: if fast_tokenizer is not None: if fast_tokenizer.__class__.__name__ in [ "RobertaTokenizerFast", "XLMRobertaTokenizerFast", "LongformerTokenizerFast", "MPNetTokenizerFast", ]: fast_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2 else: fast_tokenizer.model_max_length = tiny_config.max_position_embeddings if slow_tokenizer is not None: if slow_tokenizer.__class__.__name__ in [ "RobertaTokenizer", "XLMRobertaTokenizer", "LongformerTokenizer", "MPNetTokenizer", ]: slow_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2 else: slow_tokenizer.model_max_length = tiny_config.max_position_embeddings processors = [fast_tokenizer, slow_tokenizer] + feature_extractors processors = [p for p in processors if p is not None] for p in processors: p.save_pretrained(output_folder) return processors def get_checkpoint_dir(output_dir, model_arch): """Get framework-agnostic architecture name. Used to save all PT/TF/Flax models into the same directory.""" arch_name = model_arch.__name__ if arch_name.startswith("TF"): arch_name = arch_name[2:] elif arch_name.startswith("Flax"): arch_name = arch_name[4:] return os.path.join(output_dir, arch_name) def build_model(model_arch, tiny_config, output_dir): """Create and save a model for `model_arch`. Also copy the set of processors to each model (under the same model type) output folder. """ checkpoint_dir = get_checkpoint_dir(output_dir, model_arch) processor_output_dir = os.path.join(output_dir, "processors") # copy the (same set of) processors (for a model type) to the model arch. specific folder if os.path.isdir(processor_output_dir): shutil.copytree(processor_output_dir, checkpoint_dir, dirs_exist_ok=True) tiny_config = copy.deepcopy(tiny_config) if any(model_arch.__name__.endswith(x) for x in ["ForCausalLM", "LMHeadModel"]): tiny_config.is_encoder_decoder = False tiny_config.is_decoder = True model = model_arch(config=tiny_config) model.save_pretrained(checkpoint_dir) model.from_pretrained(checkpoint_dir) return model def fill_result_with_error(result, error, trace, models_to_create): """Fill `result` with errors for all target model arch if we can't build processor""" error = (error, trace) result["error"] = error for framework in FRAMEWORKS: if framework in models_to_create: result[framework] = {} for model_arch in models_to_create[framework]: result[framework][model_arch.__name__] = {"model": None, "checkpoint": None, "error": error} result["processor"] = {p.__class__.__name__: p.__class__.__name__ for p in result["processor"].values()} def upload_model(model_dir, organization, token): """Upload the tiny models""" arch_name = model_dir.split(os.path.sep)[-1] repo_name = f"tiny-random-{arch_name}" repo_id = f"{organization}/{repo_name}" repo_exist = False error = None try: create_repo(repo_id=repo_id, exist_ok=False, repo_type="model", token=token) except Exception as e: error = e if "You already created" in str(e): error = None logger.warning("Remote repository exists and will be cloned.") repo_exist = True try: create_repo(repo_id=repo_id, exist_ok=True, repo_type="model", token=token) except Exception as e: error = e if error is not None: raise error with tempfile.TemporaryDirectory() as tmpdir: repo = Repository(local_dir=tmpdir, clone_from=repo_id, token=token) repo.git_pull() shutil.copytree(model_dir, tmpdir, dirs_exist_ok=True) if repo_exist: # Open a PR on the existing Hub repo. hub_pr_url = upload_folder( folder_path=model_dir, repo_id=repo_id, repo_type="model", commit_message=f"Update tiny models for {arch_name}", commit_description=f"Upload tiny models for {arch_name}", create_pr=True, token=token, ) logger.warning(f"PR open in {hub_pr_url}.") # TODO: We need this information? else: # Push to Hub repo directly repo.git_add(auto_lfs_track=True) repo.git_commit(f"Upload tiny models for {arch_name}") repo.git_push(blocking=True) # this prints a progress bar with the upload logger.warning(f"Tiny models {arch_name} pushed to {repo_id}.") def build_composite_models(config_class, output_dir): import tempfile from transformers import ( BertConfig, BertLMHeadModel, BertModel, BertTokenizer, BertTokenizerFast, EncoderDecoderModel, GPT2Config, GPT2LMHeadModel, GPT2Tokenizer, GPT2TokenizerFast, SpeechEncoderDecoderModel, TFEncoderDecoderModel, TFVisionEncoderDecoderModel, TFVisionTextDualEncoderModel, VisionEncoderDecoderModel, VisionTextDualEncoderModel, ViTConfig, ViTFeatureExtractor, ViTModel, Wav2Vec2Config, Wav2Vec2Model, Wav2Vec2Processor, ) # These will be removed at the end if they are empty result = {"error": None, "warnings": []} if config_class.model_type == "encoder-decoder": encoder_config_class = BertConfig decoder_config_class = BertConfig encoder_processor = (BertTokenizerFast, BertTokenizer) decoder_processor = (BertTokenizerFast, BertTokenizer) encoder_class = BertModel decoder_class = BertLMHeadModel model_class = EncoderDecoderModel tf_model_class = TFEncoderDecoderModel elif config_class.model_type == "vision-encoder-decoder": encoder_config_class = ViTConfig decoder_config_class = GPT2Config encoder_processor = (ViTFeatureExtractor,) decoder_processor = (GPT2TokenizerFast, GPT2Tokenizer) encoder_class = ViTModel decoder_class = GPT2LMHeadModel model_class = VisionEncoderDecoderModel tf_model_class = TFVisionEncoderDecoderModel elif config_class.model_type == "speech-encoder-decoder": encoder_config_class = Wav2Vec2Config decoder_config_class = BertConfig encoder_processor = (Wav2Vec2Processor,) decoder_processor = (BertTokenizerFast, BertTokenizer) encoder_class = Wav2Vec2Model decoder_class = BertLMHeadModel model_class = SpeechEncoderDecoderModel tf_model_class = None elif config_class.model_type == "vision-text-dual-encoder": # Not encoder-decoder, but encoder-encoder. We just keep the same name as above to make code easier encoder_config_class = ViTConfig decoder_config_class = BertConfig encoder_processor = (ViTFeatureExtractor,) decoder_processor = (BertTokenizerFast, BertTokenizer) encoder_class = ViTModel decoder_class = BertModel model_class = VisionTextDualEncoderModel tf_model_class = TFVisionTextDualEncoderModel with tempfile.TemporaryDirectory() as tmpdir: try: # build encoder models_to_create = {"processor": encoder_processor, "pytorch": (encoder_class,), "tensorflow": []} encoder_output_dir = os.path.join(tmpdir, "encoder") build(encoder_config_class, models_to_create, encoder_output_dir) # build decoder models_to_create = {"processor": decoder_processor, "pytorch": (decoder_class,), "tensorflow": []} decoder_output_dir = os.path.join(tmpdir, "decoder") build(decoder_config_class, models_to_create, decoder_output_dir) # build encoder-decoder encoder_path = os.path.join(encoder_output_dir, encoder_class.__name__) decoder_path = os.path.join(decoder_output_dir, decoder_class.__name__) if config_class.model_type != "vision-text-dual-encoder": # Specify these explicitly for encoder-decoder like models, but not for `vision-text-dual-encoder` as it # has no decoder. decoder_config = decoder_config_class.from_pretrained(decoder_path) decoder_config.is_decoder = True decoder_config.add_cross_attention = True model = model_class.from_encoder_decoder_pretrained( encoder_path, decoder_path, decoder_config=decoder_config, ) elif config_class.model_type == "vision-text-dual-encoder": model = model_class.from_vision_text_pretrained(encoder_path, decoder_path) model_path = os.path.join( output_dir, f"{model_class.__name__}-{encoder_config_class.model_type}-{decoder_config_class.model_type}", ) model.save_pretrained(model_path) if tf_model_class is not None: model = tf_model_class.from_pretrained(model_path) model.save_pretrained(model_path) # copy the processors encoder_processor_path = os.path.join(encoder_output_dir, "processors") decoder_processor_path = os.path.join(decoder_output_dir, "processors") if os.path.isdir(encoder_processor_path): shutil.copytree(encoder_processor_path, model_path, dirs_exist_ok=True) if os.path.isdir(decoder_processor_path): shutil.copytree(decoder_processor_path, model_path, dirs_exist_ok=True) # fill `result` result["processor"] = {x.__name__: x.__name__ for x in encoder_processor + decoder_processor} result["pytorch"] = {model_class.__name__: {"model": model_class.__name__, "checkpoint": model_path}} result["tensorflow"] = {} if tf_model_class is not None: result["tensorflow"] = { tf_model_class.__name__: {"model": tf_model_class.__name__, "checkpoint": model_path} } except Exception: result["error"] = ( f"Failed to build models for {config_class.__name__}.", traceback.format_exc(), ) if not result["error"]: del result["error"] if not result["warnings"]: del result["warnings"] return result def get_token_id_from_tokenizer(token_id_name, tokenizer, original_token_id): """Use `tokenizer` to get the values of `bos_token_id`, `eos_token_ids`, etc. The argument `token_id_name` should be a string ending with `_token_id`, and `original_token_id` should be an integer that will be return if `tokenizer` has no token corresponding to `token_id_name`. """ token_id = original_token_id if not token_id_name.endswith("_token_id"): raise ValueError(f"`token_id_name` is {token_id_name}, which doesn't end with `_token_id`!") token = getattr(tokenizer, token_id_name.replace("_token_id", "_token"), None) if token is not None: if isinstance(tokenizer, PreTrainedTokenizerFast): token_id = tokenizer._convert_token_to_id_with_added_voc(token) else: token_id = tokenizer._convert_token_to_id(token) return token_id def get_config_overrides(config_class, processors): # `Bark` configuration is too special. Let's just not handle this for now. if config_class.__name__ == "BarkConfig": return {} config_overrides = {} # Check if there is any tokenizer (prefer fast version if any) tokenizer = None for processor in processors: if isinstance(processor, PreTrainedTokenizerFast): tokenizer = processor break elif isinstance(processor, PreTrainedTokenizer): tokenizer = processor if tokenizer is None: return config_overrides # Get some properties of the (already converted) tokenizer (smaller vocab size, special token ids, etc.) # We use `len(tokenizer)` instead of `tokenizer.vocab_size` to avoid potential issues for tokenizers with non-empty # `added_tokens_encoder`. One example is the `DebertaV2Tokenizer` where the mask token is the extra token. vocab_size = len(tokenizer) # The original checkpoint has length `35998`, but it doesn't have ids `30400` and `30514` but instead `35998` and # `35999`. if config_class.__name__ == "GPTSanJapaneseConfig": vocab_size += 2 config_overrides["vocab_size"] = vocab_size # Used to create a new model tester with `tokenizer.vocab_size` in order to get the (updated) special token ids. model_tester_kwargs = {"vocab_size": vocab_size} # `FSMTModelTester` accepts `src_vocab_size` and `tgt_vocab_size` but not `vocab_size`. if config_class.__name__ == "FSMTConfig": del model_tester_kwargs["vocab_size"] model_tester_kwargs["src_vocab_size"] = tokenizer.src_vocab_size model_tester_kwargs["tgt_vocab_size"] = tokenizer.tgt_vocab_size _tiny_config = get_tiny_config(config_class, **model_tester_kwargs) # handle the possibility of `text_config` inside `_tiny_config` for clip-like models (`owlvit`, `groupvit`, etc.) if hasattr(_tiny_config, "text_config"): _tiny_config = _tiny_config.text_config # Collect values of some special token ids for attr in dir(_tiny_config): if attr.endswith("_token_id"): token_id = getattr(_tiny_config, attr) if token_id is not None: # Using the token id values from `tokenizer` instead of from `_tiny_config`. token_id = get_token_id_from_tokenizer(attr, tokenizer, original_token_id=token_id) config_overrides[attr] = token_id if config_class.__name__ == "FSMTConfig": config_overrides["src_vocab_size"] = tokenizer.src_vocab_size config_overrides["tgt_vocab_size"] = tokenizer.tgt_vocab_size # `FSMTConfig` has `DecoderConfig` as `decoder` attribute. config_overrides["decoder"] = configuration_fsmt.DecoderConfig( vocab_size=tokenizer.tgt_vocab_size, bos_token_id=config_overrides["eos_token_id"] ) return config_overrides def build(config_class, models_to_create, output_dir): """Create all models for a certain model type. Args: config_class (`PretrainedConfig`): A subclass of `PretrainedConfig` that is used to determine `models_to_create`. models_to_create (`dict`): A dictionary containing the processor/model classes that we want to create the instances. These models are of the same model type which is associated to `config_class`. output_dir (`str`): The directory to save all the checkpoints. Each model architecture will be saved in a subdirectory under it. Models in different frameworks with the same architecture will be saved in the same subdirectory. """ if data["training_ds"] is None or data["testing_ds"] is None: ds = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1") data["training_ds"] = ds["train"] data["testing_ds"] = ds["test"] if config_class.model_type in [ "encoder-decoder", "vision-encoder-decoder", "speech-encoder-decoder", "vision-text-dual-encoder", ]: return build_composite_models(config_class, output_dir) result = {k: {} for k in models_to_create} # These will be removed at the end if they are empty result["error"] = None result["warnings"] = [] # Build processors processor_classes = models_to_create["processor"] if len(processor_classes) == 0: error = f"No processor class could be found in {config_class.__name__}." fill_result_with_error(result, error, None, models_to_create) logger.error(result["error"][0]) return result for processor_class in processor_classes: try: processor = build_processor(config_class, processor_class, allow_no_checkpoint=True) if processor is not None: result["processor"][processor_class] = processor except Exception: error = f"Failed to build processor for {processor_class.__name__}." trace = traceback.format_exc() fill_result_with_error(result, error, trace, models_to_create) logger.error(result["error"][0]) return result if len(result["processor"]) == 0: error = f"No processor could be built for {config_class.__name__}." fill_result_with_error(result, error, None, models_to_create) logger.error(result["error"][0]) return result try: tiny_config = get_tiny_config(config_class) except Exception as e: error = f"Failed to get tiny config for {config_class.__name__}: {e}" trace = traceback.format_exc() fill_result_with_error(result, error, trace, models_to_create) logger.error(result["error"][0]) return result # Convert the processors (reduce vocabulary size, smaller image size, etc.) processors = list(result["processor"].values()) processor_output_folder = os.path.join(output_dir, "processors") try: processors = convert_processors(processors, tiny_config, processor_output_folder, result) except Exception: error = "Failed to convert the processors." trace = traceback.format_exc() result["warnings"].append((error, trace)) if len(processors) == 0: error = f"No processor is returned by `convert_processors` for {config_class.__name__}." fill_result_with_error(result, error, None, models_to_create) logger.error(result["error"][0]) return result try: config_overrides = get_config_overrides(config_class, processors) except Exception as e: error = f"Failure occurs while calling `get_config_overrides`: {e}" trace = traceback.format_exc() fill_result_with_error(result, error, trace, models_to_create) logger.error(result["error"][0]) return result # Just for us to see this easily in the report if "vocab_size" in config_overrides: result["vocab_size"] = config_overrides["vocab_size"] # Update attributes that `vocab_size` involves for k, v in config_overrides.items(): if hasattr(tiny_config, k): setattr(tiny_config, k, v) # So far, we only have to deal with `text_config`, as `config_overrides` contains text-related attributes only. # `FuyuConfig` saves data under both FuyuConfig and its `text_config`. This is not good, but let's just update # every involved fields to avoid potential failure. if ( hasattr(tiny_config, "text_config") and tiny_config.text_config is not None and hasattr(tiny_config.text_config, k) ): setattr(tiny_config.text_config, k, v) # If `text_config_dict` exists, we need to update its value here too in order to # make # `save_pretrained -> from_pretrained` work. if hasattr(tiny_config, "text_config_dict"): tiny_config.text_config_dict[k] = v if result["warnings"]: logger.warning(result["warnings"][0][0]) # update `result["processor"]` result["processor"] = {type(p).__name__: p.__class__.__name__ for p in processors} for pytorch_arch in models_to_create["pytorch"]: result["pytorch"][pytorch_arch.__name__] = {} error = None try: model = build_model(pytorch_arch, tiny_config, output_dir=output_dir) except Exception as e: model = None error = f"Failed to create the pytorch model for {pytorch_arch}: {e}" trace = traceback.format_exc() result["pytorch"][pytorch_arch.__name__]["model"] = model.__class__.__name__ if model is not None else None result["pytorch"][pytorch_arch.__name__]["checkpoint"] = ( get_checkpoint_dir(output_dir, pytorch_arch) if model is not None else None ) if error is not None: result["pytorch"][pytorch_arch.__name__]["error"] = (error, trace) logger.error(f"{pytorch_arch.__name__}: {error}") for tensorflow_arch in models_to_create["tensorflow"]: # Make PT/TF weights compatible pt_arch_name = tensorflow_arch.__name__[2:] # Remove `TF` pt_arch = getattr(transformers_module, pt_arch_name) result["tensorflow"][tensorflow_arch.__name__] = {} error = None if pt_arch.__name__ in result["pytorch"] and result["pytorch"][pt_arch.__name__]["checkpoint"] is not None: ckpt = get_checkpoint_dir(output_dir, pt_arch) # Use the same weights from PyTorch. try: model = tensorflow_arch.from_pretrained(ckpt) model.save_pretrained(ckpt) except Exception as e: # Conversion may fail. Let's not create a model with different weights to avoid confusion (for now). model = None error = f"Failed to convert the pytorch model to the tensorflow model for {pt_arch}: {e}" trace = traceback.format_exc() else: try: model = build_model(tensorflow_arch, tiny_config, output_dir=output_dir) except Exception as e: model = None error = f"Failed to create the tensorflow model for {tensorflow_arch}: {e}" trace = traceback.format_exc() result["tensorflow"][tensorflow_arch.__name__]["model"] = ( model.__class__.__name__ if model is not None else None ) result["tensorflow"][tensorflow_arch.__name__]["checkpoint"] = ( get_checkpoint_dir(output_dir, tensorflow_arch) if model is not None else None ) if error is not None: result["tensorflow"][tensorflow_arch.__name__]["error"] = (error, trace) logger.error(f"{tensorflow_arch.__name__}: {error}") if not result["error"]: del result["error"] if not result["warnings"]: del result["warnings"] return result def build_tiny_model_summary(results, organization=None, token=None): """Build a summary: a dictionary of the form { model architecture name: { "tokenizer_classes": [...], "processor_classes": [...], "model_classes": [...], } .. } """ tiny_model_summary = {} for config_name in results: processors = [key for key, value in results[config_name]["processor"].items()] tokenizer_classes = sorted([x for x in processors if x.endswith("TokenizerFast") or x.endswith("Tokenizer")]) processor_classes = sorted([x for x in processors if x not in tokenizer_classes]) for framework in FRAMEWORKS: if framework not in results[config_name]: continue for arch_name in results[config_name][framework]: model_classes = [arch_name] base_arch_name = arch_name[2:] if arch_name.startswith("TF") else arch_name # tiny model is not created for `arch_name` if results[config_name][framework][arch_name]["model"] is None: model_classes = [] if base_arch_name not in tiny_model_summary: tiny_model_summary[base_arch_name] = {} tiny_model_summary[base_arch_name].update( { "tokenizer_classes": tokenizer_classes, "processor_classes": processor_classes, } ) tiny_model_summary[base_arch_name]["model_classes"] = sorted( tiny_model_summary[base_arch_name].get("model_classes", []) + model_classes ) if organization is not None: repo_name = f"tiny-random-{base_arch_name}" # composite models' checkpoints have more precise repo. names on the Hub. if base_arch_name in COMPOSITE_MODELS: repo_name = f"tiny-random-{COMPOSITE_MODELS[base_arch_name]}" repo_id = f"{organization}/{repo_name}" try: commit_hash = hf_api.repo_info(repo_id, token=token).sha except Exception: # The directory is not created, but processor(s) is/are included in `results`. logger.warning(f"Failed to get information for {repo_id}.\n{traceback.format_exc()}") del tiny_model_summary[base_arch_name] continue tiny_model_summary[base_arch_name]["sha"] = commit_hash return tiny_model_summary def build_failed_report(results, include_warning=True): failed_results = {} for config_name in results: if "error" in results[config_name]: if config_name not in failed_results: failed_results[config_name] = {} failed_results[config_name] = {"error": results[config_name]["error"]} if include_warning and "warnings" in results[config_name]: if config_name not in failed_results: failed_results[config_name] = {} failed_results[config_name]["warnings"] = results[config_name]["warnings"] for framework in FRAMEWORKS: if framework not in results[config_name]: continue for arch_name in results[config_name][framework]: if "error" in results[config_name][framework][arch_name]: if config_name not in failed_results: failed_results[config_name] = {} if framework not in failed_results[config_name]: failed_results[config_name][framework] = {} if arch_name not in failed_results[config_name][framework]: failed_results[config_name][framework][arch_name] = {} error = results[config_name][framework][arch_name]["error"] failed_results[config_name][framework][arch_name]["error"] = error return failed_results def build_simple_report(results): text = "" failed_text = "" for config_name in results: for framework in FRAMEWORKS: if framework not in results[config_name]: continue for arch_name in results[config_name][framework]: if "error" in results[config_name][framework][arch_name]: result = results[config_name][framework][arch_name]["error"] failed_text += f"{arch_name}: {result[0]}\n" else: result = ("OK",) text += f"{arch_name}: {result[0]}\n" return text, failed_text def update_tiny_model_summary_file(report_path): with open(os.path.join(report_path, "tiny_model_summary.json")) as fp: new_data = json.load(fp) with open("tests/utils/tiny_model_summary.json") as fp: data = json.load(fp) for key, value in new_data.items(): if key not in data: data[key] = value else: for attr in ["tokenizer_classes", "processor_classes", "model_classes"]: # we might get duplication here. We will remove them below when creating `updated_data`. data[key][attr].extend(value[attr]) new_sha = value.get("sha", None) if new_sha is not None: data[key]["sha"] = new_sha updated_data = {} for key in sorted(data.keys()): updated_data[key] = {} for attr, value in data[key].items(): # deduplication and sort updated_data[key][attr] = sorted(set(value)) if attr != "sha" else value with open(os.path.join(report_path, "updated_tiny_model_summary.json"), "w") as fp: json.dump(updated_data, fp, indent=4, ensure_ascii=False) def create_tiny_models( output_path, all, model_types, models_to_skip, no_check, upload, organization, token, num_workers=1, ): clone_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) if os.getcwd() != clone_path: raise ValueError(f"This script should be run from the root of the clone of `transformers` {clone_path}") report_path = os.path.join(output_path, "reports") os.makedirs(report_path, exist_ok=True) _pytorch_arch_mappings = [ x for x in dir(transformers_module) if x.startswith("MODEL_") and x.endswith("_MAPPING") and x != "MODEL_NAMES_MAPPING" ] _tensorflow_arch_mappings = [ x for x in dir(transformers_module) if x.startswith("TF_MODEL_") and x.endswith("_MAPPING") ] pytorch_arch_mappings = [getattr(transformers_module, x) for x in _pytorch_arch_mappings] tensorflow_arch_mappings = [getattr(transformers_module, x) for x in _tensorflow_arch_mappings] config_classes = CONFIG_MAPPING.values() if not all: config_classes = [CONFIG_MAPPING[model_type] for model_type in model_types] # A map from config classes to tuples of processors (tokenizer, feature extractor, processor) classes processor_type_map = {c: get_processor_types_from_config_class(c) for c in config_classes} to_create = {} for c in config_classes: processors = processor_type_map[c] models = get_architectures_from_config_class(c, pytorch_arch_mappings, models_to_skip) tf_models = get_architectures_from_config_class(c, tensorflow_arch_mappings, models_to_skip) if len(models) + len(tf_models) > 0: to_create[c] = {"processor": processors, "pytorch": models, "tensorflow": tf_models} results = {} if num_workers <= 1: for c, models_to_create in list(to_create.items()): print(f"Create models for {c.__name__} ...") result = build(c, models_to_create, output_dir=os.path.join(output_path, c.model_type)) results[c.__name__] = result print("=" * 40) else: all_build_args = [] for c, models_to_create in list(to_create.items()): all_build_args.append((c, models_to_create, os.path.join(output_path, c.model_type))) with multiprocessing.Pool() as pool: results = pool.starmap(build, all_build_args) results = {buid_args[0].__name__: result for buid_args, result in zip(all_build_args, results)} if upload: if organization is None: raise ValueError("The argument `organization` could not be `None`. No model is uploaded") to_upload = [] for model_type in os.listdir(output_path): # This is the directory containing the reports if model_type == "reports": continue for arch in os.listdir(os.path.join(output_path, model_type)): if arch == "processors": continue to_upload.append(os.path.join(output_path, model_type, arch)) to_upload = sorted(to_upload) upload_results = {} if len(to_upload) > 0: for model_dir in to_upload: try: upload_model(model_dir, organization, token) except Exception as e: error = f"Failed to upload {model_dir}. {e.__class__.__name__}: {e}" logger.error(error) upload_results[model_dir] = error with open(os.path.join(report_path, "failed_uploads.json"), "w") as fp: json.dump(upload_results, fp, indent=4) # Build the tiny model summary file. The `tokenizer_classes` and `processor_classes` could be both empty lists. # When using the items in this file to update the file `tests/utils/tiny_model_summary.json`, the model # architectures with `tokenizer_classes` and `processor_classes` being both empty should **NOT** be added to # `tests/utils/tiny_model_summary.json`. tiny_model_summary = build_tiny_model_summary(results, organization=organization, token=token) with open(os.path.join(report_path, "tiny_model_summary.json"), "w") as fp: json.dump(tiny_model_summary, fp, indent=4) with open(os.path.join(report_path, "tiny_model_creation_report.json"), "w") as fp: json.dump(results, fp, indent=4) # Build the warning/failure report (json format): same format as the complete `results` except this contains only # warnings or errors. failed_results = build_failed_report(results) with open(os.path.join(report_path, "failed_report.json"), "w") as fp: json.dump(failed_results, fp, indent=4) simple_report, failed_report = build_simple_report(results) # The simplified report: a .txt file with each line of format: # {model architecture name}: {OK or error message} with open(os.path.join(report_path, "simple_report.txt"), "w") as fp: fp.write(simple_report) # The simplified failure report: same above except this only contains line with errors with open(os.path.join(report_path, "simple_failed_report.txt"), "w") as fp: fp.write(failed_report) update_tiny_model_summary_file(report_path=os.path.join(output_path, "reports")) if __name__ == "__main__": # This has to be `spawn` to avoid hanging forever! multiprocessing.set_start_method("spawn") def list_str(values): return values.split(",") parser = argparse.ArgumentParser() parser.add_argument("--all", action="store_true", help="Will create all tiny models.") parser.add_argument( "--no_check", action="store_true", help="If set, will not check the validity of architectures. Use with caution.", ) parser.add_argument( "-m", "--model_types", type=list_str, help="Comma-separated list of model type(s) from which the tiny models will be created.", ) parser.add_argument( "--models_to_skip", type=list_str, help=( "Comma-separated list of model class names(s) from which the tiny models won't be created.\nThis is usually " "the list of model classes that have their tiny versions already uploaded to the Hub." ), ) parser.add_argument("--upload", action="store_true", help="If to upload the created tiny models to the Hub.") parser.add_argument( "--organization", default=None, type=str, help="The organization on the Hub to which the tiny models will be uploaded.", ) parser.add_argument( "--token", default=None, type=str, help="A valid authentication token for HuggingFace Hub with write access." ) parser.add_argument("output_path", type=Path, help="Path indicating where to store generated model.") parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.") args = parser.parse_args() if not args.all and not args.model_types: raise ValueError("Please provide at least one model type or pass `--all` to export all architectures.") create_tiny_models( args.output_path, args.all, args.model_types, args.models_to_skip, args.no_check, args.upload, args.organization, args.token, args.num_workers, )
transformers/utils/create_dummy_models.py/0
{ "file_path": "transformers/utils/create_dummy_models.py", "repo_id": "transformers", "token_count": 29296 }
575
# coding=utf-8 # Copyright 2024 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. import argparse import glob import importlib import os import re import subprocess from abc import ABC, abstractmethod from collections import Counter, defaultdict, deque from typing import Optional, Union import libcst as cst from create_dependency_mapping import find_priority_list from libcst import ClassDef, CSTVisitor from libcst import matchers as m from libcst.metadata import MetadataWrapper, ParentNodeProvider, PositionProvider, ScopeProvider from transformers import logging from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES logger = logging.get_logger(__name__) AUTO_GENERATED_MESSAGE = """# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # This file was automatically generated from {relative_path}. # Do NOT edit this file manually as any edits will be overwritten by the generation of # the file from the modular. If any change should be done, please apply the change to the # {short_name} file directly. One of our CI enforces this. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 """ def get_module_source_from_name(module_name: str) -> str: # Extract the source code from the module name spec = importlib.util.find_spec(module_name) if spec is None or spec.origin is None: raise ValueError(f"Cannot open file associated with {module_name} module.") with open(spec.origin, "r", encoding="utf-8") as file: source_code = file.read() return source_code def preserve_case_replace(text, patterns: dict, default_name: str): # Create a regex pattern to match all variations regex_pattern = "|".join(re.escape(key) for key in patterns) compiled_regex = re.compile(f"(?<![a-z0-9])({regex_pattern})(.|$)", re.IGNORECASE | re.DOTALL) def replace(match): matched_pattern = match.group(1) next_char = match.group(2) new_pattern = patterns.get(matched_pattern, default_name) # In this case, the cased old model did not respect CamelCase and was all UPPERCASE, so we need to rely on next char # The heuristic is: if next char is not a letter, then it is not part of a model name and result should be `new_name`.upper() if len(patterns) == 2 and matched_pattern.isupper(): if not next_char.isalpha(): # `new_name.upper()` is just the other entry for `matched_pattern.lower()`, uppercased new_pattern = patterns[matched_pattern.lower()].upper() return new_pattern + next_char return compiled_regex.sub(replace, text) def get_cased_name(lowercase_name: str) -> str: """From a model name in lowercase in the format `my_model`, return the cased name in the format `MyModel`.""" alt_lowercase_name = lowercase_name.replace("_", "-") if lowercase_name in CONFIG_MAPPING_NAMES: return CONFIG_MAPPING_NAMES[lowercase_name].replace("Config", "") elif alt_lowercase_name in CONFIG_MAPPING_NAMES: return CONFIG_MAPPING_NAMES[alt_lowercase_name].replace("Config", "") else: return "".join(x.title() for x in lowercase_name.split("_")) def get_lowercase_name(cased_name: str) -> str: """From a model name in Camelcase in the format `MyModel`, return the lowercase name in the format `my_model`.""" inverse_mapping = {value: key for key, value in CONFIG_MAPPING_NAMES.items()} if cased_name + "Config" in inverse_mapping: return inverse_mapping[cased_name + "Config"] else: return "_".join([s.lower() for s in re.findall(r"[A-Z][^A-Z]*", cased_name)]) class ReplaceNameTransformer(m.MatcherDecoratableTransformer): """A transformer that replaces `old_name` with `new_name` in comments, string and any references. It should take into account name like `MyNewModel`, or `my_new_model`. Without using the AUTO_MAPPING. Supported renaming patterns: - llama -> my_new_model and my_new_model -> llama - Llama -> MyNewModel and MyNewModel -> Llama - LLAMA -> MY_NEW_MODEL and MY_NEW_MODEL -> LLAMA - LLaMa -> MyNewModel abd MyNewModel -> Llama """ def __init__(self, old_name: str, new_name: str, original_new_model_name: str = "", only_doc: bool = False): super().__init__() old_name = old_name.replace("-", "_") new_name = new_name.replace("-", "_") self.old_name = old_name self.new_name = new_name self.cased_new_name = get_cased_name(self.new_name) self.cased_old_name = get_cased_name(self.old_name) self.patterns = { old_name: new_name, old_name.upper(): new_name.upper(), # For some old models, `self.cased_old_name` == `old_name.upper()` in which case this overwrite previous entry self.cased_old_name: self.cased_new_name, } # In case new_name is a prefix alias, and not the original new model name self.original_new_model_name = original_new_model_name self.only_doc = only_doc def _replace_name(self, original_node, updated_node): if re.findall(r"# Copied from", updated_node.value): return cst.RemoveFromParent() update = preserve_case_replace(updated_node.value, self.patterns, self.cased_new_name) return updated_node.with_changes(value=update) @m.leave(m.SimpleString() | m.Comment()) def replace_name(self, original_node, updated_node): return self._replace_name(original_node, updated_node) def leave_Name(self, original_node, updated_node): if not self.only_doc: return self._replace_name(original_node, updated_node) return updated_node def leave_ImportFrom(self, original_node, updated_node): """ The imports from other file types (configuration, processing etc) should use original model name. Also, no replaces on absolute imports (e.g. `from mamba_ssm import ...`) """ if len(original_node.relative) == 0: # no replaces on absolute imports return original_node if self.original_new_model_name != self.new_name and m.matches(updated_node.module, m.Name()): patterns = "|".join(ALL_FILE_TYPES) regex = rf"({patterns})_{self.new_name}" new_source = re.sub( regex, lambda m: f"{m.group(1)}_{self.original_new_model_name}", updated_node.module.value ) updated_node = updated_node.with_changes(module=updated_node.module.with_changes(value=new_source)) return updated_node DOCSTRING_NODE = m.SimpleStatementLine( body=[ m.Expr( value=m.SimpleString( # match anything between """ """ value=m.MatchIfTrue(lambda value: re.search(r"\"\"\"[\s\S]*\"\"\"", value) is not None) ) ) ] ) def SUPER_CALL_NODE(func_name): return m.Call(func=m.Attribute(value=m.Call(func=m.Name("super")), attr=m.Name(func_name))) def is_call_to_super(node, func_name): return m.matches( node, m.SimpleStatementLine(body=[m.Return(SUPER_CALL_NODE(func_name)) | m.Expr(SUPER_CALL_NODE(func_name))]) ) def get_full_attribute_name(node: Union[cst.Attribute, cst.Name]) -> Optional[str]: """Get the full name of an Attribute or Name node (e.g. `"nn.Module"` for an Attribute representing it). If the successive value of an Attribute are not Name nodes, return `None`.""" if m.matches(node, m.Name()): return node.value elif m.matches(node, m.Attribute()): if not m.matches(node.attr, m.Name()): return None name = node.attr.value new_node = node.value while m.matches(new_node, m.Attribute()): if not m.matches(new_node.attr, m.Name()): return None name = new_node.attr.value + "." + name new_node = new_node.value if not m.matches(new_node, m.Name()): return None return new_node.value + "." + name return None # Transformer class to replace ClassB.call_to_method and ClassB().call_to_method with super().call_to_method class ReplaceMethodCallTransformer(cst.CSTTransformer): def __init__(self, all_bases: set[str]): self.all_bases = all_bases def leave_Attribute(self, original_node: cst.Attribute, updated_node: cst.Attribute) -> cst.CSTNode: # Handle ClassB.call_to_method or module.classB.call_to_method if ( m.matches(original_node.value, m.Name() | m.Attribute()) and get_full_attribute_name(original_node.value) in self.all_bases and m.matches(original_node.attr, m.Name()) ): # Replace with super().call_to_method return updated_node.with_changes( value=cst.Call(cst.Name("super")), ) # Handle ClassB().call_to_method or module.ClassB().call_to_method elif ( m.matches(original_node.value, m.Call()) and m.matches(original_node.value.func, m.Name() | m.Attribute()) and get_full_attribute_name(original_node.value.func) in self.all_bases and m.matches(original_node.attr, m.Name()) ): # Replace with super().call_to_method return updated_node.with_changes(value=cst.Call(cst.Name("super"))) return updated_node def leave_Call(self, original_node: cst.Call, updated_node: cst.Call) -> cst.CSTNode: # Check if the function being called is of the form ClassB().func_a or ClassB.func_a if m.matches(original_node.func, m.Attribute()) and ( # Match ClassB().func_a(...) or module ( m.matches(original_node.func.value, m.Call()) and m.matches(original_node.func.value.func, m.Name() | m.Attribute()) and get_full_attribute_name(original_node.func.value.func) in self.all_bases ) or # Match ClassB.func_a(...) ( m.matches(original_node.func.value, m.Name() | m.Attribute()) and get_full_attribute_name(original_node.func.value) in self.all_bases ) ): # Check if the first argument is 'self', and remove it if len(original_node.args) > 0 and m.matches(original_node.args[0].value, m.Name("self")): # Create the new argument list without 'self' new_args = updated_node.args[1:] else: new_args = updated_node.args return updated_node.with_changes(args=new_args) return updated_node class SuperTransformer(cst.CSTTransformer): METADATA_DEPENDENCIES = (ParentNodeProvider,) def __init__(self, python_module: cst.Module, original_modeling_methods, modular_methods, all_bases=None): self.python_module = python_module self.original_modeling_methods = original_modeling_methods self.modular_methods = modular_methods self.all_assign_target = {} self.deleted_targets = {} # child node can delete some arguments self.all_bases = all_bases or [] self.transformer = ReplaceMethodCallTransformer(set(self.all_bases)) def update_body(self, existing_body, new_statements): """ Helper method to update the body by removing duplicates before adding new statements. `existing_body` is the body of the original method, the parent class `new_statements` are the additional statements """ deduplicated_new_body = [] existing_nodes = set() for node in new_statements: if m.matches(node, m.SimpleStatementLine(body=[m.Assign()])): target = self.python_module.code_for_node(node.body[0].targets[0].target) self.all_assign_target[target] = node if m.matches(node, m.SimpleStatementLine(body=[m.Del()])): target = self.python_module.code_for_node(node.body[0].target) self.deleted_targets[target] = node for stmt in existing_body: if m.matches(stmt, m.SimpleStatementLine(body=[m.Assign()])): target = self.python_module.code_for_node(stmt.body[0].targets[0].target) if target in self.deleted_targets: continue if target in self.all_assign_target: stmt = self.all_assign_target[target] # Skip the docstring (will be added later on, at the beginning) elif m.matches(stmt, DOCSTRING_NODE): continue comment_less_code = re.sub(r"#.*", "", self.python_module.code_for_node(stmt)).strip() comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() deduplicated_new_body.append(stmt) existing_nodes.add(comment_less_code) for node in new_statements: code = self.python_module.code_for_node(node) comment_less_code = re.sub(r"#.*", "", code).strip() comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() if node not in deduplicated_new_body and comment_less_code not in existing_nodes: if not m.matches(node, m.SimpleStatementLine(body=[m.Del()])): deduplicated_new_body.append(node) existing_nodes.add(comment_less_code) deduplicated_new_body = self._fix_post_init_location(deduplicated_new_body) return deduplicated_new_body def _fix_post_init_location(self, new_body: list[cst.CSTNode]): """Fix the location of the `post_init()` in the new body, if we added statements after the call to `super()` (it needs to be the very last statement called)""" # Fix the post_init() that has to be last for i, node in enumerate(new_body): code = self.python_module.code_for_node(node) comment_less_code = re.sub(r"#.*", "", code).strip() comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() if "self.post_init(" in comment_less_code and i < len(new_body) - 1: # Remove it and add it again at the end new_body.pop(i) new_body.append(node) break return new_body def _fix_init_location(self, new_body): """Fix the location of the `super().__init__()` in the new body, if we had new statements before it.""" start_index = 0 for i, node in enumerate(new_body): if m.matches(node, DOCSTRING_NODE) and i == start_index: start_index += 1 continue code = self.python_module.code_for_node(node) comment_less_code = re.sub(r"#.*", "", code).strip() comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() if "super().__init__" in comment_less_code and i > start_index: # Remove it and add it again at the top after the docstrings node = new_body.pop(i) new_body = new_body[:start_index] + [node] + new_body[start_index:] break return new_body def replace_super_calls(self, node: cst.BaseSuite, func_name: str) -> cst.BaseSuite: """Updates the body of the input `node`'s `func_name` function by replacing calls to super().func_name() with the source code of the parent class' `func_name`. It keeps everything that is defined before `super().func_name()`. """ new_body = [] modular_node_body = node.body for i, expr in enumerate(modular_node_body): if is_call_to_super(expr, func_name): original_modeling_method_body = self.original_modeling_methods[func_name].body.body new_body.extend(self.update_body(original_modeling_method_body, modular_node_body[i + 1 :])) new_body = self._fix_init_location(new_body) return node.with_changes(body=new_body) else: expr = expr.visit(self.transformer) if not m.matches(expr, m.SimpleStatementLine(body=[m.Del()])): new_body.append(expr) return node.with_changes(body=new_body) def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef: name = updated_node.name.value if name in self.modular_methods: new_body = self.replace_super_calls(updated_node.body, name) return updated_node.with_changes(body=new_body, params=updated_node.params) return updated_node def find_all_dependencies( dependency_mapping: dict[str, set], start_entity: Optional[str] = None, initial_dependencies: Optional[set] = None, initial_checked_dependencies: Optional[set] = None, return_parent: bool = False, ) -> Union[list, set]: """Return all the dependencies of the given `start_entity` or `initial_dependencies`. This is basically some kind of BFS traversal algorithm. It can either start from `start_entity`, or `initial_dependencies`. Args: dependency_mapping (`Dict[str, set]`): A mapping from entities (usually function/assignment names), to immediate dependencies. That is, for function names, a mapping {"foo": {"bar", "test"}} would indicate that functions `bar` and `test` are immediately called in `foo`'s definition. start_entity (str | None, *optional*): A key of `dependency_mapping`, indicating from which entity to start the search. initial_dependencies (set | None, *optional*): If `start_entity` is not provided, this can be used as an alternative. In this case, the search will continue from all the entities in `initial_dependencies`, if they are in `dependency_mapping`. initial_checked_dependencies (set | None, *optional*): If provided, entities already present in `initial_checked_dependencies` will not be part of the returned dependencies. return_parent (bool, *optional*): If `True`, will return a list consisting of tuples (dependency, parent) instead of a simple set of dependencies. Note that the order of the items in the list reflects the traversal order. Thus, no parent can ever appear before childs. Returns: A set of all the dependencies, or a list of tuples `(dependency, parent)` if `return_parent=True`. Example: Given the following structure in the `modular_xxx.py` file: ``` def foo1(): pass def foo2(): pass def bar(): foo1() def foobar(): bar() foo2() class MyLayer(SomeOtherModelLayer): def forward(...): foobar() ``` and the `dependency_mapping` created when visiting the `modular_xxx.py` file, we get: ``` dependency_mapping = {'bar': {'foo1'}, 'foobar': {'bar', 'foo2'}} find_all_dependencies(dependency_mapping, start_entity='foobar', return_parent=True) >>> [('bar', 'foobar'), ('foo2', 'foobar'), ('foo1', 'bar')] ``` That is, all the functions needed (and potentially their immediate parent) so that the function to be added in MyLayer (`foobar`) can work correctly. """ if initial_dependencies is None and start_entity is not None: initial_dependencies = dependency_mapping[start_entity] if initial_checked_dependencies is None: initial_checked_dependencies = set() dependency_queue = deque(initial_dependencies) all_dependencies = set() all_dependencies_with_parent = [] checked_dependencies = set(initial_checked_dependencies) parents = dict.fromkeys(initial_dependencies, start_entity) while len(dependency_queue) > 0: # Pick element to visit current = dependency_queue.popleft() if current not in checked_dependencies: # Add the dependencies all_dependencies.add(current) all_dependencies_with_parent += [(current, parents[current])] if current in dependency_mapping: # Update dependency queue dependency_queue.extend(dependency_mapping[current]) parents.update(dict.fromkeys(dependency_mapping[current], current)) # add visited node to the list checked_dependencies.add(current) if not return_parent: return all_dependencies # no child can ever appear before its parent thanks to the queue (needed to add them at the correct location in the body later) return all_dependencies_with_parent # Top-level variables that match the following patterns will always use the value in the `modular_xxx.py` file ASSIGNMENTS_REGEX_TO_KEEP = [r"_CHECKPOINT", r"_EXPECTED", r"_FOR_DOC", r"_HIDDEN_STATES_START_POSITION"] # Top-level variables that match the following patterns will use the value in the `modular_xxx.py` file only if they are not None ASSIGNMENTS_REGEX_TO_KEEP_IF_NOT_NONE = [r"_DOCSTRING"] class ClassDependencyMapper(CSTVisitor): """A visitor which is designed to analyze a single class node to get all its dependencies that are shared with the set of `global_names`. """ def __init__( self, class_name: str, global_names: set[str], objects_imported_from_modeling: Optional[set[str]] = None ): super().__init__() self.class_name = class_name self.dependencies = set() self.global_names = global_names self.objects_imported_from_modeling = ( set() if objects_imported_from_modeling is None else objects_imported_from_modeling ) def visit_Name(self, node): if ( node.value != self.class_name and node.value in self.global_names and node.value not in self.objects_imported_from_modeling ): self.dependencies.add(node.value) def dependencies_for_class_node(node: cst.ClassDef, global_names: set[str]) -> set: """Create immediate dependencies for a class node based on the `global_names`.""" temp_module = cst.Module(body=[node]) visitor = ClassDependencyMapper(node.name.value, global_names) temp_module.visit(visitor) return visitor.dependencies def augmented_dependencies_for_class_node( node: cst.ClassDef, mapper: "ModuleMapper", objects_imported_from_modeling: Optional[set[str]] = None ) -> set: """Create augmented dependencies for a class node based on a `mapper`. Augmented dependencies means immediate dependencies + recursive function and assignments dependencies. """ temp_module = cst.Module(body=[node]) visitor = ClassDependencyMapper(node.name.value, set(mapper.global_nodes.keys()), objects_imported_from_modeling) temp_module.visit(visitor) return mapper.augment_dependencies(visitor.dependencies) # All the potential file types to create ALL_FILE_TYPES = ( "modeling", "configuration", "tokenization", "processing", "image_processing", "video_processing", "feature_extraction", ) class ModuleMapper(CSTVisitor, ABC): """An abstract visitor class which analyses a module, creating a mapping of dependencies for classes, functions and assignments. Class dependencies are computed with `compute_class_dependencies()`, while function and assignment dependencies are stored in `self.object_recursive_dependency_mapping` (can be computed by `_compute_recursive_object_dependencies()`). It defines common visiting patterns (i.e. common visit_xxx/leave_xxx functions) between the modular file and the modeling files that will be visited. """ METADATA_DEPENDENCIES = (ParentNodeProvider, PositionProvider) def __init__(self, python_module: cst.Module): # fmt: off self.python_module: cst.Module = python_module # original cst.Module being visited self.classes: dict[str, cst.ClassDef] = {} # mapping from class names to Nodes (it will be ordered by default!!) self.imports = [] # stores all import statements self.functions: dict[str, cst.FunctionDef] = {} # mapping of global scope function names to Nodes self.object_dependency_mapping = defaultdict(set) # immediate function/assignment dependency mapping (i.e. dependencies immediately in the function/assignment definition) self.assignments: dict[str, cst.SimpleStatementLine] = {} # mapping of global assignments names to Nodes self.current_function = None # this keeps track of the current module-scope function self.current_class = None # this keeps track of the current module-scope class self.current_assignment = None # this keeps track of the current module-scope assignment # this keeps track of objects imported from modeling files (`from .configuration import Config`) -> `Config` should not be a dependency self.objects_imported_from_modeling = set() # regex pattern joining every possible file type self.match_patterns = "|".join(ALL_FILE_TYPES) # fmt: on def visit_ImportFrom(self, node): """This keeps track of objects imported from neighbor modeling files (e.g. in `modeling_xxx.py, we have `from .configuration_xxx import Config`, then `Config` should be recorded as it is not a dependency that needs to be added (because it will be part of the imports)""" import_module = self.python_module.code_for_node(node.module) import_statement = "." * len(node.relative) + import_module if re.search(rf"^\.({self.match_patterns})_.*", import_statement): for imported_object in node.names: # If an alias is present, we record it and not the original name if imported_object.evaluated_alias is not None: self.objects_imported_from_modeling.add(imported_object.evaluated_alias) else: self.objects_imported_from_modeling.add(imported_object.evaluated_name) def visit_SimpleStatementLine(self, node): """ Global Assigns like `GEMMA_INPUT_DOCSTRING = 'THIS IS THE INPUT'` and all import statements are extracted and saved in their corresponding dict. They are then used when updating dependency mappings. """ parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) simple_top_level_assign_structure = m.SimpleStatementLine( body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])] ) simple_top_level_variable_indexing = m.SimpleStatementLine( body=[m.Assign(targets=[m.AssignTarget(target=m.Subscript(value=m.Name()) | m.Attribute(value=m.Name()))])] ) if m.matches(parent_node, m.Module()): if m.matches(node, simple_top_level_assign_structure): left_hand_side = node.body[0].targets[0].target.value self.current_assignment = left_hand_side self.assignments[left_hand_side] = node # This corresponds to a global variable being indexed or having an attribute look-up elif m.matches(node, simple_top_level_variable_indexing): indexed_variable = node.body[0].targets[0].target.value.value # We should follow any dependencies relative to the variable being indexed self.current_assignment = indexed_variable # The indexing node should be directly added as a dependency of the indexed variable (register the node with a "fake" name) node_name = self.python_module.code_for_node(node) self.assignments[node_name] = node self.object_dependency_mapping[indexed_variable].add(node_name) elif m.matches(node, m.SimpleStatementLine(body=[m.Import() | m.ImportFrom()])): self.imports.append(node) def leave_SimpleStatementLine(self, node): # No need to check for the parent here -> everytime we exit one, it should be None anyway independently of where the # SimpleStatement is located self.current_assignment = None def visit_FunctionDef(self, node): parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) if m.matches(parent_node, m.Module()): self.current_function = node.name.value self.functions[node.name.value] = node def leave_FunctionDef(self, node): parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) if m.matches(parent_node, m.Module()): self.current_function = None def visit_If(self, node): # If we are inside a function, do not add the import to the list of imports if self.current_function is None and self.current_class is None: for stmt in node.body.body: if m.matches(stmt, m.SimpleStatementLine(body=[m.ImportFrom() | m.Import()])): self.imports.append(node) def visit_ClassDef(self, node: ClassDef) -> None: """Record class nodes to create their dependencies at the end.""" self.classes[node.name.value] = node self.current_class = node.name.value def leave_ClassDef(self, node): self.current_class = None def visit_Name(self, node: cst.Call): """This is used to create a mapping from module-scope functions and assignments to objects used inside them.""" if self.current_function is not None: self.object_dependency_mapping[self.current_function].add(node.value) if self.current_assignment is not None: self.object_dependency_mapping[self.current_assignment].add(node.value) def leave_Module(self, node): """When leaving the module, we store the position of each global scoped node to allow sorting the dependencies based on their position in the code later. We use the PositionProvider metadata wrapper for this. We also make sure to update `self.object_dependency_mapping` so that it contains only names recorded in `self.global_nodes`. """ # assign all nodes self.global_nodes = {**self.assignments, **self.classes, **self.functions} # now sort the class dependency_mapping based on the position of the nodes self.start_lines = {} for id, node in self.global_nodes.items(): self.start_lines[id] = self.get_metadata(cst.metadata.PositionProvider, node).start.line def _restrict_dependencies_to_known_entities(self): """Since we added every Name as part of `self.object_dependency_mapping`, we need to remove those that are not part of the recorded objects in `self.global_nodes` (i.e. built-in variables, imports, etc). This should be called only after all merging operations have been finalized!!""" global_objects = set(self.global_nodes.keys()) for object_name, dependencies in self.object_dependency_mapping.items(): self.object_dependency_mapping[object_name] = {dep for dep in dependencies if dep in global_objects} def _compute_recursive_object_dependencies(self) -> dict[str, set]: """Based on immediate dependency mapping, create the recursive dependency mapping. For example, given the following file: ``` def foo(): pass def bar(): foo() def test(): bar() ``` this visitor can only record immediate dependencies, i.e. it will record the following `self.object_dependency_mapping = {"test": {"bar"}, "bar": {"foo}}`. This function is used to create the recursive mapping, i.e. `recursive_dependencies = {"test": {"bar", "foo"}, "bar": {"foo}}`. """ recursive_dependencies = {} for object_name in self.object_dependency_mapping: all_dependencies = find_all_dependencies(self.object_dependency_mapping, start_entity=object_name) recursive_dependencies[object_name] = all_dependencies return recursive_dependencies def augment_dependencies(self, dependencies: set[str]) -> set[str]: """For a set of `dependencies`, augment them by adding all potential dependencies of the **functions** and **assignments** present in the `dependencies`. """ new_dependencies = dependencies.copy() # Go through the set of dependencies for dep in tuple(dependencies): if dep in self.object_recursive_dependency_mapping: new_dependencies.update(self.object_recursive_dependency_mapping[dep]) return new_dependencies def compute_class_dependencies(self): """For each visited class, find its dependencies based on visiting the current file + potential merged dependencies.""" self.class_dependency_mapping = {} for class_name, class_node in self.classes.items(): dependencies = dependencies_for_class_node(class_node, set(self.global_nodes.keys())) # Correctly augment class dependencies with all needed objects self.class_dependency_mapping[class_name] = self.augment_dependencies(dependencies) @abstractmethod def compute_relative_order(self, missing_dependencies: set) -> dict[str, int]: raise NotImplementedError class ModelFileMapper(ModuleMapper): """A mapper designed to parse modeling files (like `modeling_llama.py`). When encountering such a file in the `modular_xxx.py` file, we need to correctly visit it and merge the dependencies of the modular and current file. For this reason, this class should only be instantiated from the class method `visit_and_merge_dependencies`, which takes care of correctly merging dependencies, then finalizes all dependency graph computations. Note that we only merge functions and assignments here, as classes will be treated later on as they may be modified. For example, if you redefine `apply_rotary_pos_emb()` in the modular, the new node should be used in the dependencies of the modeling files as well. """ def __init__(self, python_module: cst.Module): super().__init__(python_module) def compute_relative_order(self, missing_dependencies: set[str]) -> dict[str, int]: """Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that will be created based on the modular. """ relative_order = {} idx = 0 classes = sorted( [dep for dep in tuple(missing_dependencies) if dep in self.classes], key=lambda x: self.start_lines[x] ) # This is because for merged dependencies, we only have relative order in the other visited file, so we need # to track dependency order relative to a given class if len(classes) > 0 and not hasattr(self, "class_dependency_mapping"): raise ValueError("Cannot correctly find the relative order of the dependencies.") remaining_dependencies = missing_dependencies.copy() # Start by tracking relative order class by class for class_name in classes: class_dependencies = tuple(self.class_dependency_mapping[class_name] & remaining_dependencies) original_dependencies = [] merged_dependencies = [] # We need to differentiate between nodes that were already present (we can get relative order globally) and # nodes that were merged (we can get relative order only relative to the class the dependencies relate to) for class_dep in class_dependencies: if class_dep in self.start_lines: original_dependencies.append(class_dep) else: merged_dependencies.append(class_dep) # We need to sort deterministically before actual sorting, so that entries missing (i.e. with value 1e10) # will always get the same order independently of the system (they come from a set, which has no deterministic order) original_dependencies = sorted(original_dependencies, reverse=True) # Sort both list according to the order in their respective file original_dependencies = sorted(original_dependencies, key=lambda x: self.start_lines.get(x, 1e10)) merged_dependencies = sorted(merged_dependencies, key=lambda x: self.modular_file_start_lines[x]) # Add all original node first, then merged ones for dep in original_dependencies + merged_dependencies: remaining_dependencies.remove(dep) relative_order[dep] = idx idx += 1 # Add the class itself (it can sometimes already be present if the order of classes in the source file # does not make sense, i.e. a class is used somewhere before being defined like in `rt_detr`...) if class_name in remaining_dependencies: remaining_dependencies.remove(class_name) relative_order[class_name] = idx idx += 1 # Now add what still remains remaining_dependencies = tuple(remaining_dependencies) original_dependencies = [] merged_dependencies = [] for dep in remaining_dependencies: if dep in self.modular_file_start_lines: merged_dependencies.append(dep) else: original_dependencies.append(dep) # We need to sort deterministically before actual sorting, so that entries missing (i.e. with value 1e10) # will always get the same order independently of the system (they come from a set, which has no deterministic order) original_dependencies = sorted(original_dependencies, reverse=True) # Sort both list according to the order in their respective file original_dependencies = sorted(original_dependencies, key=lambda x: self.start_lines.get(x, 1e10)) merged_dependencies = sorted(merged_dependencies, key=lambda x: self.modular_file_start_lines[x]) # Add all original node first, then merged ones for dep in original_dependencies + merged_dependencies: relative_order[dep] = idx idx += 1 return relative_order def _merge_functions(self, functions: dict[str, cst.CSTNode], object_mapping: dict[str, set]): """Update the global nodes and function dependency mapping with those from the modular file. Merging rule: if any function with the same name was redefined in the modular, use it and its dependencies instead of the original ones (this may mean to add new functions as well, if any redefined function uses a new one). """ # Add/overwrite all needed function nodes and dependencies self.functions.update(functions) self.object_dependency_mapping.update({obj: dep for obj, dep in object_mapping.items() if obj in functions}) # Add them to global nodes self.global_nodes.update(self.functions) def _merge_assignments(self, assignments: dict[str, cst.CSTNode], object_mapping: dict[str, set]): """Update the global nodes with the assignment from the modular file. Merging rule: if any assignment with the same name was redefined in the modular, we use it and its dependencies ONLY if it matches a pattern in `ASSIGNMENTS_REGEX_TO_KEEP_IF_NOT_NONE` and its value is not None, or if it matches a pattern in `ASSIGNMENTS_REGEX_TO_KEEP. Otherwise, we use the original value and dependencies. This rule was chosen to avoid having to rewrite the big docstrings. """ for assignment, node in assignments.items(): should_keep = any(re.search(pattern, assignment) for pattern in ASSIGNMENTS_REGEX_TO_KEEP) should_keep_if_not_none = any( re.search(pattern, assignment) for pattern in ASSIGNMENTS_REGEX_TO_KEEP_IF_NOT_NONE ) and not (hasattr(node.body[0].value, "value") and node.body[0].value.value == "None") if should_keep or should_keep_if_not_none or assignment not in self.assignments: self.assignments[assignment] = node if assignment in object_mapping: self.object_dependency_mapping[assignment] = object_mapping[assignment] # Add them to global nodes self.global_nodes.update(self.assignments) def _merge_classes(self, classes: dict[str, cst.CSTNode]): """Update the global nodes with the new classes from the modular (i.e. classes which do not exist in current file, and are not imported). We do NOT update any dependency mapping here. This is because we only need the names of newly defined classes in the modular to be discoverable when computing dependencies for new nodes later on. For this reason, we do not add the new classes to `self.classes`, but only to `global_nodes`. """ # Add/overwrite all needed function nodes and dependencies self.global_nodes.update( { name: node for name, node in classes.items() if name not in self.classes and name not in self.objects_imported_from_modeling } ) def merge_modular_dependencies(self, classes, functions, assignments, object_mapping, start_lines): """Merge classes, functions and assignments from the modular definitions into the current module file, then record the relative order of all nodes. Note: This function takes care of updating `global_nodes` and `object_recursive_dependency_mapping` as well after the merge with other files dependencies. """ self._merge_functions(functions, object_mapping) self._merge_assignments(assignments, object_mapping) self._merge_classes(classes) self.modular_file_start_lines = start_lines # Restrict the dependency mappings to the known entities to avoid Python's built-ins and imports self._restrict_dependencies_to_known_entities() # Create the global mapping of recursive dependencies for functions and assignments self.object_recursive_dependency_mapping = self._compute_recursive_object_dependencies() @classmethod def visit_and_merge_dependencies( cls, module: cst.Module, classes, functions, assignments, object_mapping, start_lines ) -> "ModelFileMapper": wrapper = MetadataWrapper(module) mapper = cls(module) wrapper.visit(mapper) # Merge dependencies mapper.merge_modular_dependencies(classes, functions, assignments, object_mapping, start_lines) # Create the class dependencies graph mapper.compute_class_dependencies() return mapper def common_partial_suffix(str1: str, str2: str) -> str: """Return the biggest common suffix between 2 strings. If one string is a full suffix of the other string, we do not consider it a common suffix and return `""`""" common_suffix = "" for i in range(1, min(len(str1), len(str2)) + 1): if str1[-i] == str2[-i]: common_suffix = str1[-i] + common_suffix else: break # We do not allow full string suffix if common_suffix == str1 or common_suffix == str2: common_suffix = "" return common_suffix def replace_class_node( mapper: ModelFileMapper, modular_class_node: cst.ClassDef, renamed_super_class: str, original_super_class: str ) -> cst.ClassDef: """ Replace a class node which inherits from another modeling class. This function works in the following way: - start from the methods and class attributes of the original modeling code node, and replace their definition if overriden in the modular - append all new methods and class attributes defined in the child class - all potential method/class docstrings and decorators use the ones found in modular if any, else in original modeling - replace all calls to super() with the unravelled code Args: mapper (`ModelFileMapper`): The mapper corresponding to the visited file from which the modular class node inherits. modular_class_node (`cst.ClassDef`): The class node as found in the modular file. renamed_super_class (`str`): The name of the class from which `modular_class_node` inherits after automatic renaming. original_super_class (`str`): The name of the class from which `modular_class_node` inherits before automatic renaming. Returns: A new class node corresponding to the modular definition. """ all_bases = [get_full_attribute_name(k.value) for k in modular_class_node.bases] if any(base is None for base in all_bases): raise ValueError(f"Could not parse the name of the bases for {modular_class_node.name.value}") original_modeling_node = mapper.classes[renamed_super_class] # Always use the new name of the class (in case we use e.g. `ColPaliForRetrieval` inheriting from `PaliGemmaForConditionalGeneration`) new_class_name = modular_class_node.name # If the new class name is different from the renamed super class name, we need to update the docstrings/comments accordingly if new_class_name.value != renamed_super_class: common_suffix = common_partial_suffix(new_class_name.value, renamed_super_class) # Note that this works even without common prefix, in which case it does not replace anything old, new = renamed_super_class.replace(common_suffix, ""), new_class_name.value.replace(common_suffix, "") temp_module = cst.Module(body=[original_modeling_node]) original_modeling_node = temp_module.visit( ReplaceNameTransformer(get_lowercase_name(old), get_lowercase_name(new), only_doc=True) ).body[0] # If we explicitly passed a new base with common suffix to an old base, it is for switching the prefix # e.g. if the "natural" parent class is `PreTrainedModel` but we wanted to rename it to `PreTrainedVisionModel` additional_bases = [base for base in all_bases if base != original_super_class] new_class_bases = [] for original_base in original_modeling_node.bases: new_base = original_base # we only potentially switch base for Name-based bases, not Attribute if m.matches(original_base.value, m.Name()): original_base_name = original_base.value.value for additional_base_name in additional_bases: suffix = common_partial_suffix(original_base_name, additional_base_name) if len(suffix) > 0 and suffix[0].isupper(): new_name_node = original_base.value.with_changes(value=additional_base_name) new_base = original_base.with_changes(value=new_name_node) break new_class_bases.append(new_base) # Use class decorators redefined in modular file if any new_class_decorators = ( modular_class_node.decorators if len(modular_class_node.decorators) > 0 else original_modeling_node.decorators ) # Compute new class docstring original_modeling_docstring = [ node for node in original_modeling_node.body.body if m.matches(node, DOCSTRING_NODE) ] modular_docstring = [node for node in modular_class_node.body.body if m.matches(node, DOCSTRING_NODE)] # Use class docstring in modular if any, else original modeling code docstring new_class_docstring = modular_docstring if len(modular_docstring) > 0 else original_modeling_docstring # Compute new class attributes original_modeling_class_attributes = {} for node in original_modeling_node.body.body: if m.matches(node, m.SimpleStatementLine(body=[m.Assign()])): original_modeling_class_attributes[node.body[0].targets[0].target.value] = node elif m.matches(node, m.SimpleStatementLine(body=[m.AnnAssign()])): original_modeling_class_attributes[node.body[0].target.value] = node modular_class_attributes = {} for node in modular_class_node.body.body: if m.matches(node, m.SimpleStatementLine(body=[m.Assign()])): modular_class_attributes[node.body[0].targets[0].target.value] = node elif m.matches(node, m.SimpleStatementLine(body=[m.AnnAssign()])): modular_class_attributes[node.body[0].target.value] = node # Use all original modeling attributes, and potentially override some with values in the modular new_class_attributes = list({**original_modeling_class_attributes, **modular_class_attributes}.values()) # Check class methods defined in the modular and associated modeling original_modeling_methods = {} for node in original_modeling_node.body.body: if m.matches(node, m.FunctionDef()): # Due to the @property and @name.setter decorators, methods can sometimes have the same name, so we need a way # to separate them if node.name.value in original_modeling_methods: # If it's already present, and the decorator is @property, it means the node already added was the setter if node.decorators[0].decorator.value == "property": original_modeling_methods[f"{node.name.value}_setter"] = original_modeling_methods[node.name.value] original_modeling_methods[node.name.value] = node # In this case current node is the setter else: original_modeling_methods[f"{node.name.value}_setter"] = node else: original_modeling_methods[node.name.value] = node modular_methods = {} for node in modular_class_node.body.body: if m.matches(node, m.FunctionDef()): # Due to the @property and @name.setter decorators, methods can sometimes have the same name, so we need a way # to separate them if node.name.value in modular_methods: # If it's already present, and the decorator is @property, it means the node already added was the setter if node.decorators[0].decorator.value == "property": modular_methods[f"{node.name.value}_setter"] = modular_methods[node.name.value] modular_methods[node.name.value] = node # In this case current node is the setter else: modular_methods[f"{node.name.value}_setter"] = node else: modular_methods[node.name.value] = node new_class_methods = [] # Iterate over the methods of the original modeling code, and add them to the list of methods to add for name, node in original_modeling_methods.items(): # If the method was redefined in modular, make appropriate changes to the node if name in modular_methods: # Get the corresponding method node in modular modular_node = modular_methods[name] # If we match the pattern, we should avoid inheriting the method if re.match(r"\ndef .*\(.*\):\n raise.*Error\(.*", mapper.python_module.code_for_node(modular_node)): continue # Compute new method docstring modeling_docstring = [node_ for node_ in node.body.body if m.matches(node_, DOCSTRING_NODE)] modular_docstring = [node_ for node_ in modular_node.body.body if m.matches(node_, DOCSTRING_NODE)] # Use method docstring in modular if any, else original modeling code docstring new_body = ( modular_node.body.body if len(modular_docstring) > 0 else modeling_docstring + list(modular_node.body.body) ) new_body = modular_node.body.with_changes(body=new_body) # Use arguments as defined in the modular new_params = modular_node.params # If using the `**super_kwargs` syntax in modular, merge any existing modular arg with all the original modeling ones kwarg_name = getattr(modular_node.params, "star_kwarg", None) if kwarg_name and kwarg_name.name.value == "super_kwargs": original_modeling_params = {k.name.value: k for k in node.params.params} modular_params = {k.name.value: k for k in new_params.params[1:]} new_param_list = list({**original_modeling_params, **modular_params}.values()) new_params = new_params.with_changes(params=new_param_list, star_kwarg=node.params.star_kwarg) # Keep decorators in modular if any, else original decorators new_decorators = modular_node.decorators if len(modular_node.decorators) > 0 else node.decorators # Keep return annotation in modular if any, else original return annotation new_return_annotation = modular_node.returns if modular_node.returns else node.returns # Update the method node node = node.with_changes( body=new_body, params=new_params, decorators=new_decorators, returns=new_return_annotation, ) new_class_methods.append(node) # Port new methods that are defined only in modular-file and append at the end for name, node in modular_methods.items(): if name not in original_modeling_methods: new_class_methods.append(node) # Recreate the whole new class body new_class_body = new_class_docstring + new_class_attributes + new_class_methods # Replace the calls to `super()` of the redefined modular methods with the unrolled code result_node = original_modeling_node.with_changes(body=cst.IndentedBlock(body=new_class_body)) temp_module = cst.Module(body=[result_node]) new_module = MetadataWrapper(temp_module) new_replacement_class = new_module.visit( SuperTransformer(temp_module, original_modeling_methods, modular_methods, all_bases) ) new_class_body = new_replacement_class.body[0].body # get the indented block return original_modeling_node.with_changes( body=new_class_body, decorators=new_class_decorators, bases=new_class_bases, name=new_class_name ) TYPE_TO_FILE_TYPE = { "Config": "configuration", "Tokenizer": "tokenization", "Processor": "processing", "ImageProcessor": "image_processing", "ImageProcessorFast": "image_processing*_fast", # "*" indicates where to insert the model name before the "_fast" suffix "VideoProcessor": "video_processing", "VideoProcessorInitKwargs": "video_processing", "FastImageProcessorKwargs": "image_processing*_fast", "FeatureExtractor": "feature_extraction", "ProcessorKwargs": "processing", "VideosKwargs": "processing", "ImagesKwargs": "processing", "TextKwargs": "processing", } def find_file_type(class_name: str, model_name: str) -> str: """Based on a class name, find the file type corresponding to the class. If the class name is `LlamaConfig` it will return `configuration`. The list of suffixes is in `TYPE_TO_FILE_TYPE`. If there are no match, we match by default to `modeling` """ match_pattern = "|".join(TYPE_TO_FILE_TYPE.keys()) # We remove the model name to avoid ambiguity, e.g. for `Sam2VideoProcessor`, # removing `Sam2Video` ensures we match `Processor` instead of `VideoProcessor`. match = re.search(rf"({match_pattern})$", class_name.replace(get_cased_name(model_name), "")) if match: file_type = TYPE_TO_FILE_TYPE[match.group(1)] else: file_type = "modeling" return file_type # These top-level variables will always appear at the very beginning of the file, in the order they are defined in # this list (this is to avoid having variables at weird places, even if they are not used before) VARIABLES_AT_THE_BEGINNING = ( "logger", "_CHECKPOINT_FOR_DOC", "_CONFIG_FOR_DOC", ) # These specific modeling imports should not be visited as other modeling files IMPORTS_TO_SKIP_IN_MODULAR = ("auto.modeling_auto",) def append_new_import_node( node: cst.CSTNode, unused_imports: set[str], added_names: set, imports_to_keep: list[cst.CSTNode] ): """Insert the new `node` to the list of `imports_to_keep` in-place, if it is not part of the `unused_imports` or `added_names`. Also modifies `added_names` in-place accordingly.""" import_node = node.body[0] names_to_keep = [] for name in import_node.names: name_value = name.evaluated_alias or name.evaluated_name if name_value not in unused_imports and name_value not in added_names: names_to_keep.append(name.with_changes(comma=cst.MaybeSentinel.DEFAULT)) added_names.add(name_value) if len(names_to_keep) > 0: new_node = node.with_changes(body=[import_node.with_changes(names=names_to_keep)]) imports_to_keep.append(new_node) def get_needed_imports(body: dict[str, dict], all_imports: list[cst.CSTNode]) -> list[cst.CSTNode]: """Get all the imports needed in the `body`, from the list of `all_imports`. `body` is a dict with the following structure `{str: {"insert_idx": int, "node": cst.CSTNode}}`. Note: we need to use `isinstance` on scope assignments, m.matches apparently does not work here yet! """ new_body = [k[1]["node"] for k in sorted(body.items(), key=lambda x: x[1]["insert_idx"])] wrapper = MetadataWrapper(cst.Module(body=all_imports + new_body)) scopes = set(wrapper.resolve(ScopeProvider).values()) unused_imports = set() import_ref_count = defaultdict(lambda: 0) for scope in scopes: for assignment in scope.assignments: node = assignment.node if isinstance(assignment, cst.metadata.Assignment) and isinstance(node, (cst.Import, cst.ImportFrom)): ref_count = len(assignment.references) name = assignment.name import_ref_count[name] = max(ref_count, import_ref_count[name]) # Similar imports may be redefined, and only used between their 1st and 2nd definition so if we already have # a ref count > 0 at any point, the imports is actually used unused_imports = {name for name, count in import_ref_count.items() if count <= 0 or name in body} imports_to_keep = [] # We need to keep track of which names were already imported, because some import may be duplicated from multiple sources # or be both protected and unprotected due to inconsistency between models added_names = set() existing_protected_statements = set() # str repr of the import nodes - does not work with the nodes directly for node in all_imports: if m.matches(node, m.If()): # handle safe imports new_statements = [] for stmt_node in node.body.body: append_new_import_node(stmt_node, unused_imports, added_names, new_statements) new_statements = [stmt for stmt in new_statements if str(stmt) not in existing_protected_statements] if len(new_statements) > 0: new_node = node.with_changes(body=node.body.with_changes(body=new_statements)) imports_to_keep.append(new_node) existing_protected_statements.update({str(stmt) for stmt in new_statements}) else: append_new_import_node(node, unused_imports, added_names, imports_to_keep) protected_import_nodes = [node for node in imports_to_keep if m.matches(node, m.If())] usual_import_nodes = [node for node in imports_to_keep if not m.matches(node, m.If())] # Protected imports always appear at the end of all imports return usual_import_nodes + protected_import_nodes def split_all_assignment(node: cst.CSTNode, model_name: str) -> dict[str, cst.CSTNode]: """Split the `__all__` assignment found in the modular between each corresponding files.""" all_all_per_file = {} assign_node = node.body[0] if isinstance(assign_node.value, cst.List): # Extract the elements from the list all_all_to_add = defaultdict(list) for element in assign_node.value.elements: if isinstance(element.value, cst.SimpleString): # Remove quotes and add the string to the elements list class_name = element.value.value file = find_file_type(element.value.evaluated_value, model_name) all_all_to_add[file] += [class_name] for file, new_alls in all_all_to_add.items(): new_node = assign_node.with_changes( value=cst.List(elements=[cst.Element(value=cst.SimpleString(value=k)) for k in new_alls]) ) all_all_per_file[file] = node.with_changes(body=[new_node]) return all_all_per_file class ModularFileMapper(ModuleMapper): """This is a Mapper to visit a modular file (like `modular_llama.py`). It visits the whole file, recording dependency, then visits all imported modeling files (like `modeling_llama.py`), and manages their mutual dependencies. Calling the method `create_modules()` after visit will create all modules based on this modular file. """ def __init__(self, python_module, new_name): super().__init__(python_module) # fmt: off self.model_name = new_name # name of the model being defined. Should be in the format of `llama` or `layout_xlm` or `phi3` self.model_specific_imported_objects: dict[str, str] = {} # e.g. {"LlamaModel": "transformers.models.llama.modeling_llama"} self.model_specific_modules: dict[str, cst.Module] = {} # e.g. {"transformers.models.llama.modeling_llama": cst.Module} self.all_all_to_add = {} # fmt: on def visit_ImportFrom(self, node: cst.ImportFrom) -> None: """When visiting imports from modeling files (i.e. `transformers.models.xxx`) we get the code, parse it, and save it in `self.model_specific_modules` to later visit. The imported objects are saved in `self.model_specific_imported_objects`. """ import_module = self.python_module.code_for_node(node.module) import_statement = "." * len(node.relative) + import_module if any(import_to_skip in import_statement for import_to_skip in IMPORTS_TO_SKIP_IN_MODULAR): return if m.matches(node.module, m.Attribute()): for imported_ in node.names: _import = re.search( rf"(?:transformers\.models\.)|(?:\.\.)\w+\.({self.match_patterns})_.*", import_statement ) if _import: source = _import.group(1) if source == "modeling" and "Config" in self.python_module.code_for_node(imported_): raise ValueError( f"You are importing {self.python_module.code_for_node(imported_)} from the modeling file. Import from the `configuration_xxxx.py` file instead" ) if import_module not in self.model_specific_modules: if "models" not in import_module: import_module = "models." + import_module if "transformers" not in import_module: import_module = "transformers." + import_module source_code = get_module_source_from_name(import_module) tree = cst.parse_module(source_code) self.model_specific_modules[import_module] = tree imported_object = self.python_module.code_for_node(imported_.name) self.model_specific_imported_objects[imported_object] = import_module if m.matches(node.module, m.Name()): if "transformers" == import_module: raise ValueError( f"You are importing from {import_module} directly using global imports. Import from the correct local path" ) def visit_SimpleStatementLine(self, node): """If we visit an import statement not previously visited, record it. If we visit a module-scope assignment, simply record it or, if it is `__all__`, split it between files where we should dispatch it. """ parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) simple_top_level_assign_structure = m.SimpleStatementLine( body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])] ) simple_top_level_variable_indexing = m.SimpleStatementLine( body=[m.Assign(targets=[m.AssignTarget(target=m.Subscript(value=m.Name()) | m.Attribute(value=m.Name()))])] ) if m.matches(parent_node, m.Module()): if m.matches(node, m.SimpleStatementLine(body=[m.Import()])): self.imports.append(node) elif m.matches(node, m.SimpleStatementLine(body=[m.ImportFrom()])): import_module = self.python_module.code_for_node(node.body[0].module) import_statement = "." * len(node.body[0].relative) + import_module if not ( re.search(rf"(?:transformers\.models\.)|(?:\.\.)\w+\.({self.match_patterns})_.*", import_statement) and not any(import_to_skip in import_statement for import_to_skip in IMPORTS_TO_SKIP_IN_MODULAR) ): self.imports.append(node) elif m.matches(node, simple_top_level_assign_structure): assigned_variable = node.body[0].targets[0].target.value # __all__ is treated differently and not added to general assignments if assigned_variable == "__all__": self.all_all_to_add = split_all_assignment(node, self.model_name) else: self.current_assignment = assigned_variable self.assignments[assigned_variable] = node # This corresponds to a global variable being indexed or having an attribute look-up elif m.matches(node, simple_top_level_variable_indexing): indexed_variable = node.body[0].targets[0].target.value.value # We should follow any dependencies relative to the variable being indexed self.current_assignment = indexed_variable # The indexing node should be directly added as a dependency of the indexed variable (register the node with a "fake" name) node_name = self.python_module.code_for_node(node) self.assignments[node_name] = node self.object_dependency_mapping[indexed_variable].add(node_name) def leave_Module(self, node): """When we leave the modular file, we do the following in order: 1. for each modeling file found in the imports, rename it with the new model name, visit it, and update its dependency graph with the new function and assignment definitions found in the modular 2. update the modular dependency graph with the imported functions and assignments (found when visiting the matching files) 3. compute the nested (recursive) function and assignment dependencies """ # Takes care of finalizing our visit super().leave_Module(node) # 1. for each modeling file found in the imports, rename it with the new model name, visit it, and update dependencies self.visited_modules = {} self.renamers = {} name_prefixes = self.infer_new_model_name() for file, module in self.model_specific_modules.items(): file_model_name = file.split(".")[-2] new_name = name_prefixes[file] renamer = ReplaceNameTransformer(file_model_name, new_name, self.model_name) renamed_module = module.visit(renamer) self.visited_modules[file] = ModelFileMapper.visit_and_merge_dependencies( renamed_module, self.classes, self.functions, self.assignments, self.object_dependency_mapping, self.start_lines, ) # We record it so that we can rename classes later the exact same way self.renamers[file] = renamer # 2. in turn, we need to add the imported functions/assignments to the dependencies of the modular mapper, using the # definitions found in the visited files self.merge_model_specific_imports(self.visited_modules) # 3. compute the nested (recursive) function and assignment dependencies self.object_recursive_dependency_mapping = self._compute_recursive_object_dependencies() # We need to keep track of which objects were imported directly into which modeling file to not add them wrongly later # Note that we may visit several of the same file types, thus we save them per file type, not file self.imported_objects_per_file = defaultdict(set) for file, mapper in self.visited_modules.items(): file_type = re.search(rf"^transformers\.models\.\w+\.({self.match_patterns})_.*", file).group(1) self.imported_objects_per_file[file_type].update(mapper.objects_imported_from_modeling) def merge_model_specific_imports(self, visited_modules): """Merge the functions and assignments imported from the modeling files to the modular nodes and dependency graph, based on the visited files.""" self.start_lines_file_mapping = {} self.added_objects_file_mapping = {} for object_name, file in self.model_specific_imported_objects.items(): visited_module = visited_modules[file] self.start_lines_file_mapping[file] = visited_module.start_lines # Add functions and their dependencies if object_name in visited_module.functions and object_name not in self.functions: self.functions[object_name] = visited_module.functions[object_name] self.added_objects_file_mapping[object_name] = file dependencies = visited_module.object_dependency_mapping.get(object_name, None) if dependencies is not None: self.object_dependency_mapping[object_name] = dependencies for dep in dependencies: if dep not in self.global_nodes: self.added_objects_file_mapping[dep] = file self.functions[dep] = visited_module.global_nodes[dep] # Add/overwrite the imported functions to other visited modules as well, in case it is absent/different # in he modeling source file of the inherited class. See `examples/modular-tranformers/modular_switch_function.py` # and `examples/modular-tranformers/modular_add_function.py` for examples recursive_dependencies = visited_module.object_recursive_dependency_mapping.get(object_name, set()) node_recursive_dependencies_mapping = { dep: visited_module.global_nodes[dep] for dep in recursive_dependencies } for filename, module_mapper in self.visited_modules.items(): if filename != file: module_mapper.global_nodes[object_name] = visited_module.functions[object_name] if len(recursive_dependencies) > 0: module_mapper.object_recursive_dependency_mapping[object_name] = recursive_dependencies module_mapper.global_nodes.update(node_recursive_dependencies_mapping) # Add assignments and their dependencies elif object_name in visited_module.assignments and object_name not in self.assignments: self.assignments[object_name] = visited_module.assignments[object_name] self.added_objects_file_mapping[object_name] = file dependencies = visited_module.object_dependency_mapping.get(object_name, None) if dependencies is not None: self.object_dependency_mapping[object_name] = dependencies for dep in dependencies: if dep not in self.global_nodes: self.added_objects_file_mapping[dep] = file self.assignments[dep] = visited_module.global_nodes[dep] # Do not forget to re-assign all nodes after the merge self.global_nodes = {**self.assignments, **self.classes, **self.functions} # And restric dependencies to those nodes only self._restrict_dependencies_to_known_entities() def compute_relative_order(self, missing_dependencies: set) -> dict[str, int]: """Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that will be created based on the modular. """ relative_order = {} idx = 0 original_dependencies = [] other_files_dependencies = defaultdict(list) for dep in sorted(missing_dependencies): if dep in self.added_objects_file_mapping: file = self.added_objects_file_mapping[dep] other_files_dependencies[file].append(dep) else: original_dependencies.append(dep) # Sort all lists according to the order in their respective file all_dependencies = [] for file, dependencies in other_files_dependencies.items(): sorted_dependencies = sorted(dependencies, key=lambda x: self.start_lines_file_mapping[file][x]) all_dependencies += sorted_dependencies all_dependencies += sorted(original_dependencies, key=lambda x: self.start_lines[x]) # Add all original node first, then merged ones (one file at a time) for dep in all_dependencies: relative_order[dep] = idx idx += 1 return relative_order def infer_new_model_name(self) -> dict: """Infer whether we are using a model name prefix different from the usual model name as defined from the filename. This is useful e.g. when we define a new multi-modal model, and only the text part inherits from `LlamaModel`, so we have something like: ```python class NewModelNameTextDecoderLayer(LlamaDecoderLayer): pass ``` with the `Text` prefix added to the model name. However, in case of multiple prefix used, we raise a warning and use the most frequent prefix, to avoid parsing the same file multiple times and inconsistencies in the objects added from dependencies. If the new prefix collides with a prefix of another class in the file where we are importing from, then we also raise a warning, and use the default prefix (model name) to avoid collisions in dependencies. """ prefix_model_name_mapping = defaultdict(Counter) cased_default_name = get_cased_name(self.model_name) # Iterate over all new classes to get modeling super classes for class_name, class_node in self.classes.items(): modeling_bases = [ k.value.value for k in class_node.bases if k.value.value in self.model_specific_imported_objects ] if len(modeling_bases) > 1: raise ValueError( f"{class_name} was defined with more than 1 model-specific super class. This is unsupported. We found {(*modeling_bases,)}." ) if len(modeling_bases) == 1: filename = self.model_specific_imported_objects[modeling_bases[0]] cased_model_name = cased_default_name # the default name prefix suffix = common_partial_suffix(class_name, modeling_bases[0]) if len(suffix) > 0 and suffix[0].isupper(): cased_model_name = class_name.replace(suffix, "") # If both the old model and new model share the last part of their name, is detected as a common # suffix, but it should not be the case -> use the full name in this case if len(cased_model_name) < len(cased_default_name) and cased_default_name in class_name: cased_model_name = cased_default_name prefix_model_name_mapping[filename].update([cased_model_name]) # Check if we found multiple prefixes for some modeling files final_name_mapping = {} for file, prefixes_counter in prefix_model_name_mapping.items(): if len(prefixes_counter) > 1: _, total = prefixes_counter.most_common(1)[0] most_used_entities = [name for name, count in prefixes_counter.most_common() if count == total] # if the default name is in the pool of equally used prefixes, use it, otherwise last encountered final_name = cased_default_name if cased_default_name in most_used_entities else most_used_entities[-1] else: final_name = list(prefixes_counter)[0] # Check if the prefix can be used without collisions in the names old_cased_model_name = get_cased_name(file.split(".")[-2]) old_model_name_prefix = final_name.replace(cased_default_name, old_cased_model_name) # Raise adequate warning depending on the situation has_prefix_collision = f"\nclass {old_model_name_prefix}" in get_module_source_from_name(file) if final_name != cased_default_name and has_prefix_collision: if len(prefixes_counter) > 1: logger.warning( f"We detected multiple prefix names when inheriting from {file}: {(*set(prefixes_counter),)}. However, the " f"most used one, '{final_name}', is already present in the source file and will likely cause consistency " f"issues. For this reason we fallback to the default prefix '{cased_default_name}' when grabbing args " "and dependencies. Make sure to subclass the intermediate classes with the prefix you want (if different " f"from '{cased_default_name}') or use a single prefix in all the modular (best)." ) else: logger.warning( f"We detected the use of the new default prefix {final_name} when inheriting from {file}. However, it is " "already present in the source file and will likely cause consistency issues. For this reason we fallback " f"to the default prefix '{cased_default_name}' when grabbing args and dependencies. Make sure to subclass " f"the intermediate classes with the prefix you want (if different from '{cased_default_name}')" ) final_name = cased_default_name elif len(prefixes_counter) > 1: logger.warning( f"We detected multiple prefix names when inheriting from {file}: {(*set(prefixes_counter),)}. We will only " f"use the most used '{final_name}' prefix when grabbing args and dependencies. Make sure to subclass the " f"intermediate classes with the prefix you want (if different from '{final_name}') or use a single prefix " "in all the modular (best)." ) final_name_mapping[file] = get_lowercase_name(final_name) # Check we are not missing imported files for file in self.model_specific_modules: if file not in final_name_mapping: final_name_mapping[file] = self.model_name return final_name_mapping def check_dependencies_and_create_import_node( file_type: str, new_dependencies: set[str], mapper: ModuleMapper, new_name: str ) -> tuple[set[str], dict[str, cst.CSTNode]]: """Check that all class nodes in the `new_dependencies` belong to the correct `file_type`. If this is not the case, we need to remove it from the dependencies, and create a new import to it instead. This scenario may appear in the following case: If a new class in the `modular_xxx.py` file does not belong to `type_xxx.py`, but is used somewhere in `other_type_xxx.py` (e.g. as a type hint), but none of the visited files had a similar class, then it would be imported in `type_xxx.py` as part of the standard dependency graph (because we never encountered an import towards this new class in any file). For example imagine the following `modular.py`: ``` from ..llama.modeling_llama import LlamaModel class NewNameTextConfig(PretrainedConfig): ... class NewNameConfig(PretrainedConfig): ... class NewNameModel(LlamaModel): config = NewNameConfig() text_config = NewNameTextConfig() ... ``` then without the help of this function, `NewNameTextConfig` would be imported in the `modeling_newname.py` as well as `configuration_newname.py`, because `modeling_llama.py` tells us to not import `NewNameConfig`, but has no knowledge of `NewNameTextConfig`. """ class_dependencies = {dep for dep in new_dependencies if m.matches(mapper.global_nodes[dep], m.ClassDef())} corrected_dependencies = new_dependencies.copy() new_imports = {} for class_name in class_dependencies: class_file_type = find_file_type(class_name, new_name) # In this case, we need to remove it from the dependencies and create a new import instead if class_file_type != file_type: corrected_dependencies.remove(class_name) import_statement = f"from .{class_file_type}_{new_name} import {class_name}" new_imports[class_name] = cst.parse_statement(import_statement) return corrected_dependencies, new_imports def get_class_node_and_dependencies( modular_mapper: ModularFileMapper, class_name: str, node: cst.CSTNode, files: dict[str, dict] ) -> tuple[dict, str, dict]: """Return a single class node (and all its dependency nodes), to be added to the `files`. It creates the new class node based on the inherited classes if needed. Also returns any new imports of a new class defined in the modular that we nay need. """ # An exception was already raised if this has len > 1 model_specific_bases = [ k.value.value for k in node.bases if k.value.value in modular_mapper.model_specific_imported_objects ] super_class = model_specific_bases[0] if len(model_specific_bases) == 1 else None file_type = find_file_type(class_name, modular_mapper.model_name) file_to_update = files[file_type] model_name = modular_mapper.model_name # This is used to avoid adding objects to the dependencies graph if they will be imported already imported_objects = modular_mapper.imported_objects_per_file[file_type] # We need to replace the class node with the transformers (modeling file) super class node if super_class is not None: super_file_name = modular_mapper.model_specific_imported_objects[super_class] # Get the mapper corresponding to the inherited class mapper = modular_mapper.visited_modules[super_file_name] # Rename the super class according to the exact same rule we used when renaming the whole module renamer = modular_mapper.renamers[super_file_name] renamed_super_class = preserve_case_replace(super_class, renamer.patterns, renamer.cased_new_name) # Create the new class node updated_node = replace_class_node(mapper, node, renamed_super_class, super_class) # Grab all immediate dependencies of the new node new_node_dependencies = augmented_dependencies_for_class_node(updated_node, mapper, imported_objects) # At this point, if any class dependency is found, but belongs to another file, it means that we need to remove # it from the dependencies, and add a new import of it instead new_node_dependencies, new_imports = check_dependencies_and_create_import_node( file_type, new_node_dependencies, mapper, model_name ) # The node was modified -> look for all recursive dependencies of the new node all_dependencies_to_add = find_all_dependencies( dependency_mapping=mapper.class_dependency_mapping, initial_dependencies=new_node_dependencies, initial_checked_dependencies=set(file_to_update.keys()), ) relative_dependency_order = mapper.compute_relative_order(all_dependencies_to_add) nodes_to_add = { dep: (relative_dependency_order[dep], mapper.global_nodes[dep]) for dep in all_dependencies_to_add } # No transformers (modeling file) super class, just check functions and assignments dependencies else: updated_node = node # The node was NOT modified -> no need to look recursively for other class dependencies. Indeed, even if they are not # already defined (which would mean a weird order of the code in the modular...), they will be in the future all_dependencies_to_add = augmented_dependencies_for_class_node(updated_node, modular_mapper, imported_objects) # At this point, if any class dependency is found, but belongs to another file, it means that we need to remove # it from the dependencies, and add a new import of it instead all_dependencies_to_add, new_imports = check_dependencies_and_create_import_node( file_type, all_dependencies_to_add, modular_mapper, model_name ) relative_dependency_order = modular_mapper.compute_relative_order(all_dependencies_to_add) nodes_to_add = { dep: (relative_dependency_order[dep], modular_mapper.global_nodes[dep]) for dep in all_dependencies_to_add if dep not in file_to_update } # Add the class node itself to the nodes to add class_idx = max(relative_dependency_order.values()) + 1 if len(relative_dependency_order) > 0 else 0 nodes_to_add[class_name] = (class_idx, updated_node) return nodes_to_add, file_type, new_imports def create_modules(modular_mapper: ModularFileMapper) -> dict[str, cst.Module]: """Create all the new modules based on visiting the modular file. It replaces all classes as necessary.""" files = defaultdict(dict) current_file_indices = defaultdict(lambda: 0) # For each class defined in modular, potentially replace the node and add it with its dependencies for class_name, node in modular_mapper.classes.items(): nodes_to_add, file_type, new_imports = get_class_node_and_dependencies(modular_mapper, class_name, node, files) # Add the new potential new imports that we may need to the `modular_mapper` variable modular_mapper.imported_objects_per_file[file_type].update(new_imports.keys()) modular_mapper.imports.extend(list(new_imports.values())) # Sort the nodes according to their relative order nodes_to_add = sorted(nodes_to_add.items(), key=lambda x: x[1][0]) # Write all nodes to file for dependency, (_, node) in nodes_to_add: # This is used to keep certain variables at the beginning of the file try: # The -1000 is arbitrary -> just keep it bigger than the list idx = -1000 + VARIABLES_AT_THE_BEGINNING.index(dependency) except ValueError: idx = current_file_indices[file_type] current_file_indices[file_type] += 1 files[file_type][dependency] = {"insert_idx": idx, "node": node} # Add the __all__ statement to files at the end for file_type, node in modular_mapper.all_all_to_add.items(): idx = current_file_indices[file_type] files[file_type]["__all__"] = {"insert_idx": idx, "node": node} # Aggregate all the imports statements (we look for duplicates with the code_for_node, not the nodes themselves because # they are wrapped in SimpleStatementLine or If which could have different newlines, blanks etc) all_imports = modular_mapper.imports.copy() all_imports_code = {modular_mapper.python_module.code_for_node(node).strip() for node in all_imports} for file, mapper in modular_mapper.visited_modules.items(): new_imports = [ node for node in mapper.imports if mapper.python_module.code_for_node(node).strip() not in all_imports_code ] new_imports_code = {mapper.python_module.code_for_node(node).strip() for node in new_imports} all_imports.extend(new_imports) all_imports_code.update(new_imports_code) # Find the correct imports, and write the new modules for file, body in files.items(): new_body = [k[1]["node"] for k in sorted(body.items(), key=lambda x: x[1]["insert_idx"])] needed_imports = get_needed_imports(body, all_imports) full_module = needed_imports + new_body new_module = cst.Module(body=full_module, header=modular_mapper.python_module.header) files[file] = new_module return files def run_ruff(code, check=False): if check: command = ["ruff", "check", "-", "--fix", "--exit-zero"] else: command = ["ruff", "format", "-", "--config", "pyproject.toml", "--silent"] process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) stdout, _ = process.communicate(input=code.encode()) return stdout.decode() def convert_modular_file(modular_file): pattern = re.search(r"modular_(.*)(?=\.py$)", modular_file) output = {} if pattern is not None: model_name = pattern.groups()[0] # Parse the Python file with open(modular_file, "r", encoding="utf-8") as file: code = file.read() module = cst.parse_module(code) wrapper = MetadataWrapper(module) cst_transformers = ModularFileMapper(module, model_name) wrapper.visit(cst_transformers) for file, module in create_modules(cst_transformers).items(): if module != {}: # Get relative path starting from src/transformers/ relative_path = re.search( r"(src/transformers/.*|examples/.*)", os.path.abspath(modular_file).replace("\\", "/") ).group(1) header = AUTO_GENERATED_MESSAGE.format( relative_path=relative_path, short_name=os.path.basename(relative_path) ) ruffed_code = run_ruff(header + module.code, True) formatted_code = run_ruff(ruffed_code, False) output[file] = [formatted_code, ruffed_code] return output else: print(f"modular pattern not found in {modular_file}, exiting") return {} def save_modeling_file(modular_file, converted_file): for file_type in converted_file: file_name_prefix = file_type.split("*")[0] file_name_suffix = file_type.split("*")[-1] if "*" in file_type else "" new_file_name = modular_file.replace("modular_", f"{file_name_prefix}_").replace( ".py", f"{file_name_suffix}.py" ) non_comment_lines = len( [line for line in converted_file[file_type][0].strip().split("\n") if not line.strip().startswith("#")] ) if len(converted_file[file_type][0].strip()) > 0 and non_comment_lines > 0: with open(new_file_name, "w", encoding="utf-8") as f: f.write(converted_file[file_type][0]) else: non_comment_lines = len( [line for line in converted_file[file_type][0].strip().split("\n") if not line.strip().startswith("#")] ) if len(converted_file[file_type][1].strip()) > 0 and non_comment_lines > 0: logger.warning("The modeling code contains errors, it's written without formatting") with open(new_file_name, "w", encoding="utf-8") as f: f.write(converted_file[file_type][1]) if __name__ == "__main__": parser = argparse.ArgumentParser() # Same arg as both positional and optional, just for convenience parser.add_argument( "files", nargs="*", help="A list of `modular_xxxx` files that should be converted to single model file", ) parser.add_argument( "--files-to-parse", "--files_to_parse", "--files", "-f", default=["all"], nargs="+", help="A list of `modular_xxxx` files that should be converted to single model file", ) args = parser.parse_args() # Both arg represent the same data, but as positional and optional files_to_parse = args.files if len(args.files) > 0 else args.files_to_parse if files_to_parse == ["all"]: files_to_parse = glob.glob("src/transformers/models/**/modular_*.py", recursive=True) if files_to_parse == ["examples"]: files_to_parse = glob.glob("examples/**/modular_*.py", recursive=True) else: for i, model_name in enumerate(files_to_parse): if os.sep not in model_name: full_path = os.path.join("src", "transformers", "models", model_name, f"modular_{model_name}.py") # If it does not exist, try in the examples section if not os.path.isfile(full_path): full_path = os.path.join("examples", "modular-transformers", f"modular_{model_name}.py") # We did not find it anywhere if not os.path.isfile(full_path): raise ValueError(f"Cannot find a modular file for {model_name}. Please provide the full path.") files_to_parse[i] = full_path priority_list, _ = find_priority_list(files_to_parse) priority_list = [item for sublist in priority_list for item in sublist] # flatten the list of lists assert len(priority_list) == len(files_to_parse), "Some files will not be converted" for file_name in priority_list: print(f"Converting {file_name} to a single model single file format") module_path = file_name.replace("/", ".").replace(".py", "").replace("src.", "") converted_files = convert_modular_file(file_name) converter = save_modeling_file(file_name, converted_files)
transformers/utils/modular_model_converter.py/0
{ "file_path": "transformers/utils/modular_model_converter.py", "repo_id": "transformers", "token_count": 38248 }
576
# 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. """ This script is used to get the files against which we will run doc testing. This uses `tests_fetcher.get_all_doctest_files` then groups the test files by their directory paths. The files in `docs/source/en/model_doc` or `docs/source/en/tasks` are **NOT** grouped together with other files in the same directory: the objective is to run doctest against them in independent GitHub Actions jobs. Assume we are under `transformers` root directory: To get a map (dictionary) between directory (or file) paths and the corresponding files ```bash python utils/split_doctest_jobs.py ``` or to get a list of lists of directory (or file) paths ```bash python utils/split_doctest_jobs.py --only_return_keys --num_splits 4 ``` (this is used to allow GitHub Actions to generate more than 256 jobs using matrix) """ import argparse from collections import defaultdict from pathlib import Path from tests_fetcher import get_all_doctest_files if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--only_return_keys", action="store_true", help="if to only return the keys (which is a list of list of files' directory or file paths).", ) parser.add_argument( "--num_splits", type=int, default=1, help="the number of splits into which the (flat) list of directory/file paths will be split. This has effect only if `only_return_keys` is `True`.", ) args = parser.parse_args() all_doctest_files = get_all_doctest_files() raw_test_collection_map = defaultdict(list) for file in all_doctest_files: file_dir = "/".join(Path(file).parents[0].parts) # not to run files in `src/` for now as it is completely broken at this moment. See issues/39159 and # https://github.com/huggingface/transformers/actions/runs/15988670157 # TODO (ydshieh): fix the error, ideally before 2025/09 if file_dir.startswith("src/"): continue raw_test_collection_map[file_dir].append(file) refined_test_collection_map = {} for file_dir in raw_test_collection_map: if file_dir in ["docs/source/en/model_doc", "docs/source/en/tasks"]: for file in raw_test_collection_map[file_dir]: refined_test_collection_map[file] = file else: refined_test_collection_map[file_dir] = " ".join(sorted(raw_test_collection_map[file_dir])) sorted_file_dirs = sorted(refined_test_collection_map.keys()) test_collection_map = {} for file_dir in sorted_file_dirs: test_collection_map[file_dir] = refined_test_collection_map[file_dir] num_jobs = len(test_collection_map) num_jobs_per_splits = num_jobs // args.num_splits file_directory_splits = [] end = 0 for idx in range(args.num_splits): start = end end = start + num_jobs_per_splits + (1 if idx < num_jobs % args.num_splits else 0) file_directory_splits.append(sorted_file_dirs[start:end]) if args.only_return_keys: print(file_directory_splits) else: print(dict(test_collection_map))
transformers/utils/split_doctest_jobs.py/0
{ "file_path": "transformers/utils/split_doctest_jobs.py", "repo_id": "transformers", "token_count": 1330 }
577
# Iterative Trainer [![](https://img.shields.io/badge/All_models-Iterative_SFT-blue)](https://huggingface.co/models?other=iterative-sft,trl) <Tip warning={true}> The IterativeSFTTrainer is deprecated and will be removed in version 0.24.0. Please use the [`SFTTrainer`]. </Tip> Iterative fine-tuning is a training method that enables to perform custom actions (generation and filtering for example) between optimization steps. In TRL we provide an easy-to-use API to fine-tune your models in an iterative way in just a few lines of code. ## Quickstart To get started quickly, you can either pass a model identifier or a pre-instantiated model to the trainer: ```python from trl import IterativeSFTConfig, IterativeSFTTrainer # Using a model identifier trainer = IterativeSFTTrainer( "facebook/opt-350m", args=IterativeSFTConfig( max_length=512, output_dir="./output", ), ) # Or using a pre-instantiated model from transformers import AutoModelForCausalLM, AutoTokenizer model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m") tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") trainer = IterativeSFTTrainer( model, args=IterativeSFTConfig( max_length=512, output_dir="./output", ), processing_class=tokenizer, ) ``` ## Usage The [`IterativeSFTTrainer`] supports two ways of providing input data to the `step` function: ### Using a list of tensors as input: ```python inputs = { "input_ids": input_ids, "attention_mask": attention_mask, } trainer.step(**inputs) ``` ### Using a list of strings as input: ```python inputs = { "texts": texts, "texts_labels": texts_labels, # Optional, defaults to texts } trainer.step(**inputs) ``` For causal language models, labels will automatically be created from `input_ids` or from `texts`. When using sequence to sequence models you will have to provide your own labels or `text_labels`. ## Configuration The [`IterativeSFTConfig`] class provides several parameters to customize the training: ```python from trl import IterativeSFTConfig config = IterativeSFTConfig( # Model initialization parameters model_init_kwargs={"torch_dtype": "bfloat16"}, # Data preprocessing parameters max_length=512, truncation_mode="keep_end", # Training parameters output_dir="./output", learning_rate=2e-5, per_device_train_batch_size=4, gradient_accumulation_steps=4, max_steps=1000, save_steps=100, optim="adamw_torch", report_to="wandb", ) ``` ### Model Initialization You can control how the model is initialized by passing keyword arguments to `model_init_kwargs`: ```python config = IterativeSFTConfig( model_init_kwargs={ "torch_dtype": "bfloat16", "device_map": "auto", "trust_remote_code": True, } ) ``` ### Data Preprocessing The trainer supports two truncation modes: - `keep_end`: Truncates from the start of the sequence - `keep_start`: Truncates from the end of the sequence ```python config = IterativeSFTConfig( max_length=512, truncation_mode="keep_end", # or "keep_start" ) ``` ### Training Optimization You can optimize CUDA cache usage for more memory-efficient training: ```python config = IterativeSFTConfig( optimize_device_cache=True, ) ``` ## IterativeSFTTrainer [[autodoc]] IterativeSFTTrainer - train - save_model - push_to_hub ## IterativeSFTConfig [[autodoc]] IterativeSFTConfig
trl/docs/source/iterative_sft_trainer.md/0
{ "file_path": "trl/docs/source/iterative_sft_trainer.md", "repo_id": "trl", "token_count": 1223 }
578
# Quickstart TRL is a comprehensive library for post-training foundation models using techniques like Supervised Fine-Tuning (SFT), Group Relative Policy Optimization (GRPO), Direct Preference Optimization (DPO). ## Quick Examples Get started instantly with TRL's most popular trainers. Each example uses compact models for quick experimentation. ### Supervised Fine-Tuning ```python from trl import SFTTrainer from datasets import load_dataset trainer = SFTTrainer( model="Qwen/Qwen2.5-0.5B", train_dataset=load_dataset("trl-lib/Capybara", split="train"), ) trainer.train() ``` ### Group Relative Policy Optimization ```python from trl import GRPOTrainer from datasets import load_dataset # Define a simple reward function (count unique chars as example) def reward_function(completions, **kwargs): return [len(set(completion.lower())) for completion in completions] trainer = GRPOTrainer( model="Qwen/Qwen2.5-0.5B-Instruct", # Start from SFT model train_dataset=load_dataset("trl-lib/tldr", split="train"), reward_function=reward_function, ) trainer.train() ``` ### Direct Preference Optimization ```python from trl import DPOTrainer from datasets import load_dataset trainer = DPOTrainer( model="Qwen/Qwen2.5-0.5B-Instruct", # Use your SFT model ref_model="Qwen/Qwen2.5-0.5B-Instruct", # Original base model train_dataset=load_dataset("trl-lib/ultrafeedback_binarized", split="train"), ) trainer.train() ``` ## Command Line Interface Skip the code entirely - train directly from your terminal: ```bash # SFT: Fine-tune on instructions trl sft --model_name_or_path Qwen/Qwen2.5-0.5B \ --dataset_name trl-lib/Capybara # DPO: Align with preferences trl dpo --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ --dataset_name trl-lib/ultrafeedback_binarized ``` ## What's Next? ### 📚 Learn More - [SFT Trainer](https://huggingface.co/docs/trl/sft_trainer) - Complete SFT guide - [DPO Trainer](https://huggingface.co/docs/trl/dpo_trainer) - Preference alignment - [GRPO Trainer](https://huggingface.co/docs/trl/grpo_trainer) - Group relative policy optimization - [Training FAQ](https://huggingface.co/docs/trl/how_to_train) - Common questions ### 🚀 Scale Up - [Distributed Training](https://huggingface.co/docs/trl/distributing_training) - Multi-GPU setups - [Memory Optimization](https://huggingface.co/docs/trl/reducing_memory_usage) - Efficient training - [PEFT Integration](https://huggingface.co/docs/trl/peft_integration) - LoRA and QLoRA ### 💡 Examples - [Example Scripts](https://github.com/huggingface/trl/tree/main/examples) - Production-ready code - [Community Tutorials](https://huggingface.co/docs/trl/community_tutorials) - External guides ## Troubleshooting ### Out of Memory? Reduce batch size and enable optimizations: <hfoptions id="batch_size"> <hfoption id="SFT"> ```python training_args = SFTConfig( per_device_train_batch_size=1, # Start small gradient_accumulation_steps=8, # Maintain effective batch size ) ``` </hfoption> <hfoption id="DPO"> ```python training_args = DPOConfig( per_device_train_batch_size=1, # Start small gradient_accumulation_steps=8, # Maintain effective batch size ) ``` </hfoption> </hfoptions> ### Loss not decreasing? Try adjusting the learning rate: ```python training_args = SFTConfig(learning_rate=2e-5) # Good starting point ``` For more help, see our [Training FAQ](how_to_train.md) or open an [issue on GitHub](https://github.com/huggingface/trl/issues).
trl/docs/source/quickstart.md/0
{ "file_path": "trl/docs/source/quickstart.md", "repo_id": "trl", "token_count": 1235 }
579
# Copyright 2020-2025 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 dataclasses import dataclass, field from typing import Optional from datasets import load_dataset from huggingface_hub import ModelCard from transformers import HfArgumentParser @dataclass class ScriptArguments: r""" Arguments for the script. Args: push_to_hub (`bool`, *optional*, defaults to `False`): Whether to push the dataset to the Hugging Face Hub. repo_id (`str`, *optional*, defaults to `"trl-lib/ultrafeedback-prompt"`): Hugging Face repository ID to push the dataset to. dataset_num_proc (`int` or `None`, *optional*, defaults to `None`): Number of workers to use for dataset processing. """ push_to_hub: bool = field( default=False, metadata={"help": "Whether to push the dataset to the Hugging Face Hub."}, ) repo_id: str = field( default="trl-lib/ultrafeedback-prompt", metadata={"help": "Hugging Face repository ID to push the dataset to."}, ) dataset_num_proc: Optional[int] = field( default=None, metadata={"help": "Number of workers to use for dataset processing."}, ) def to_unpaired_preference(example): prompt = [{"role": "user", "content": example["instruction"]}] return {"prompt": prompt} def drop_long_prompt(example): if len(example["prompt"][0]["content"]) > 512: return False else: return True model_card = ModelCard(""" --- tags: [trl] --- # UltraFeedback - Prompts Dataset ## Summary The UltraFeedback - Prompts dataset is a processed version of the [UltraFeedback](https://huggingface.co/datasets/openbmb/UltraFeedback) dataset for model evaluation on specific aspects like helpfulness, honesty, and instruction-following. ## Data Structure - **Format**: [Conversational](https://huggingface.co/docs/trl/main/dataset_formats#conversational) - **Type**: [Prompt-only](https://huggingface.co/docs/trl/main/dataset_formats#prompt-only) Column: - `"prompt"`: The input question or instruction provided to the model. ## Generation script The script used to generate this dataset can be found [here](https://github.com/huggingface/trl/blob/main/examples/datasets/ultrafeedback-prompt.py). """) if __name__ == "__main__": parser = HfArgumentParser(ScriptArguments) script_args = parser.parse_args_into_dataclasses()[0] dataset = load_dataset("openbmb/UltraFeedback", split="train") dataset = dataset.map( to_unpaired_preference, remove_columns=["source", "instruction", "models", "completions", "correct_answers", "incorrect_answers"], num_proc=script_args.dataset_num_proc, ) dataset = dataset.filter(drop_long_prompt) dataset = dataset.train_test_split(test_size=0.05, seed=42) if script_args.push_to_hub: dataset.push_to_hub(script_args.repo_id) model_card.push_to_hub(script_args.repo_id, repo_type="dataset")
trl/examples/datasets/ultrafeedback-prompt.py/0
{ "file_path": "trl/examples/datasets/ultrafeedback-prompt.py", "repo_id": "trl", "token_count": 1246 }
580
# Copyright 2020-2025 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 argparse import os from accelerate import Accelerator from datasets import load_dataset from peft import LoraConfig from tqdm import tqdm from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, logging, set_seed from trl import SFTTrainer from trl.trainer import ConstantLengthDataset """ Fine-Tune Llama-7b on SE paired dataset """ def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--model_path", type=str, default="") parser.add_argument("--dataset_name", type=str, default="lvwerra/stack-exchange-paired") parser.add_argument("--subset", type=str, default="data/finetune") parser.add_argument("--split", type=str, default="train") parser.add_argument("--size_valid_set", type=int, default=4000) parser.add_argument("--streaming", action="store_true") parser.add_argument("--shuffle_buffer", type=int, default=5000) parser.add_argument("--seq_length", type=int, default=1024) parser.add_argument("--max_steps", type=int, default=10000) parser.add_argument("--batch_size", type=int, default=4) parser.add_argument("--gradient_accumulation_steps", type=int, default=1) parser.add_argument("--eos_token_id", type=int, default=49152) parser.add_argument("--learning_rate", type=float, default=1e-4) parser.add_argument("--lr_scheduler_type", type=str, default="cosine") parser.add_argument("--num_warmup_steps", type=int, default=100) parser.add_argument("--weight_decay", type=float, default=0.05) parser.add_argument("--local_rank", type=int, default=0) parser.add_argument("--fp16", action="store_true", default=False) parser.add_argument("--bf16", action="store_true", default=False) parser.add_argument("--gradient_checkpointing", action="store_true", default=False) parser.add_argument("--seed", type=int, default=0) parser.add_argument("--num_workers", type=int, default=None) parser.add_argument("--output_dir", type=str, default="./checkpoints") parser.add_argument("--log_freq", default=1, type=int) parser.add_argument("--eval_freq", default=1000, type=int) parser.add_argument("--save_freq", default=1000, type=int) return parser.parse_args() def chars_token_ratio(dataset, tokenizer, nb_examples=400): """ Estimate the average number of characters per token in the dataset. """ total_characters, total_tokens = 0, 0 for _, example in tqdm(zip(range(nb_examples), iter(dataset)), total=nb_examples): text = prepare_sample_text(example) total_characters += len(text) if tokenizer.is_fast: total_tokens += len(tokenizer(text).tokens()) else: total_tokens += len(tokenizer.tokenize(text)) return total_characters / total_tokens def print_trainable_parameters(model): """ Prints the number of trainable parameters in the model. """ trainable_params = 0 all_param = 0 for _, param in model.named_parameters(): all_param += param.numel() if param.requires_grad: trainable_params += param.numel() print( f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}" ) def prepare_sample_text(example): """Prepare the text from a sample of the dataset.""" text = f"Question: {example['question']}\n\nAnswer: {example['response_j']}" return text def create_datasets(tokenizer, args): dataset = load_dataset( args.dataset_name, data_dir=args.subset, split=args.split, use_auth_token=True, num_proc=args.num_workers if not args.streaming else None, streaming=args.streaming, ) if args.streaming: print("Loading the dataset in streaming mode") valid_data = dataset.take(args.size_valid_set) train_data = dataset.skip(args.size_valid_set) train_data = train_data.shuffle(buffer_size=args.shuffle_buffer, seed=args.seed) else: dataset = dataset.train_test_split(test_size=0.005, seed=args.seed) train_data = dataset["train"] valid_data = dataset["test"] print(f"Size of the train set: {len(train_data)}. Size of the validation set: {len(valid_data)}") chars_per_token = chars_token_ratio(train_data, tokenizer) print(f"The character to token ratio of the dataset is: {chars_per_token:.2f}") train_dataset = ConstantLengthDataset( tokenizer, train_data, formatting_func=prepare_sample_text, infinite=True, seq_length=args.seq_length, chars_per_token=chars_per_token, ) valid_dataset = ConstantLengthDataset( tokenizer, valid_data, formatting_func=prepare_sample_text, infinite=False, seq_length=args.seq_length, chars_per_token=chars_per_token, ) return train_dataset, valid_dataset def run_training(args, train_data, val_data): print("Loading the model") lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) train_data.start_iteration = 0 print("Starting main loop") training_args = TrainingArguments( output_dir=args.output_dir, dataloader_drop_last=True, eval_strategy="steps", max_steps=args.max_steps, eval_steps=args.eval_freq, save_steps=args.save_freq, logging_steps=args.log_freq, per_device_train_batch_size=args.batch_size, per_device_eval_batch_size=args.batch_size, learning_rate=args.learning_rate, lr_scheduler_type=args.lr_scheduler_type, warmup_steps=args.num_warmup_steps, gradient_accumulation_steps=args.gradient_accumulation_steps, gradient_checkpointing=args.gradient_checkpointing, fp16=args.fp16, bf16=args.bf16, weight_decay=args.weight_decay, run_name="llama-7b-finetuned", report_to="wandb", ddp_find_unused_parameters=False, ) model = AutoModelForCausalLM.from_pretrained( args.model_path, load_in_8bit=True, device_map={"": Accelerator().process_index} ) trainer = SFTTrainer( model=model, args=training_args, train_dataset=train_data, eval_dataset=val_data, peft_config=lora_config, packing=True, ) print_trainable_parameters(trainer.model) print("Training...") trainer.train() print("Saving last checkpoint of the model") trainer.model.save_pretrained(os.path.join(args.output_dir, "final_checkpoint/")) def main(args): tokenizer = AutoTokenizer.from_pretrained(args.model_path) train_dataset, eval_dataset = create_datasets(tokenizer, args) run_training(args, train_dataset, eval_dataset) if __name__ == "__main__": args = get_args() assert args.model_path != "", "Please provide the llama model path" set_seed(args.seed) os.makedirs(args.output_dir, exist_ok=True) logging.set_verbosity_error() main(args)
trl/examples/research_projects/stack_llama/scripts/supervised_finetuning.py/0
{ "file_path": "trl/examples/research_projects/stack_llama/scripts/supervised_finetuning.py", "repo_id": "trl", "token_count": 3068 }
581
# Copyright 2020-2025 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. # /// script # dependencies = [ # "trl @ git+https://github.com/huggingface/trl.git", # "peft", # ] # /// """ # Full training: python examples/scripts/gkd.py \ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \ --dataset_name trl-lib/chatbot_arena_completions \ --learning_rate 2e-5 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --output_dir gkd-model \ --num_train_epochs 1 \ --push_to_hub \ --gradient_checkpointing # LoRA: python examples/scripts/gkd.py \ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \ --dataset_name trl-lib/chatbot_arena_completions \ --learning_rate 2e-4 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --output_dir gkd-model \ --num_train_epochs 1 \ --push_to_hub \ --gradient_checkpointing \ --use_peft \ --lora_r 64 \ --lora_alpha 16 """ from datasets import load_dataset from transformers import AutoTokenizer, GenerationConfig from trl import ( GKDConfig, GKDTrainer, LogCompletionsCallback, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config, ) if __name__ == "__main__": parser = TrlParser((ScriptArguments, GKDConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config() ################ # Model & Tokenizer ################ quantization_config = get_quantization_config(model_args) model_kwargs = dict( revision=model_args.model_revision, trust_remote_code=model_args.trust_remote_code, attn_implementation=model_args.attn_implementation, torch_dtype=model_args.torch_dtype, use_cache=False if training_args.gradient_checkpointing else True, device_map=get_kbit_device_map() if quantization_config is not None else None, quantization_config=quantization_config, ) training_args.model_init_kwargs = model_kwargs teacher_model_kwargs = dict( revision=model_args.model_revision, trust_remote_code=model_args.trust_remote_code, attn_implementation=model_args.attn_implementation, torch_dtype=model_args.torch_dtype, use_cache=True, device_map=get_kbit_device_map() if quantization_config is not None else None, quantization_config=quantization_config, ) training_args.teacher_model_init_kwargs = teacher_model_kwargs tokenizer = AutoTokenizer.from_pretrained( model_args.model_name_or_path, revision=model_args.model_revision, trust_remote_code=model_args.trust_remote_code, padding_side="left", ) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token ################ # Dataset ################ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config) ################ # Training ################ trainer = GKDTrainer( model=model_args.model_name_or_path, teacher_model=training_args.teacher_model_name_or_path, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, processing_class=tokenizer, peft_config=get_peft_config(model_args), ) if training_args.eval_strategy != "no": generation_config = GenerationConfig( max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature ) completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8) trainer.add_callback(completions_callback) trainer.train() # Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)
trl/examples/scripts/gkd.py/0
{ "file_path": "trl/examples/scripts/gkd.py", "repo_id": "trl", "token_count": 1879 }
582
[metadata] name = trl version = 0.22.0.dev0 description = Train transformer language models with reinforcement learning. long_description = file: README.md long_description_content_type = text/markdown author = Leandro von Werra author_email = leandro.vonwerra@gmail.com url = https://github.com/huggingface/trl keywords = transformers, huggingface, language modeling, post-training, rlhf, sft, dpo, grpo license_file = LICENSE classifiers = Development Status :: 2 - Pre-Alpha Intended Audience :: Developers Intended Audience :: Science/Research Natural Language :: English Operating System :: OS Independent Programming Language :: Python :: 3 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 Programming Language :: Python :: 3.12 Programming Language :: Python :: 3.13 [options] packages = find_namespace: python_requires = >=3.9 include_package_data = True install_requires = accelerate>=1.4.0 datasets>=3.0.0 transformers>=4.55.0 [options.packages.find] exclude = tests* [options.extras_require] bco = scikit-learn joblib deepspeed = deepspeed>=0.14.4 diffusers = diffusers>=0.18.0 ftfy judges = openai>=1.23.2 llm-blender>=0.0.2 liger = liger-kernel>=0.5.9 peft = peft>=0.8.0 quantization = bitsandbytes scikit = scikit-learn test = parameterized pytest-cov pytest-rerunfailures pytest-xdist pytest vllm = # vLLM package does not yet support Python 3.13. These constraints can be lifted once support is added: # see https://github.com/vllm-project/vllm/pull/13164 vllm>=0.10.0; python_version < "3.13" fastapi; python_version < "3.13" pydantic; python_version < "3.13" requests; python_version < "3.13" uvicorn; python_version < "3.13" vlm = Pillow torchvision num2words dev = %(bco)s %(deepspeed)s %(diffusers)s %(judges)s %(liger)s %(peft)s %(quantization)s %(scikit)s %(test)s %(vlm)s [options.entry_points] console_scripts = trl = trl.cli:main [coverage:run] branch = True
trl/setup.cfg/0
{ "file_path": "trl/setup.cfg", "repo_id": "trl", "token_count": 866 }
583
# Copyright 2020-2025 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 torch from trl.trainer.dpo_trainer import DataCollatorForPreference from .testing_utils import TrlTestCase class TestDataCollatorForPreference(TrlTestCase): def setUp(self): super().setUp() self.collator = DataCollatorForPreference(pad_token_id=0) def assertTensorEqual(self, tensor1, tensor2): self.assertTrue(torch.equal(tensor1, tensor2), f"Tensors are not equal:\n{tensor1}\n{tensor2}") def test_padding_behavior(self): examples = [ {"prompt_input_ids": [1, 2, 3], "chosen_input_ids": [4, 5], "rejected_input_ids": [6]}, {"prompt_input_ids": [7, 8], "chosen_input_ids": [9, 10], "rejected_input_ids": [11, 12, 13]}, ] output = self.collator.torch_call(examples) expected_prompt_input_ids = torch.tensor([[1, 2, 3], [0, 7, 8]]) expected_prompt_attention_mask = torch.tensor([[1, 1, 1], [0, 1, 1]]) expected_chosen_input_ids = torch.tensor([[4, 5], [9, 10]]) expected_chosen_attention_mask = torch.tensor([[1, 1], [1, 1]]) expected_rejected_input_ids = torch.tensor([[6, 0, 0], [11, 12, 13]]) expected_rejected_attention_mask = torch.tensor([[1, 0, 0], [1, 1, 1]]) self.assertTensorEqual(output["prompt_input_ids"], expected_prompt_input_ids) self.assertTensorEqual(output["prompt_attention_mask"], expected_prompt_attention_mask) self.assertTensorEqual(output["chosen_input_ids"], expected_chosen_input_ids) self.assertTensorEqual(output["chosen_attention_mask"], expected_chosen_attention_mask) self.assertTensorEqual(output["rejected_input_ids"], expected_rejected_input_ids) self.assertTensorEqual(output["rejected_attention_mask"], expected_rejected_attention_mask) def test_optional_fields(self): examples = [ { "prompt_input_ids": [1], "chosen_input_ids": [2], "rejected_input_ids": [3], "pixel_values": [[[0.1, 0.2], [0.3, 0.4]]], # Example 3D tensor (1x2x2) }, { "prompt_input_ids": [4], "chosen_input_ids": [5], "rejected_input_ids": [6], "pixel_values": [[[0.5, 0.6], [0.7, 0.8]]], # Example 3D tensor (1x2x2) }, ] output = self.collator.torch_call(examples) expected_pixel_values = torch.tensor( [ [[[0.1, 0.2], [0.3, 0.4]]], [[[0.5, 0.6], [0.7, 0.8]]], ] ) # Shape: (2, 1, 2, 2) self.assertTensorEqual(output["pixel_values"], expected_pixel_values)
trl/tests/test_collators.py/0
{ "file_path": "trl/tests/test_collators.py", "repo_id": "trl", "token_count": 1468 }
584
# Copyright 2020-2025 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 torch from datasets import load_dataset from parameterized import parameterized from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer from transformers.testing_utils import require_peft from trl import ORPOConfig, ORPOTrainer from trl.trainer.utils import SIMPLE_CHAT_TEMPLATE from .testing_utils import TrlTestCase class ORPOTrainerTester(TrlTestCase): def setUp(self): super().setUp() self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" self.model = AutoModelForCausalLM.from_pretrained(self.model_id) self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) self.tokenizer.pad_token = self.tokenizer.eos_token # get t5 as seq2seq example: model_id = "trl-internal-testing/tiny-T5ForConditionalGeneration" self.t5_model = AutoModelForSeq2SeqLM.from_pretrained(model_id) self.t5_tokenizer = AutoTokenizer.from_pretrained(model_id) self.t5_tokenizer.chat_template = SIMPLE_CHAT_TEMPLATE @parameterized.expand( [ ("qwen", "standard_preference"), ("t5", "standard_implicit_prompt_preference"), ("qwen", "conversational_preference"), ("t5", "conversational_implicit_prompt_preference"), ] ) def test_orpo_trainer(self, name, config_name): training_args = ORPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=1, learning_rate=9e-1, eval_strategy="steps", beta=0.1, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) if name == "qwen": model = self.model tokenizer = self.tokenizer elif name == "t5": model = self.t5_model tokenizer = self.t5_tokenizer training_args.is_encoder_decoder = True trainer = ORPOTrainer( model=model, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.equal(param, new_param)) @parameterized.expand( [ ("standard_preference",), ("standard_implicit_prompt_preference",), ("conversational_preference",), ("conversational_implicit_prompt_preference",), ] ) @require_peft def test_orpo_trainer_with_lora(self, config_name): from peft import LoraConfig lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) training_args = ORPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", beta=0.1, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) trainer = ORPOTrainer( model=self.model, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], peft_config=lora_config, ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): if "lora" in n: new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.equal(param, new_param)) def test_compute_metrics(self): model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") tokenizer.pad_token = tokenizer.eos_token dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") def dummy_compute_metrics(*args, **kwargs): return {"test": 0.0} training_args = ORPOConfig( output_dir=self.tmp_dir, remove_unused_columns=False, per_device_train_batch_size=2, do_eval=True, eval_strategy="steps", eval_steps=1, per_device_eval_batch_size=2, report_to="none", ) trainer = ORPOTrainer( model=model, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], compute_metrics=dummy_compute_metrics, ) trainer.train() self.assertEqual(trainer.state.log_history[-2]["eval_test"], 0.0)
trl/tests/test_orpo_trainer.py/0
{ "file_path": "trl/tests/test_orpo_trainer.py", "repo_id": "trl", "token_count": 2951 }
585
compute_environment: LOCAL_MACHINE debug: false distributed_type: FSDP downcast_bf16: 'no' enable_cpu_affinity: false fsdp_config: fsdp_activation_checkpointing: false fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP fsdp_backward_prefetch: BACKWARD_PRE fsdp_cpu_ram_efficient_loading: true fsdp_forward_prefetch: true fsdp_offload_params: false fsdp_reshard_after_forward: FULL_SHARD fsdp_state_dict_type: FULL_STATE_DICT fsdp_sync_module_states: true fsdp_use_orig_params: true fsdp_version: 1 machine_rank: 0 main_training_function: main mixed_precision: bf16 num_machines: 1 num_processes: 8 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false
trl/trl/accelerate_configs/fsdp1.yaml/0
{ "file_path": "trl/trl/accelerate_configs/fsdp1.yaml", "repo_id": "trl", "token_count": 296 }
586
# Copyright 2020-2025 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 torch from huggingface_hub import HfApi from trl.import_utils import is_mergekit_available if is_mergekit_available(): from mergekit.config import MergeConfiguration from mergekit.merge import MergeOptions, run_merge def upload_model_to_hf(folder_path: str, repo_id: str): api = HfApi() # Create the repository if it doesn't exist repo = api.create_repo(repo_id, repo_type="model") # Upload the folder to the specified repository api.upload_folder( folder_path=folder_path, repo_id=repo.repo_id, repo_type=repo.repo_type, ) class MergeConfig: r""" Configuration class for merging two models using `mergekit`. This class provides a structured way to configure and generate merge configurations for various merge methods, such as `linear`, `ties`, `dare_ties`, and `slerp`. Args: method (`str`, *optional*, defaults to `"linear"`): Merge method to use. Supported methods include: - `"linear"`: Linearly combines two models with specified weights. - `"ties"`: Combines two models using the TIES method with density parameters. - `"dare_ties"`: A variant of TIES for domain adaptation. - `"slerp"`: Combines models using spherical linear interpolation. Note: For more details about the merge methods and how they are implemented, see the [MergeKit GitHub repository](https://github.com/arcee-ai/mergekit?tab=readme-ov-file#merge-methods). Attributes: method (`str`): The merge method to use. policy_model_path (`str` or `None`): Path to the policy model. target_model_path (`str` or `None`): Path to the target model. policy_model_weight (`float`): Weight for the policy model (for `linear` and `ties` methods). target_model_weight (`float`): Weight for the target model (for `linear` and `ties` methods). policy_model_density (`list[float]`): Density parameters for the policy model (for `ties` and `dare_ties`). target_model_density (`list[float]`): Density parameters for the target model (for `ties` and `dare_ties`). normalize (`float` or `None`): Normalization factor for the TIES method. t_values (`float` or `None`): Interpolation factor for the SLERP method. dtype (`str`): Data type to use for merging, e.g., `"float16"`. """ def __init__(self, method: str = "linear"): if not is_mergekit_available(): raise ImportError("MergeConfig requires the `mergekit` extra. To install, run `pip install mergekit`.") self.method = method self.policy_model_path = None self.target_model_path = None # Initialize relevant parameters based on the method if method == "linear": self.policy_model_weight = 0.5 self.target_model_weight = 0.5 self.dtype = "float16" elif method == "ties": self.policy_model_weight = 1.0 self.policy_model_density = [1.0, 0.7, 0.1] self.target_model_weight = 1.0 self.target_model_density = [1.0] self.normalize = 1.0 self.dtype = "float16" elif method == "dare_ties": self.policy_model_weight = 1.0 self.policy_model_density = [1.0, 0.7, 0.1] self.target_model_weight = 1.0 self.target_model_density = [1.0] self.normalize = 1.0 self.dtype = "float16" elif method == "slerp": self.t_values = 0.5 self.dtype = "float16" else: raise ValueError(f"Unsupported merge method: {method}") def create_merge_config_linear(self) -> "MergeConfiguration": """ Creates a merge configuration for a linear merge of two models with specified weights. """ # Create the merge configuration dictionary merge_config_dict = { "dtype": self.dtype, "merge_method": "linear", "models": [ {"model": self.policy_model_path, "parameters": {"weight": self.policy_model_weight}}, {"model": self.target_model_path, "parameters": {"weight": self.target_model_weight}}, ], } # Create the MergeConfiguration from the dictionary merge_config = MergeConfiguration.model_validate(merge_config_dict) return merge_config def create_merge_config_ties(self) -> "MergeConfiguration": """ Creates a merge configuration for a TIES merge of two models, with specified weights and densities. """ # Create the TIES merge configuration dictionary merge_config_dict = { "merge_method": "ties", "slices": None, # Optional slices if needed "models": [ { "model": { "model": {"path": self.target_model_path, "revision": None}, "lora": None, "override_architecture": None, }, "parameters": {"density": self.target_model_density, "weight": self.target_model_weight}, }, { "model": { "model": {"path": self.policy_model_path, "revision": None}, "lora": None, "override_architecture": None, }, "parameters": {"density": self.policy_model_density, "weight": self.policy_model_weight}, }, ], "parameters": {"normalize": self.normalize}, "base_model": { "model": {"path": self.policy_model_path, "revision": None}, "lora": None, "override_architecture": None, }, "dtype": self.dtype, "tokenizer_source": None, "tokenizer": None, "chat_template": None, "out_dtype": None, } # Create the MergeConfiguration from the dictionary merge_config = MergeConfiguration.model_validate(merge_config_dict) return merge_config def create_merge_config_dare_ties(self) -> "MergeConfiguration": """ Creates a merge configuration for a DARE TIES merge of two models, with specified weights and densities. """ # Create the DARE TIES merge configuration dictionary merge_config_dict = { "merge_method": "dare_ties", "slices": None, # Optional slices if needed "models": [ { "model": { "model": {"path": self.target_model_path, "revision": None}, "lora": None, "override_architecture": None, }, "parameters": {"density": self.target_model_density, "weight": self.target_model_weight}, }, { "model": { "model": {"path": self.policy_model_path, "revision": None}, "lora": None, "override_architecture": None, }, "parameters": {"density": self.policy_model_density, "weight": self.policy_model_weight}, }, ], "parameters": {"normalize": self.normalize}, "base_model": { "model": {"path": self.policy_model_path, "revision": None}, "lora": None, "override_architecture": None, }, "dtype": self.dtype, "tokenizer_source": None, "tokenizer": None, "chat_template": None, "out_dtype": None, } # Create the MergeConfiguration from the dictionary merge_config = MergeConfiguration.model_validate(merge_config_dict) return merge_config def create_merge_config_slerp(self) -> "MergeConfiguration": """ Creates a merge configuration for a SLERP merge of a model with a base model. """ # Create the SLERP merge configuration dictionary merge_config_dict = { "merge_method": "slerp", "slices": None, # Optional slices if needed "models": [ { "model": { "model": {"path": self.target_model_path, "revision": None}, "lora": None, "override_architecture": None, }, "parameters": None, # No specific parameters for SLERP model } ], "parameters": { "t": self.t_values # Set the t values for SLERP }, "base_model": { "model": {"path": self.policy_model_path, "revision": None}, "lora": None, "override_architecture": None, }, "dtype": self.dtype, "tokenizer_source": None, "tokenizer": None, "chat_template": None, "out_dtype": None, } # Create the MergeConfiguration from the dictionary merge_config = MergeConfiguration.model_validate(merge_config_dict) return merge_config def create(self) -> "MergeConfiguration": if self.method == "linear": return self.create_merge_config_linear() elif self.method == "ties": return self.create_merge_config_ties() elif self.method == "dare_ties": return self.create_merge_config_dare_ties() elif self.method == "slerp": return self.create_merge_config_slerp() def merge_models(config: MergeConfig, out_path: str): """ Merge two models using mergekit Args: config (`MergeConfig`): The merge configuration. out_path (`str`): The output path for the merged model. """ if not is_mergekit_available(): raise ImportError("merge_models requires the `mergekit` extra. To install, run `pip install mergekit`.") run_merge( config, out_path=out_path, options=MergeOptions( device="auto", cuda=torch.cuda.is_available(), copy_tokenizer=True, lazy_unpickle=False, low_cpu_memory=False, ), )
trl/trl/mergekit_utils.py/0
{ "file_path": "trl/trl/mergekit_utils.py", "repo_id": "trl", "token_count": 5120 }
587
# Copyright 2020-2025 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. # /// script # dependencies = [ # "trl @ git+https://github.com/huggingface/trl.git", # "peft", # ] # /// import argparse import importlib import os import sys from dataclasses import dataclass, field from typing import Optional from accelerate import logging from datasets import load_dataset from trl import ( DatasetMixtureConfig, GRPOConfig, GRPOTrainer, ModelConfig, ScriptArguments, TrlParser, get_dataset, get_peft_config, ) from trl.rewards import get_soft_overlong_punishment, think_format_reward logger = logging.get_logger(__name__) reward_funcs_registry = { "think_format_reward": think_format_reward, "get_soft_overlong_punishment": get_soft_overlong_punishment, } @dataclass class GRPOScriptArguments(ScriptArguments): """ Script arguments for the GRPO training script. Args: reward_model_name_or_path (`str` or `None`, *optional*, defaults to `None`): Reward model id of a pretrained model hosted inside a model repo on huggingface.co or local path to a directory containing model weights saved using [`~transformers.PreTrainedModel.save_pretrained`]. reward_funcs (`list[str]` or `None`, *optional*, defaults to `None`): Reward functions to use. It can be either one of `"think_format_reward"`; or a dotted import path " (e.g., `'my_lib.rewards.custom_reward'`). """ reward_model_name_or_path: Optional[str] = field( default=None, metadata={ "help": "Reward model id of a pretrained model hosted inside a model repo on huggingface.co or " "local path to a directory containing model weights saved using `PreTrainedModel.save_pretrained`." }, ) reward_funcs: Optional[list[str]] = field( default=None, metadata={ "help": "Reward functions to use. It can be either one of 'think_format_reward'; or a dotted " "import path. (e.g., 'my_lib.rewards.custom_reward')." }, ) def main(script_args, training_args, model_args, dataset_args): # Get the reward models and functions reward_funcs = [] if script_args.reward_model_name_or_path: reward_funcs.append(script_args.reward_model_name_or_path) if script_args.reward_funcs: for func_name in script_args.reward_funcs: if func_name in reward_funcs_registry: reward_funcs.append(reward_funcs_registry[func_name]) elif "." in func_name: module_path, func_name = func_name.rsplit(".", 1) sys.path.insert(0, os.getcwd()) module = importlib.import_module(module_path) reward_func = getattr(module, func_name) reward_funcs.append(reward_func) else: raise ValueError( f"Could not load reward function '{func_name}'. Expected one of " f"{list(reward_funcs_registry.keys())} or a valid import path." ) # Load the dataset if dataset_args.datasets and script_args.dataset_name: logger.warning( "Both `datasets` and `dataset_name` are provided. The `datasets` argument will be used to load the " "dataset and `dataset_name` will be ignored." ) elif dataset_args.datasets and not script_args.dataset_name: dataset = get_dataset(dataset_args) elif not dataset_args.datasets and script_args.dataset_name: dataset = load_dataset( script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming ) else: raise ValueError("Either `datasets` or `dataset_name` must be provided.") # Initialize the GRPO trainer trainer = GRPOTrainer( model=model_args.model_name_or_path, reward_funcs=reward_funcs, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, peft_config=get_peft_config(model_args), ) # Train the model trainer.train() # Save and push to Hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name) def make_parser(subparsers: argparse._SubParsersAction = None): dataclass_types = (GRPOScriptArguments, GRPOConfig, ModelConfig, DatasetMixtureConfig) if subparsers is not None: parser = subparsers.add_parser("grpo", help="Run the GRPO training script", dataclass_types=dataclass_types) else: parser = TrlParser(dataclass_types) return parser if __name__ == "__main__": parser = make_parser() # When using the trl cli, this script may be run with additional arguments, corresponding accelerate arguments. # To ensure that their parsing does not interfere with the script arguments, parse the arguments with # `return_remaining_strings=True`, then ignore the remaining strings. script_args, training_args, model_args, dataset_args, _ = parser.parse_args_and_config( return_remaining_strings=True ) main(script_args, training_args, model_args, dataset_args)
trl/trl/scripts/grpo.py/0
{ "file_path": "trl/trl/scripts/grpo.py", "repo_id": "trl", "token_count": 2330 }
588
# Copyright 2020-2025 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 dataclasses import dataclass, field from enum import Enum from typing import Any, Callable, Optional, Union from transformers import TrainingArguments class FDivergenceType(Enum): REVERSE_KL = "reverse_kl" JS_DIVERGENCE = "js_divergence" ALPHA_DIVERGENCE = "alpha_divergence" class FDivergenceConstants: ALPHA_DIVERGENCE_COEF_KEY = "alpha_divergence_coef" ALPHA_DIVERGENCE_COEF_DEFAULT = 1.0 @dataclass class DPOConfig(TrainingArguments): r""" Configuration class for the [`DPOTrainer`]. This class includes only the parameters that are specific to DPO training. For a full list of training arguments, please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may differ from those in [`~transformers.TrainingArguments`]. Using [`~transformers.HfArgumentParser`] we can turn this class into [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the command line. Parameters: > Parameters that control the model and reference model model_init_kwargs (`dict[str, Any]` or `None`, *optional*, defaults to `None`): Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the [`DPOTrainer`] is provided as a string. ref_model_init_kwargs (`dict[str, Any]` or `None`, *optional*, defaults to `None`): Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `ref_model` argument of the [`DPOTrainer`] is provided as a string. model_adapter_name (`str` or `None`, *optional*, defaults to `None`): Name of the train target PEFT adapter, when using LoRA with multiple adapters. ref_adapter_name (`str` or `None`, *optional*, defaults to `None`): Name of the reference PEFT adapter, when using LoRA with multiple adapters. force_use_ref_model (`bool`, *optional*, defaults to `False`): If you provide a PEFT model as the active model and wish to use a different model for the `ref_model`, set this flag to `True`. disable_dropout (`bool`, *optional*, defaults to `True`): Whether to disable dropout in the model and reference model. use_logits_to_keep (`bool`, *optional*, defaults to `False`): If `True`, only a specified number of logits are computed in the forward pass. This can be useful for saving memory and speeding up training by not computing the logits for all tokens, especially in scenarios when working with very long prompts where labels are ignored (-100). > Parameters that control the data preprocessing dataset_num_proc (`int` or `None`, *optional*, defaults to `None`): Number of processes to use for processing the dataset. padding_value (`int` or `None`, *optional*, defaults to `None`): Padding value to use. If `None`, the padding value of the tokenizer is used. label_pad_token_id (`int`, *optional*, defaults to `-100`): Padding value to use for labels. max_prompt_length (`int` or `None`, *optional*, defaults to `512`): Maximum length of the prompt. max_completion_length (`int` or `None`, *optional*, defaults to `None`): Maximum length of the completion. max_length (`int` or `None`, *optional*, defaults to `1024`): Maximum length of the full sequence (prompt + completion). truncation_mode (`str`, *optional*, defaults to `"keep_end"`): Truncation mode to use when the sequence exceeds `max_length`. Possible values are `"keep_end"` and `"keep_start"`. padding_free (`bool`, *optional*, defaults to `False`): Whether to perform forward passes without padding by flattening all sequences in the batch into a single continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only supported with the `flash_attention_2` attention implementation, which can efficiently handle the flattened batch structure. precompute_ref_log_probs (`bool`, *optional*, defaults to `False`): Whether to precompute the log probabilities from the reference model. Setting this to `True` allows training without needing the reference model during training, which can help reduce GPU memory usage. If set to `False` (default), the reference model will be used during training to compute log probabilities on-the-fly. precompute_ref_batch_size (`int` or `None`, *optional*, defaults to `None`): Batch size to use when precomputing reference model log probabilities. This can be set higher than the training batch size to speed up preprocessing. If `None`, defaults to `per_device_train_batch_size` for training and `per_device_eval_batch_size` for evaluation. tools (`Optional[list[Union[dict, Callable]]]`, *optional*, defaults to `None`): List of tools (callable functions) that will be accessible to the model. If the template does not support function calling, this argument will have no effect. > Parameters that control the training loss_type (`str` or `list[str]`, *optional*, defaults to `"sigmoid"`): Type of loss to use. Possible values are: - `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper. - `"hinge"`: hinge loss on the normalized likelihood from the [SLiC](https://huggingface.co/papers/2305.10425) paper. - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper. - `"exo_pair"`: pairwise EXO loss from the [EXO](https://huggingface.co/papers/2402.00856) paper. - `"nca_pair"`: pairwise NCA loss from the [NCA](https://huggingface.co/papers/2402.05369) paper. - `"robust"`: unbiased estimate of the DPO loss that is robust to preference noise from the [Robust DPO](https://huggingface.co/papers/2403.00409) paper. - `"bco_pair"`: pairwise BCO loss from the [BCO](https://huggingface.co/papers/2404.04656) paper. - `"sppo_hard"`: SPPO loss with hard label from the [SPPO](https://huggingface.co/papers/2405.00675) paper. - `"aot"`: AOT loss for paired datasets from the [AOT](https://huggingface.co/papers/2406.05882) paper. - `"aot_pair"`: AOT loss for unpaired datasets from the [AOT](https://huggingface.co/papers/2406.05882) paper. - `"discopop"`: DiscoPOP (a.k.a Log-Ratio Modulated Loss, LRML) loss from the [DiscoPOP](https://huggingface.co/papers/2406.08414) paper. - `"apo_zero"`: APO-zero loss from the [APO](https://huggingface.co/papers/2408.06266) paper. - `"apo_down"`: APO-down loss from the [APO](https://huggingface.co/papers/2408.06266) paper. - `"sft"`: Negative log-likelihood loss (standard supervised fine-tuning loss). Multiple loss types can be combined using comma separation (e.g., `["sigmoid", "bco_pair", "sft"]` for [MPO](https://huggingface.co/papers/2411.10442)). The `loss_weights` parameter can be used to specify corresponding weights for each loss type. use_liger_loss (`bool`, *optional*, defaults to `False`): Whether to use Liger loss. base_model_attribute_name (`str`, *optional*, defaults to `"model"`): Name of the attribute in the model that contains the base model. This is used to get the base model from the model when the model does not have a `get_decoder` method in the case when `use_liger_loss` is `True`. beta (`float`, *optional*, defaults to `0.1`): Parameter controlling the deviation from the reference model. Higher β means less deviation from the reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in the [paper](https://huggingface.co/papers/2310.12036). f_divergence_type (`str`, *optional*, defaults to `FDivergenceType.REVERSE_KL`): Type of f-divergence regularization function to compute divergence between policy and reference model. f_alpha_divergence_coef (`float`, *optional*, defaults to `1.0`): α coefficient in the α-divergence u^-α regularization function for DPO loss. reference_free (`bool`, *optional*, defaults to `False`): Whether to ignore the provided reference model and implicitly use a reference model that assigns equal probability to all responses. label_smoothing (`float`, *optional*, defaults to `0.0`): Robust DPO label smoothing parameter from the [cDPO report](https://ericmitchell.ai/cdpo.pdf) and [Robust DPO](https://huggingface.co/papers/2403.00409) paper that should be between `0.0` and `0.5`. use_weighting (`bool`, *optional*, defaults to `False`): Whether to weight the loss as done in the [WPO paper](https://huggingface.co/papers/2406.11827). rpo_alpha (`float`, *optional*, defaults to `None`): α parameter from the [RPO paper](https://huggingface.co/papers/2404.19733) (v3), which controls the weighting of the NLL term in the loss. If `None`, no weighting is applied and the loss is the same as the DPO loss. The paper recommends `rpo_alpha=1.0`. ld_alpha (`float` or `None`, *optional*, defaults to `None`): α parameter from the [LD-DPO paper](https://huggingface.co/papers/2409.06411), which controls the weighting of the verbose token log-probabilities in responses. If `None`, no weighting is applied to the verbose part, and the loss is equivalent to the standard DPO loss. The paper recommends setting `ld_alpha` between `0.0` and `1.0`. discopop_tau (`float`, *optional*, defaults to `0.05`): τ/temperature parameter from the [DiscoPOP](https://huggingface.co/papers/2406.08414) paper, which controls the shape of log ratio modulated loss. The paper recommends the default value `discopop_tau=0.05`. loss_weights (`list[float]` or `None`, *optional*, defaults to `None`): List of loss weights for multi-loss combinations. Used when combining multiple loss types. Example: `[0.8, 0.2, 1.0]` for [MPO](https://huggingface.co/papers/2411.10442). If not provided, defaults to equal weights (`1.0`) for all loss types. sync_ref_model (`bool`, *optional*, defaults to `False`): Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using the `ref_model_mixup_alpha` parameter. This synchronization originates from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper. ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`): α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix between the current policy and the previous reference policy during updates. The reference policy is updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`. ref_model_sync_steps (`int`, *optional*, defaults to `512`): τ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how frequently the current policy is synchronized with the reference policy. To use this parameter, you must set `sync_ref_model=True`. > Parameters that control the logging generate_during_eval (`bool`, *optional*, defaults to `False`): Whether to generate and log completions from both the model and the reference model to W&B or Comet during evaluation. """ _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs", "ref_model_init_kwargs"] # Parameters whose default values are overridden from TrainingArguments learning_rate: float = field( default=1e-6, metadata={"help": "The initial learning rate for AdamW."}, ) logging_steps: float = field( default=10, metadata={ "help": "Log every X updates steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, " "will be interpreted as ratio of total training steps." }, ) gradient_checkpointing: bool = field( default=True, metadata={ "help": "If True, use gradient checkpointing to save memory at the expense of slower backward pass." }, ) bf16: Optional[bool] = field( default=None, metadata={ "help": "Whether to use bf16 (mixed) precision instead of 32-bit. Requires Ampere or higher NVIDIA " "architecture or Intel XPU or using CPU (use_cpu) or Ascend NPU. If not set, it defaults to `True` if " "`fp16` is not set." }, ) # Parameters that control the model and reference model model_init_kwargs: Optional[dict[str, Any]] = field( default=None, metadata={ "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " "the `DPOTrainer` is provided as a string." }, ) ref_model_init_kwargs: Optional[dict[str, Any]] = field( default=None, metadata={ "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `ref_model` argument " "of the `DPOTrainer` is provided as a string." }, ) model_adapter_name: Optional[str] = field( default=None, metadata={"help": "Name of the train target PEFT adapter, when using LoRA with multiple adapters."}, ) ref_adapter_name: Optional[str] = field( default=None, metadata={"help": "Name of the reference PEFT adapter, when using LoRA with multiple adapters."}, ) force_use_ref_model: bool = field( default=False, metadata={ "help": "If you provide a PEFT model as the active model and wish to use a different model for the " "`ref_model`, set this flag to `True`." }, ) disable_dropout: bool = field( default=True, metadata={"help": "Whether to disable dropout in the model and reference model."}, ) use_logits_to_keep: bool = field( default=False, metadata={ "help": "If `True`, only a specified number of logits are computed in the forward pass. This can be " "useful for saving memory and speeding up training by not computing the logits for all tokens, especially " "in scenarios when working with very long prompts where labels are ignored (-100)." }, ) # Parameters that control the data preprocessing dataset_num_proc: Optional[int] = field( default=None, metadata={"help": "Number of processes to use for processing the dataset."}, ) padding_value: Optional[int] = field( default=None, metadata={"help": "Padding value to use. If `None`, the padding value of the tokenizer is used."}, ) label_pad_token_id: int = field( default=-100, metadata={"help": "Padding value to use for labels."}, ) max_prompt_length: Optional[int] = field( default=512, metadata={"help": "Maximum length of the prompt."}, ) max_completion_length: Optional[int] = field( default=None, metadata={"help": "Maximum length of the completion."}, ) max_length: Optional[int] = field( default=1024, metadata={"help": "Maximum length of the full sequence (prompt + completion)."}, ) truncation_mode: str = field( default="keep_end", metadata={ "help": "Truncation mode to use when the sequence exceeds `max_length`. Possible values are `'keep_end'` " "and `'keep_start'`.", "choices": ["keep_end", "keep_start"], }, ) padding_free: bool = field( default=False, metadata={ "help": "Whether to perform forward passes without padding by flattening all sequences in the batch into " "a single continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, " "this is only supported with the `flash_attention_2` attention implementation, which can efficiently " "handle the flattened batch structure." }, ) precompute_ref_log_probs: bool = field( default=False, metadata={ "help": "Whether to precompute the log probabilities from the reference model. Setting this to `True` " "allows training without needing the reference model during training, which can help reduce GPU memory " "usage. If set to `False` (default), the reference model will be used during training to compute log " "probabilities on-the-fly." }, ) precompute_ref_batch_size: Optional[int] = field( default=None, metadata={ "help": "Batch size to use when precomputing reference model log probabilities. This can be set higher " "than the training batch size to speed up preprocessing. If `None`, defaults to " "`per_device_train_batch_size` for training and `per_device_eval_batch_size` for evaluation." }, ) tools: Optional[list[Union[dict, Callable]]] = field( default=None, metadata={ "help": "List of tools (callable functions) that will be accessible to the model. If the template does " "not support function calling, this argument will have no effect." }, ) # Parameters that control the training loss_type: list[str] = field( default_factory=lambda: ["sigmoid"], metadata={ "help": "Type of loss to use. Possible values are: `'sigmoid'`, `'hinge'`, `'ipo'`, `'exo_pair'`, " "`'nca_pair'`, `'robust'`, `'bco_pair'`, `'sppo_hard'`, `'aot'`, `'aot_pair'`, `'discopop'`, " "`'apo_zero'`, `'apo_down'` and `'sft'`. Multiple loss types can be combined using comma separation " "(e.g., `['sigmoid', 'bco_pair', 'sft']` for MPO). The `loss_weights` parameter can be used to specify " "corresponding weights for each loss type." }, ) use_liger_loss: bool = field( default=False, metadata={"help": "Whether to use Liger loss."}, ) base_model_attribute_name: str = field( default="model", metadata={ "help": "Name of the attribute in the model that contains the base model. This is used to get the base " "model from the model when the model does not have a `get_decoder` method in the case when " "`use_liger_loss` is `True`." }, ) beta: float = field( default=0.1, metadata={ "help": "Parameter controlling the deviation from the reference model. " "Higher β means less deviation from the reference model." }, ) f_divergence_type: FDivergenceType = field( default=FDivergenceType.REVERSE_KL, metadata={ "help": "Type of f-divergence regularization function to compute divergence between policy and reference " "model." }, ) f_alpha_divergence_coef: float = field( default=1.0, metadata={"help": "α coefficient in the α-divergence u^-α regularization function for DPO loss."}, ) reference_free: bool = field( default=False, metadata={ "help": "Whether to ignore the provided reference model and implicitly use a reference model that assigns " "equal probability to all responses." }, ) label_smoothing: float = field( default=0.0, metadata={ "help": "Robust DPO label smoothing parameter from the cDPO report and Robust DPO paper that should " "be between `0.0` and `0.5`." }, ) use_weighting: bool = field( default=False, metadata={"help": "Whether to weight the loss as done in the WPO paper."}, ) rpo_alpha: Optional[float] = field( default=None, metadata={ "help": "α parameter from the RPO paper (v3), which controls the weighting of the NLL term in the loss. " "If `None`, no weighting is applied and the loss is the same as the DPO loss. The paper recommends " "`rpo_alpha=1.0`." }, ) ld_alpha: Optional[float] = field( default=None, metadata={ "help": "α parameter from the LD-DPO paper, which controls the weighting of the verbose token " "log-probabilities in responses. If `None`, no weighting is applied to the verbose part, and the loss is " "equivalent to the standard DPO loss. The paper recommends setting `ld_alpha` between `0.0` and `1.0`.", }, ) discopop_tau: float = field( default=0.05, metadata={ "help": "τ/temperature parameter from the DiscoPOP paper, which controls the shape of log ratio modulated " "loss. The paper recommends the default value `discopop_tau=0.05`." }, ) loss_weights: Optional[list[float]] = field( default=None, metadata={ "help": "List of loss weights for multi-loss combinations. Used when combining multiple loss types. " "Example: `[0.8, 0.2, 1.0]` for MPO. If not provided, defaults to equal weights (`1.0`) for all loss " "types." }, ) sync_ref_model: bool = field( default=False, metadata={ "help": "Whether to synchronize the reference model with the active model every `ref_model_sync_steps` " "steps, using the `ref_model_mixup_alpha` parameter." }, ) ref_model_mixup_alpha: float = field( default=0.6, metadata={ "help": "α parameter from the TR-DPO paper, which controls the mix between the current policy and the " "previous reference policy during updates. The reference policy is updated according to the equation: " "`π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`." }, ) ref_model_sync_steps: int = field( default=512, metadata={ "help": "τ parameter from the TR-DPO paper, which determines how frequently the current policy is " "synchronized with the reference policy. To use this parameter, you must set `sync_ref_model=True`." }, ) # Parameters that control the logging generate_during_eval: bool = field( default=False, metadata={ "help": "Whether to generate and log completions from both the model and the reference model to W&B, MLFLow " "or Comet during evaluation." }, ) def __post_init__(self): self.bf16 = not (self.fp16) if self.bf16 is None else self.bf16 # Normalize loss_type to string format for internal use if hasattr(self.loss_type, "__len__") and len(self.loss_type) == 1: self.loss_type = self.loss_type[0] # Validate loss_type if self.loss_weights is not None: loss_types = self.loss_type if isinstance(self.loss_type, list) else [self.loss_type] if len(self.loss_weights) != len(loss_types): raise ValueError( f"Length of loss_weights list ({self.loss_weights}) must match number of loss types " f"({loss_types})." ) super().__post_init__()
trl/trl/trainer/dpo_config.py/0
{ "file_path": "trl/trl/trainer/dpo_config.py", "repo_id": "trl", "token_count": 9729 }
589
from translation import auto_translate output_lang = "vi" prompt = lambda content: f''' You are a translator for the Vietnamese translation team. You are tasked with translating the following text into Vietnamese. You must follow these instructions: - Translate the text into Vietnamese, while keeping the original formatting (either Markdown, MDX or HTML) - Inside code blocks, translate the comments but leave the code as-is ; If the code block contains quite plain texts, you MUST provide the translation in <details> tag - Do not translate inline code, the URLs and file paths - If the term is abbreviated, keep the original term and provide the translation in parentheses for the first time it appears in the text - If there are any slag or funny joke in english, keep it (do not translate) and give an explanation so vietnamese reader can understand - Use "ta", "chúng ta", "chúng mình", "các bạn" as pronouns KEEP THESE TERMS (DO NOT TRANSLATE, do NOT add translation in parentheses): model, API, SDK, CLI, HTML, GGUF, AI, training, inference, server, client, notebook, python, Hugging Face, transformers, diffusion, diffuser, data, function, LangGraph, LangChain, Llama, Gemma, token, Unit, pretrain, Live (live stream), form, format, certificate, Space, CodeAgent Also KEEP these terms but PROVIDE TRANSLATION in parentheses for the first time it appears in the text: alignment (cân chỉnh), LLM, RAG (tìm kiếm và tạo ra câu trả lời), Agent (tác nhân), Tools (công cụ), "Special Token" (token đặc biệt), "chain-of-thought" (luồng suy luận), fine-tuning (tinh chỉnh), Thought-Action-Observation (Tư duy-Hành động-Quan sát) For these terms, use the pre-defined translation: - Quick Quiz: Kiểm tra nhanh - Unit: Chương - Bonus Unit: Chương bổ trợ - Module: Mô-đun - Lesson ...: Bài ... - Course: Khóa học - state-of-the-art: hiện đại nhất - Q&A: Hỏi và Đáp - Dummy: ảo (or "giả", or "thử" depending on the context) - onboarding: làm quen - Hands-on: Thực hành - Challenge: Bài tập lớn Here is an example: - Original text: To run the models, we will use [ollama](https://ollama.com), a command line tool that allows you to run LLMs and embedding models from Hugging Face. With ollama, you **don't need** to have access to a server or cloud service to run the models. You can run the models directly **on your computer**. - Translation: Để chạy các model, ta sẽ sử dụng [ollama](https://ollama.com), một công cụ dòng lệnh cho phép bạn chạy LLMs và embedding models từ Hugging Face. Với ollama, bạn **không cần** phải tạo server hay truy cập API bên thứ 3. Bạn có thể chạy các model trực tiếp **trên máy tính của bạn**. Here is another example: - Original text: The model can then be **aligned** to the creator's preferences. For instance, a customer service chat model that must never be impolite to customers. - Translation: Model sau đó có thể được **alignment** (cân chỉnh) theo mong muốn của người tạo. Ví dụ: model chat hỗ trợ khách hàng không bao giờ được bất lịch sự. If the code block contains many plain texts, prove translation in collapsible <details> tag. Example: - Original text: ``` <|im_start|>Hello, how are you?<|im_end|> <|im_start|>I'm fine, thank you.<|im_end|> message = {{"user": "This is a test"}} ``` - Translation (add the <details> collapsible ABOVE of the original code block): <details> <summary>Bấm để xem bản dịch tiếng Việt</summary> ``` <|im_start|>Xin chào, bạn có khỏe không?<|im_end|> <|im_start|>Mình khỏe, cảm ơn bạn.<|im_end|> message = {{"user": "Đây là một tin nhắn thử"}} ``` </details> ``` <|im_start|>Hello, how are you?<|im_end|> <|im_start|>I'm fine, thank you.<|im_end|> message = {{"user": "This is a test"}} ``` IMPORTANT: Only output the translated text and nothing else, no need explanation or instruction. The input text is between "=== BEGIN OF TEXT ===" and "=== END OF TEXT ===". Please translate the following text to vietnamese: === BEGIN OF TEXT === {content} === END OF TEXT === '''.strip() auto_translate( prompt=prompt, output_lang=output_lang, )
agents-course/scripts/vi.py/0
{ "file_path": "agents-course/scripts/vi.py", "repo_id": "agents-course", "token_count": 1651 }
0
# The State of the Art in Using LLMs in Games To give you a sense of how much progress has been made in this field, let’s examine three tech demos and one published game that showcase the integration of LLMs in gaming. ## 🕵️‍♂️ Covert Protocol by NVIDIA and Inworld AI <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit3/covert-protocol.jpg" alt="Covert Protocol"/> Unveiled at GDC 2024, *Covert Protocol* is a tech demo that places you in the shoes of a private detective. What’s interesting in this demo is the use of AI-powered NPCs that respond to your inquiries in real-time, influencing the narrative based on your interactions. The demo is built on Unreal Engine 5, it leverages NVIDIA's Avatar Cloud Engine (ACE) and Inworld's AI to create lifelike character interactions. Learn more here 👉 [Inworld AI Blog](https://inworld.ai/blog/nvidia-inworld-ai-demo-on-device-capabilities) ## 🤖 NEO NPCs by Ubisoft <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit3/neo-npc.jpeg" alt="Neo NPC"/> Also at GDC 2024, Ubisoft introduced *NEO NPCs*, a prototype showcasing NPCs powered by generative AI. These characters can perceive their environment, remember past interactions, and engage in meaningful conversations with players. The idea here is to create more immersive and responsive game worlds where the player can have true interaction with NPCs. Learn more here 👉 [Inworld AI Blog](https://inworld.ai/blog/gdc-2024) ## ⚔️ Mecha BREAK Featuring NVIDIA's ACE <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit3/mecha-break.jpg" alt="Mecha BREAK"/> *Mecha BREAK*, an upcoming multiplayer mech battle game, integrates NVIDIA's ACE technology to bring AI-powered NPCs to life. Players can interact with these characters using natural language, and the NPCs can recognize players and objects via webcam, thanks to GPT-4o integration. This innovation promises a more immersive and interactive gaming experience. Learn more here 👉 [NVIDIA Blog](https://blogs.nvidia.com/blog/digital-human-technology-mecha-break/) ## 🧛‍♂️ *Suck Up!* by Proxima Enterprises <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit3/suck-up.jpg" alt="Suck Up"/> Finally, *Suck Up!* is a published game where you play as a vampire attempting to gain entry into homes by **convincing AI-powered NPCs to invite you in.** Each character is driven by generative AI, allowing for dynamic and unpredictable interactions. Learn more here 👉 [Suck Up! Official Website](https://www.playsuckup.com/) ## Wait… Where Are the Agents? After exploring these demos, you might be wondering: "These examples showcase the use of LLMs in games but they don't seem to involve Agents. So, what's the distinction, and what additional capabilities do Agents bring to the table?” Don’t worry, it’s what we’re going to study in the next section.
agents-course/units/en/bonus-unit3/state-of-art.mdx/0
{ "file_path": "agents-course/units/en/bonus-unit3/state-of-art.mdx", "repo_id": "agents-course", "token_count": 860 }
1
# Thought: Internal Reasoning and the ReAct Approach <Tip> In this section, we dive into the inner workings of an AI agent—its ability to reason and plan. We’ll explore how the agent leverages its internal dialogue to analyze information, break down complex problems into manageable steps, and decide what action to take next. Additionally, we introduce the ReAct approach, a prompting technique that encourages the model to think “step by step” before acting. </Tip> Thoughts represent the **Agent's internal reasoning and planning processes** to solve the task. This utilises the agent's Large Language Model (LLM) capacity **to analyze information when presented in its prompt** — essentially, its inner monologue as it works through a problem. The Agent's thoughts help it assess current observations and decide what the next action(s) should be. Through this process, the agent can **break down complex problems into smaller, more manageable steps**, reflect on past experiences, and continuously adjust its plans based on new information. ## 🧠 Examples of Common Thought Types | Type of Thought | Example | |--------------------|-------------------------------------------------------------------------| | Planning | "I need to break this task into three steps: 1) gather data, 2) analyze trends, 3) generate report" | | Analysis | "Based on the error message, the issue appears to be with the database connection parameters" | | Decision Making | "Given the user's budget constraints, I should recommend the mid-tier option" | | Problem Solving | "To optimize this code, I should first profile it to identify bottlenecks" | | Memory Integration | "The user mentioned their preference for Python earlier, so I'll provide examples in Python" | | Self-Reflection | "My last approach didn't work well, I should try a different strategy" | | Goal Setting | "To complete this task, I need to first establish the acceptance criteria" | | Prioritization | "The security vulnerability should be addressed before adding new features" | > **Note:** In the case of LLMs fine-tuned for function-calling, the thought process is optional. More details will be covered in the Actions section. ## 🔗 Chain-of-Thought (CoT) **Chain-of-Thought (CoT)** is a prompting technique that guides a model to **think through a problem step-by-step before producing a final answer.** It typically starts with: > *"Let's think step by step."* This approach helps the model **reason internally**, especially for logical or mathematical tasks, **without interacting with external tools**. ### ✅ Example (CoT) ``` Question: What is 15% of 200? Thought: Let's think step by step. 10% of 200 is 20, and 5% of 200 is 10, so 15% is 30. Answer: 30 ``` ## ⚙️ ReAct: Reasoning + Acting A key method is the **ReAct approach**, which combines "Reasoning" (Think) with "Acting" (Act). ReAct is a prompting technique that encourages the model to think step-by-step and interleave actions (like using tools) between reasoning steps. This enables the agent to solve complex multi-step tasks by alternating between: - Thought: internal reasoning - Action: tool usage - Observation: receiving tool output ### 🔄 Example (ReAct) ``` Thought: I need to find the latest weather in Paris. Action: Search["weather in Paris"] Observation: It's 18°C and cloudy. Thought: Now that I know the weather... Action: Finish["It's 18°C and cloudy in Paris."] ``` <figure> <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/ReAct.png" alt="ReAct"/> <figcaption> (d) is an example of the ReAct approach, where we prompt "Let's think step by step", and the model acts between thoughts. </figcaption> </figure> ## 🔁 Comparison: ReAct vs. CoT | Feature | Chain-of-Thought (CoT) | ReAct | |----------------------|-----------------------------|-------------------------------------| | Step-by-step logic | ✅ Yes | ✅ Yes | | External tools | ❌ No | ✅ Yes (Actions + Observations) | | Best suited for | Logic, math, internal tasks | Info-seeking, dynamic multi-step tasks | <Tip> Recent models like **Deepseek R1** or **OpenAI’s o1** were fine-tuned to *think before answering*. They use structured tokens like `<think>` and `</think>` to explicitly separate the reasoning phase from the final answer. Unlike ReAct or CoT — which are prompting strategies — this is a **training-level technique**, where the model learns to think via examples. </Tip>
agents-course/units/en/unit1/thoughts.mdx/0
{ "file_path": "agents-course/units/en/unit1/thoughts.mdx", "repo_id": "agents-course", "token_count": 1395 }
2
# Conclusion Congratulations on finishing the `llama-index` module of this second Unit 🥳 You’ve just mastered the fundamentals of `llama-index` and you’ve seen how to build your own agentic workflows! Now that you have skills in `llama-index`, you can start to create search engines that will solve tasks you're interested in. In the next module of the unit, you're going to learn **how to build Agents with LangGraph**. Finally, we would love **to hear what you think of the course and how we can improve it**. If you have some feedback then, please 👉 [fill this form](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) ### Keep Learning, and stay awesome 🤗
agents-course/units/en/unit2/llama-index/conclusion.mdx/0
{ "file_path": "agents-course/units/en/unit2/llama-index/conclusion.mdx", "repo_id": "agents-course", "token_count": 229 }
3
<CourseFloatingBanner classNames="absolute z-10 right-0 top-0" notebooks={[ {label: "Google Colab", value: "https://colab.research.google.com/#fileId=https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/tools.ipynb"}, ]} askForHelpUrl="http://hf.co/join/discord" /> # Tools As we explored in [unit 1](https://huggingface.co/learn/agents-course/unit1/tools), agents use tools to perform various actions. In `smolagents`, tools are treated as **functions that an LLM can call within an agent system**. To interact with a tool, the LLM needs an **interface description** with these key components: - **Name**: What the tool is called - **Tool description**: What the tool does - **Input types and descriptions**: What arguments the tool accepts - **Output type**: What the tool returns For instance, while preparing for a party at Wayne Manor, Alfred needs various tools to gather information - from searching for catering services to finding party theme ideas. Here's how a simple search tool interface might look: - **Name:** `web_search` - **Tool description:** Searches the web for specific queries - **Input:** `query` (string) - The search term to look up - **Output:** String containing the search results By using these tools, Alfred can make informed decisions and gather all the information needed for planning the perfect party. Below, you can see an animation illustrating how a tool call is managed: ![Agentic pipeline from https://huggingface.co/docs/smolagents/conceptual_guides/react](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Agent_ManimCE.gif) ## Tool Creation Methods In `smolagents`, tools can be defined in two ways: 1. **Using the `@tool` decorator** for simple function-based tools 2. **Creating a subclass of `Tool`** for more complex functionality ### The `@tool` Decorator The `@tool` decorator is the **recommended way to define simple tools**. Under the hood, smolagents will parse basic information about the function from Python. So if you name your function clearly and write a good docstring, it will be easier for the LLM to use. Using this approach, we define a function with: - **A clear and descriptive function name** that helps the LLM understand its purpose. - **Type hints for both inputs and outputs** to ensure proper usage. - **A detailed description**, including an `Args:` section where each argument is explicitly described. These descriptions provide valuable context for the LLM, so it's important to write them carefully. #### Generating a tool that retrieves the highest-rated catering <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/smolagents/alfred-catering.jpg" alt="Alfred Catering"/> <Tip> You can follow the code in <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/tools.ipynb" target="_blank">this notebook</a> that you can run using Google Colab. </Tip> Let's imagine that Alfred has already decided on the menu for the party, but now he needs help preparing food for such a large number of guests. To do so, he would like to hire a catering service and needs to identify the highest-rated options available. Alfred can leverage a tool to search for the best catering services in his area. Below is an example of how Alfred can use the `@tool` decorator to make this happen: ```python from smolagents import CodeAgent, InferenceClientModel, tool # Let's pretend we have a function that fetches the highest-rated catering services. @tool def catering_service_tool(query: str) -> str: """ This tool returns the highest-rated catering service in Gotham City. Args: query: A search term for finding catering services. """ # Example list of catering services and their ratings services = { "Gotham Catering Co.": 4.9, "Wayne Manor Catering": 4.8, "Gotham City Events": 4.7, } # Find the highest rated catering service (simulating search query filtering) best_service = max(services, key=services.get) return best_service agent = CodeAgent(tools=[catering_service_tool], model=InferenceClientModel()) # Run the agent to find the best catering service result = agent.run( "Can you give me the name of the highest-rated catering service in Gotham City?" ) print(result) # Output: Gotham Catering Co. ``` ### Defining a Tool as a Python Class This approach involves creating a subclass of [`Tool`](https://huggingface.co/docs/smolagents/v1.8.1/en/reference/tools#smolagents.Tool). For complex tools, we can implement a class instead of a Python function. The class wraps the function with metadata that helps the LLM understand how to use it effectively. In this class, we define: - `name`: The tool's name. - `description`: A description used to populate the agent's system prompt. - `inputs`: A dictionary with keys `type` and `description`, providing information to help the Python interpreter process inputs. - `output_type`: Specifies the expected output type. - `forward`: The method containing the inference logic to execute. Below, we can see an example of a tool built using `Tool` and how to integrate it within a `CodeAgent`. #### Generating a tool to generate ideas about the superhero-themed party Alfred's party at the mansion is a **superhero-themed event**, but he needs some creative ideas to make it truly special. As a fantastic host, he wants to surprise the guests with a unique theme. To do this, he can use an agent that generates superhero-themed party ideas based on a given category. This way, Alfred can find the perfect party theme to wow his guests. ```python from smolagents import Tool, CodeAgent, InferenceClientModel class SuperheroPartyThemeTool(Tool): name = "superhero_party_theme_generator" description = """ This tool suggests creative superhero-themed party ideas based on a category. It returns a unique party theme idea.""" inputs = { "category": { "type": "string", "description": "The type of superhero party (e.g., 'classic heroes', 'villain masquerade', 'futuristic Gotham').", } } output_type = "string" def forward(self, category: str): themes = { "classic heroes": "Justice League Gala: Guests come dressed as their favorite DC heroes with themed cocktails like 'The Kryptonite Punch'.", "villain masquerade": "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains.", "futuristic Gotham": "Neo-Gotham Night: A cyberpunk-style party inspired by Batman Beyond, with neon decorations and futuristic gadgets." } return themes.get(category.lower(), "Themed party idea not found. Try 'classic heroes', 'villain masquerade', or 'futuristic Gotham'.") # Instantiate the tool party_theme_tool = SuperheroPartyThemeTool() agent = CodeAgent(tools=[party_theme_tool], model=InferenceClientModel()) # Run the agent to generate a party theme idea result = agent.run( "What would be a good superhero party idea for a 'villain masquerade' theme?" ) print(result) # Output: "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains." ``` With this tool, Alfred will be the ultimate super host, impressing his guests with a superhero-themed party they won't forget! 🦸‍♂️🦸‍♀️ ## Default Toolbox `smolagents` comes with a set of pre-built tools that can be directly injected into your agent. The [default toolbox](https://huggingface.co/docs/smolagents/guided_tour?build-a-tool=Decorate+a+function+with+%40tool#default-toolbox) includes: - **PythonInterpreterTool** - **FinalAnswerTool** - **UserInputTool** - **DuckDuckGoSearchTool** - **GoogleSearchTool** - **VisitWebpageTool** Alfred could use various tools to ensure a flawless party at Wayne Manor: - First, he could use the `DuckDuckGoSearchTool` to find creative superhero-themed party ideas. - For catering, he'd rely on the `GoogleSearchTool` to find the highest-rated services in Gotham. - To manage seating arrangements, Alfred could run calculations with the `PythonInterpreterTool`. - Once everything is gathered, he'd compile the plan using the `FinalAnswerTool`. With these tools, Alfred guarantees the party is both exceptional and seamless. 🦇💡 ## Sharing and Importing Tools One of the most powerful features of **smolagents** is its ability to share custom tools on the Hub and seamlessly integrate tools created by the community. This includes connecting with **HF Spaces** and **LangChain tools**, significantly enhancing Alfred's ability to orchestrate an unforgettable party at Wayne Manor. 🎭 With these integrations, Alfred can tap into advanced event-planning tools—whether it's adjusting the lighting for the perfect ambiance, curating the ideal playlist for the party, or coordinating with Gotham's finest caterers. Here are examples showcasing how these functionalities can elevate the party experience: ### Sharing a Tool to the Hub Sharing your custom tool with the community is easy! Simply upload it to your Hugging Face account using the `push_to_hub()` method. For instance, Alfred can share his `party_theme_tool` to help others find the best catering services in Gotham. Here's how to do it: ```python party_theme_tool.push_to_hub("{your_username}/party_theme_tool", token="<YOUR_HUGGINGFACEHUB_API_TOKEN>") ``` ### Importing a Tool from the Hub You can easily import tools created by other users using the `load_tool()` function. For example, Alfred might want to generate a promotional image for the party using AI. Instead of building a tool from scratch, he can leverage a predefined one from the community: ```python from smolagents import load_tool, CodeAgent, InferenceClientModel image_generation_tool = load_tool( "m-ric/text-to-image", trust_remote_code=True ) agent = CodeAgent( tools=[image_generation_tool], model=InferenceClientModel() ) agent.run("Generate an image of a luxurious superhero-themed party at Wayne Manor with made-up superheros.") ``` ### Importing a Hugging Face Space as a Tool You can also import a HF Space as a tool using `Tool.from_space()`. This opens up possibilities for integrating with thousands of spaces from the community for tasks from image generation to data analysis. The tool will connect with the spaces Gradio backend using the `gradio_client`, so make sure to install it via `pip` if you don't have it already. For the party, Alfred can use an existing HF Space for the generation of the AI-generated image to be used in the announcement (instead of the pre-built tool we mentioned before). Let's build it! ```python from smolagents import CodeAgent, InferenceClientModel, Tool image_generation_tool = Tool.from_space( "black-forest-labs/FLUX.1-schnell", name="image_generator", description="Generate an image from a prompt" ) model = InferenceClientModel("Qwen/Qwen2.5-Coder-32B-Instruct") agent = CodeAgent(tools=[image_generation_tool], model=model) agent.run( "Improve this prompt, then generate an image of it.", additional_args={'user_prompt': 'A grand superhero-themed party at Wayne Manor, with Alfred overseeing a luxurious gala'} ) ``` ### Importing a LangChain Tool We'll discuss the `LangChain` framework in upcoming sections. For now, we just note that we can reuse LangChain tools in your smolagents workflow! You can easily load LangChain tools using the `Tool.from_langchain()` method. Alfred, ever the perfectionist, is preparing for a spectacular superhero night at Wayne Manor while the Waynes are away. To make sure every detail exceeds expectations, he taps into LangChain tools to find top-tier entertainment ideas. By using `Tool.from_langchain()`, Alfred effortlessly adds advanced search functionalities to his smolagent, enabling him to discover exclusive party ideas and services with just a few commands. Here's how he does it: ```python from langchain.agents import load_tools from smolagents import CodeAgent, InferenceClientModel, Tool search_tool = Tool.from_langchain(load_tools(["serpapi"])[0]) agent = CodeAgent(tools=[search_tool], model=model) agent.run("Search for luxury entertainment ideas for a superhero-themed event, such as live performances and interactive experiences.") ``` ### Importing a tool collection from any MCP server `smolagents` also allows importing tools from the hundreds of MCP servers available on [glama.ai](https://glama.ai/mcp/servers) or [smithery.ai](https://smithery.ai). If you want to dive deeper about MCP, you can check our [free MCP Course](https://huggingface.co/learn/mcp-course/). <details> <summary>Install mcp client</summary> We first need to install the `mcp` integration for `smolagents`. ```bash pip install "smolagents[mcp]" ``` </details> The MCP servers tools can be loaded in a ToolCollection object as follow: ```python import os from smolagents import ToolCollection, CodeAgent from mcp import StdioServerParameters from smolagents import InferenceClientModel model = InferenceClientModel("Qwen/Qwen2.5-Coder-32B-Instruct") server_parameters = StdioServerParameters( command="uvx", args=["--quiet", "pubmedmcp@0.1.3"], env={"UV_PYTHON": "3.12", **os.environ}, ) with ToolCollection.from_mcp(server_parameters, trust_remote_code=True) as tool_collection: agent = CodeAgent(tools=[*tool_collection.tools], model=model, add_base_tools=True) agent.run("Please find a remedy for hangover.") ``` With this setup, Alfred can quickly discover luxurious entertainment options, ensuring Gotham's elite guests have an unforgettable experience. This tool helps him curate the perfect superhero-themed event for Wayne Manor! 🎉 ## Resources - [Tools Tutorial](https://huggingface.co/docs/smolagents/tutorials/tools) - Explore this tutorial to learn how to work with tools effectively. - [Tools Documentation](https://huggingface.co/docs/smolagents/v1.8.1/en/reference/tools) - Comprehensive reference documentation on tools. - [Tools Guided Tour](https://huggingface.co/docs/smolagents/v1.8.1/en/guided_tour#tools) - A step-by-step guided tour to help you build and utilize tools efficiently. - [Building Effective Agents](https://huggingface.co/docs/smolagents/tutorials/building_good_agents) - A detailed guide on best practices for developing reliable and high-performance custom function agents.
agents-course/units/en/unit2/smolagents/tools.mdx/0
{ "file_path": "agents-course/units/en/unit2/smolagents/tools.mdx", "repo_id": "agents-course", "token_count": 4076 }
4
- title: Unit 0. Bienvenida al curso sections: - local: unit0/introduction title: Bienvenida al curso 🤗 - local: unit0/onboarding title: Incorporación - local: unit0/discord101 title: (Optional) Discord 101 - title: Live 1. Como funciona el curso y preguntas y respuestas sections: - local: communication/live1 title: Live 1. Como funciona el curso y preguntas y respuestas - title: Unit 1. Introducción a Agentes sections: - local: unit1/introduction title: Introducción - local: unit1/what-are-agents title: ¿Qué es un Agente? - local: unit1/quiz1 title: Prueba rápida 1 - local: unit1/what-are-llms title: ¿Qué son los LLMs? - local: unit1/messages-and-special-tokens title: Mensajes y tokens especiales - local: unit1/tools title: ¿Qué son las Herramientas? - local: unit1/quiz2 title: Prueba rápida 2 - local: unit1/agent-steps-and-structure title: Entendiendo los Agentes a través del Ciclo de Pensamiento, Acción y Observación - local: unit1/thoughts title: Pensamiento Interno y el Enfoque Re-Act - local: unit1/actions title: Acciones, Habilitando al Agente para Interactuar con su Entorno - local: unit1/observations title: Observar, Integrando Feedback para Reflejar y Adaptar - local: unit1/dummy-agent-library title: Libreria de Agentes Dummy - local: unit1/tutorial title: Creemos nuesto primer Agente usando smolagents - local: unit1/final-quiz title: Prueba Final de Unidad 1 - local: unit1/conclusion title: Conclusión - title: Unidad 2. Frameworks para Agentes de IA sections: - local: unit2/introduction title: Frameworks para Agentes de IA - title: Unidad 2.1 Framework smolagents sections: - local: unit2/smolagents/introduction title: Introducción a smolagents - local: unit2/smolagents/why_use_smolagents title: Por que usar smolagents? - local: unit2/smolagents/quiz1 title: Prueba rápida 1 - local: unit2/smolagents/code_agents title: Construyendo Agentes que Utilizan Código - local: unit2/smolagents/tool_calling_agents title: Escribiendo acciones como snippets de código o bloques JSON - local: unit2/smolagents/tools title: Herramientas - local: unit2/smolagents/retrieval_agents title: Agentes de Recuperación - local: unit2/smolagents/quiz2 title: Prueba rápida 2 - local: unit2/smolagents/multi_agent_systems title: Sistemas de Agentes Multiples - local: unit2/smolagents/vision_agents title: Agentes de Visión y Navegación - local: unit2/smolagents/final_quiz title: Prueba Final - local: unit2/smolagents/conclusion title: Conclusión - title: Unidad 2.2 Framework LlamaIndex sections: - local: unit2/llama-index/introduction title: Introducción a LlamaIndex - local: unit2/llama-index/llama-hub title: Introducción a LlamaHub - local: unit2/llama-index/components title: ¿Qué son Componentes en LlamaIndex? - local: unit2/llama-index/tools title: Utilizando Herramientas en LlamaIndex - local: unit2/llama-index/quiz1 title: Prueba rápida 1 - local: unit2/llama-index/agents title: Utilizando Agentes en LlamaIndex - local: unit2/llama-index/workflows title: Crear flujos Agenticos en LlamaIndex - local: unit2/llama-index/quiz2 title: Prueba rápida 2 - local: unit2/llama-index/conclusion title: Conclusión - title: Unidad 2.3 LangGraph sections: - local: unit2/langgraph/introduction title: Introducción a LangGraph - local: unit2/langgraph/when_to_use_langgraph title: ¿Qué es LangGraph? - local: unit2/langgraph/building_blocks title: Componentes de LangGraph - local: unit2/langgraph/first_graph title: Construyendo Tu Primer LangGraph - local: unit2/langgraph/document_analysis_agent title: Grafo de Análisis de Documentos - local: unit2/langgraph/quiz1 title: Prueba rápida 1 - local: unit2/langgraph/conclusion title: Conclusión - title: Unidad 3. Caso de Uso para Agentic RAG sections: - local: unit3/agentic-rag/introduction title: Introducción al Caso de Uso para Agentic RAG - local: unit3/agentic-rag/agentic-rag title: Agentic Retrieval Augmented Generation (RAG) - local: unit3/agentic-rag/invitees title: Creando una herramienta RAG para historias de invitados - local: unit3/agentic-rag/tools title: Construyendo y integrando herramientas para tu agente - local: unit3/agentic-rag/agent title: Creando tu agente de gala - local: unit3/agentic-rag/conclusion title: Conclusión - title: Unidad Bonus 1. Fine-tuning de un LLM para Llamadas a Funciones sections: - local: bonus-unit1/introduction title: Introducción - local: bonus-unit1/what-is-function-calling title: ¿Qué es la Llamada a Funciones? - local: bonus-unit1/fine-tuning title: Hagamos Fine-Tuning de Tu Modelo para Llamadas a Funciones - local: bonus-unit1/conclusion title: Conclusión - title: Unidad 4. Proyecto Final - Crear, Probar y Certificar tu Agente sections: - local: unit4/introduction title: Introducción a la unidad final - local: unit4/what-is-gaia title: ¿Qué es GAIA? - local: unit4/hands-on title: El último Hands-On - local: unit4/get-your-certificate title: Obtén tu certificado de Excelencia - local: unit4/conclusion title: Conclusión del curso - local: unit4/additional-readings title: ¿Qué más deberías aprender? - title: Unidad Bonus 2. Observabilidad y Evaluación de Agentes sections: - local: bonus-unit2/introduction title: Introducción - local: bonus-unit2/what-is-agent-observability-and-evaluation title: ¿Qué es la observabilidad y evaluación de agentes? - local: bonus-unit2/monitoring-and-evaluating-agents-notebook title: Monitorear y Evaluar Agentes - local: bonus-unit2/quiz title: Prueba - title: Bonus Unit 3. Agentes en Juegos con Pokémon sections: - local: bonus-unit3/introduction title: Introducción - local: bonus-unit3/state-of-art title: El Estado del Arte en el Uso de LLMs en Juegos - local: bonus-unit3/from-llm-to-agents title: De LLMs a Agentes - local: bonus-unit3/building_your_pokemon_agent title: Construye tu propio Agente Pokémon - local: bonus-unit3/launching_agent_battle title: Lanzar tu Agente Pokémon - local: bonus-unit3/conclusion title: Conclusión
agents-course/units/es/_toctree.yml/0
{ "file_path": "agents-course/units/es/_toctree.yml", "repo_id": "agents-course", "token_count": 2426 }
5
# (Opcional) Discord 101 [[discord-101]] <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/discord-etiquette.jpg" alt="La Etiqueta de Discord" width="100%"/> Esta guía está diseñada para ayudarte a comenzar a utilizar Discord, una plataforma de chat gratuita popular en las comunidades de gaming e IA. Únete al servidor de Discord de la Comunidad Hugging Face, que **tiene más de 100,000 miembros**, haciendo clic <a href="https://discord.gg/UrrTSsSyjb" target="_blank">aquí</a>. ¡Es un gran lugar para conectar con otros! ## El curso de Agentes en la Comunidad Discord de Hugging Face Comenzar en Discord puede ser un poco abrumador, así que aquí hay una guía rápida para ayudarte a navegar. <!-- Ya no es el caso, se te pedirá que elijas tus intereses. Asegúrate de seleccionar **"AI Agents"** para obtener acceso a la Categoría de Agentes de IA, que incluye todos los canales relacionados con el curso. ¡Siéntete libre de explorar y unirte a canales adicionales si lo deseas! 🚀--> El Servidor de la Comunidad HF alberga una comunidad vibrante con intereses en varias áreas, ofreciendo oportunidades de aprendizaje a través de discusiones de papers, eventos y más. Después de [registrarte](http://hf.co/join/discord), preséntate en el canal `#introduce-yourself`. Hemos creado 4 canales para el Curso de Agentes: - `agents-course-announcements`: para las **últimas actualizaiones del curso**. - `🎓-agents-course-general`: para **discusiones generales y charlas**. - `agents-course-questions`: para **hacer preguntas y ayudar a tus compañeros**. - `agents-course-showcase`: para **mostrar tus mejores agentes**. Además, puedes consultar: - `smolagents`: para **discusión y soporte con la biblioteca**. ## Consejos para usar Discord de manera efectiva ### Cómo unirse a un servidor Si estás menos familiarizado con Discord, quizás quieras consultar esta <a href="https://support.discord.com/hc/en-us/articles/360034842871-How-do-I-join-a-Server#h_01FSJF9GT2QJMS2PRAW36WNBS8" target="_blank">guía</a> sobre cómo unirte a un servidor. Aquí hay un resumen rápido de los pasos: 1. Haz clic en el <a href="https://discord.gg/UrrTSsSyjb" target="_blank">Enlace de Invitación</a>. 2. Inicia sesión con tu cuenta de Discord, o crea una cuenta si no tienes una. 3. ¡Valida que no eres un agente de IA! 4. Configura tu apodo y avatar. 5. Haz clic en "Unirse al Servidor". ### Cómo usar Discord de manera efectiva Aquí hay algunos consejos para usar Discord de manera efectiva: - Los **canales de voz** están disponibles, aunque el chat de texto se usa más comúnmente. - Puedes formatear texto usando **estilo markdown**, lo cual es especialmente útil para escribir código. Ten en cuenta que markdown no funciona tan bien para enlaces. - Considera abrir hilos para **conversaciones largas** para mantener las discusiones organizadas. Esperamos que encuentres esta guía útil. Si tienes alguna pregunta, no dudes en preguntarnos en Discord 🤗.
agents-course/units/es/unit0/discord101.mdx/0
{ "file_path": "agents-course/units/es/unit0/discord101.mdx", "repo_id": "agents-course", "token_count": 1130 }
6
# Vamos Crear Nuestro Primer Agente Usando smolagents En la última sección, aprendimos cómo podemos crear Agentes desde cero usando código Python, y **vimos lo tedioso que puede ser ese proceso**. Afortunadamente, muchas librerías de Agentes simplifican este trabajo **manejando gran parte del trabajo pesado por ti**. En este tutorial, **crearás tu primer Agente** capaz de realizar acciones como generación de imágenes, búsqueda web, verificación de zonas horarias y mucho más. También publicarás tu agente **en un Space de Hugging Face para que puedas compartirlo con amigos y colegas**. ¡Comencemos! ## ¿Qué es smolagents? <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/smolagents.png" alt="smolagents"/> Para crear este Agente, vamos a usar `smolagents`, una librería que **proporciona un marco para desarrollar tus agentes con facilidad**. Esta librería ligera está diseñada para ser simple, pero abstrae gran parte de la complejidad de construir un Agente, permitiéndote enfocarte en diseño el comportamiento de tu agente. Profundizaremos más en smolagents en la siguiente Unidad. Mientras tanto, también puedes consultar esta <a href="https://huggingface.co/blog/smolagents" target="_blank">publicación del blog</a> o el <a href="https://github.com/huggingface/smolagents" target="_blank">repositorio de la librería en GitHub</a>. En resumen, `smolagents` es una librería que se enfoca en **codeAgent**, un tipo de agente que realiza **"Acciones"** a través de bloques de código, y luego **"Observa"** los resultados ejecutando el código. ¡Aquí un ejemplo de lo que construiremos! Proporcionamos a nuestro agente una **herramienta de generación de imágenes** y le pedimos que genere una imagen de un gato. El agente dentro de `smolagents` va a tener los **mismos comportamientos que el personalizado que construimos anteriormente**: va a **pensar, actuar y observar en ciclo** hasta que llegue a una respuesta final: <iframe width="560" height="315" src="https://www.youtube.com/embed/PQDKcWiuln4?si=ysSTDZoi8y55FVvA" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> Emocionante, ¿cierto? ## ¡Construyamos nuestro Agente! Para comenzar, duplica este Space: <a href="https://huggingface.co/spaces/agents-course/First_agent_template" target="_blank">https://huggingface.co/spaces/agents-course/First_agent_template</a> > ¡Gracias a <a href="https://huggingface.co/m-ric" target="_blank">Aymeric</a> por esta plantilla! 🙌 Duplicar este space significa **crear una copia local en tu propio perfil**: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/duplicate-space.gif" alt="Duplicate"/> A lo largo de esta lección, el único archivo que necesitarás modificar es el (actualmente incompleto) **"app.py"**. Puedes ver aquí el [original en la plantilla](https://huggingface.co/spaces/agents-course/First_agent_template/blob/main/app.py). Para encontrar el tuyo, ve a tu copia del space, luego haz clic en la pestaña `Files` y luego en `app.py` en el listado de directorios. Analicemos el código juntos: - El archivo comienza con algunas importaciones de bibliotecas simples pero necesarias ```python from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool import datetime import requests import pytz import yaml from tools.final_answer import FinalAnswerTool ``` Como se describió anteriormente, usaremos directamente la clase **CodeAgent** de **smolagents**. ### Las Herramientas ¡Ahora vamos con las herramientas! Si quieres un repaso sobre las herramientas, no dudes en volver a la sección [Herramientas](tools) del curso. ```python @tool def my_custom_tool(arg1:str, arg2:int)-> str: # es importante especificar el tipo que se regresara # Mantén este formato para la descripción de la herramienta / descripción de args pero siéntete libre de modificar la herramienta """Una herramienta que aun no hace nada Args: arg1: el primer argumento arg2: el segundo argumento """ return "¿Qué magia construirás?" @tool def get_current_time_in_timezone(timezone: str) -> str: """Una herramienta que obtiene la hora local actual en una zona horaria especificada. Args: timezone: Una cadena que representa una zona horaria válida (por ejemplo, 'America/New_York'). """ try: # Crear objeto de zona horaria tz = pytz.timezone(timezone) # Obtener la hora actual en esa zona horaria local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") return f"La hora local actual en {timezone} es: {local_time}" except Exception as e: return f"Error al obtener la hora para la zona horaria '{timezone}': {str(e)}" ``` Las Herramientas son lo que te estamos animando a construir en esta sección. Te damos dos ejemplos: 1. Una **Herramienta ficticia que no funciona** que puedes modificar para hacer algo útil. 2. Una **Herramienta que realmente funciona** que obtiene la hora actual en algún lugar del mundo. Para definir tu herramienta es importante: 1. Proporcionar tipos de entrada y salida para tu función, como en `get_current_time_in_timezone(timezone: str) -> str:` 2. **Un docstring formateado**. `smolagents` espera que todos los argumentos tengan una **descripción textual en el docstring**. ### El Agente Utiliza [`Qwen/Qwen2.5-Coder-32B-Instruct`](https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct) como motor LLM. Este es un modelo muy capaz al que accederemos a través de la API sin servidor. ```python final_answer = FinalAnswerTool() model = InferenceClientModel( max_tokens=2096, temperature=0.5, model_id='Qwen/Qwen2.5-Coder-32B-Instruct', custom_role_conversions=None, ) with open("prompts.yaml", 'r') as stream: prompt_templates = yaml.safe_load(stream) # Estamos creando nuestro CodeAgent agent = CodeAgent( model=model, tools=[final_answer], # añade tus herramientas aquí (no elimines final_answer) max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) GradioUI(agent).launch() ``` ¡Este Agente todavía usa el `InferenceClient` que vimos en una sección anterior detrás de la clase **InferenceClientModel**! Daremos ejemplos más detallados cuando presentemos el marco en la Unidad 2. Por ahora, debes enfocarte en **agregar nuevas herramientas a la lista de herramientas** usando el parámetro `tools` de tu Agente. Por ejemplo, podrías usar el `DuckDuckGoSearchTool` que se importó en la primera línea del código, o puedes examinar el `image_generation_tool` que se carga desde el Hub más adelante en el código. **Agregar herramientas le dará a tu agente nuevas capacidades**, ¡intenta ser creativo aquí! El "app.py" completo: ```python from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool import datetime import requests import pytz import yaml from tools.final_answer import FinalAnswerTool from Gradio_UI import GradioUI # A continuación hay un ejemplo de una herramienta que no hace nada. ¡Sorpréndenos con tu creatividad! @tool def my_custom_tool(arg1:str, arg2:int)-> str: # es importante especificar el tipo de retorno # Mantén este formato para la descripción de la herramienta / descripción de args pero siéntete libre de modificar la herramienta """Una herramienta que aún no hace nada Args: arg1: el primer argumento arg2: el segundo argumento """ return "¿Qué magia construirás?" @tool def get_current_time_in_timezone(timezone: str) -> str: """Una herramienta que obtiene la hora local actual en una zona horaria especificada. Args: timezone: Una cadena que representa una zona horaria válida (por ejemplo, 'America/New_York'). """ try: # Crear objeto de zona horaria tz = pytz.timezone(timezone) # Obtener la hora actual en esa zona horaria local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") return f"La hora local actual en {timezone} es: {local_time}" except Exception as e: return f"Error al obtener la hora para la zona horaria '{timezone}': {str(e)}" final_answer = FinalAnswerTool() model = InferenceClientModel( max_tokens=2096, temperature=0.5, model_id='Qwen/Qwen2.5-Coder-32B-Instruct', custom_role_conversions=None, ) # Importar herramienta desde Hub image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) with open("prompts.yaml", 'r') as stream: prompt_templates = yaml.safe_load(stream) agent = CodeAgent( model=model, tools=[final_answer], # añade tus herramientas aquí (no elimines final_answer) max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) GradioUI(agent).launch() ``` Tu **Objetivo** es familiarizarte con el Space y el Agente. Actualmente, el agente en la plantilla **no utiliza ninguna herramienta, así que intenta proporcionarle algunas de las prefabricadas o incluso crear algunas herramientas nuevas tú mismo.** ¡Estamos esperando ansiosamente tus increíbles resultados de agentes en el canal de Discord **#agents-course-showcase**! --- ¡Felicidades, has construido tu primer Agente! No dudes en compartirlo con tus amigos y colegas. Como este es tu primer intento, es perfectamente normal si es un poco inestable o lento. En futuras unidades, aprenderemos cómo construir Agentes aún mejores. La mejor manera de aprender es intentarlo, así que no dudes en actualizarlo, agregar más herramientas, probar con otro modelo, etc. En la siguiente sección, completarás el Quiz final y obtendrás tu certificado.
agents-course/units/es/unit1/tutorial.mdx/0
{ "file_path": "agents-course/units/es/unit1/tutorial.mdx", "repo_id": "agents-course", "token_count": 3818 }
7
# Introducción a LlamaHub **LlamaHub es un registro de cientos de integraciones, agentes y herramientas que puedes utilizar dentro de LlamaIndex.** ![LlamaHub](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/llama-hub.png) Vamos a utilizar varias integraciones en este curso, así que primero echaremos un vistazo a LlamaHub y veremos cómo puede ayudarnos. Vamos a ver cómo encontrar e instalar las dependencias para los componentes que necesitamos. ## Instalación Las instrucciones de instalación de LlamaIndex están disponibles en **[LlamaHub](https://llamahub.ai/)**. Puede parecer un poco abrumador al principio, pero la mayoría de los comandos de **instalación siguen un formato fácil de recordar **: ```bash pip install llama-index-{component-type}-{framework-name} ``` Vamos a intentar instalar las dependencias para un componente de LLM utilizando la [integración de la API de inferencia de Hugging Face](https://llamahub.ai/l/llms/llama-index-llms-huggingface-api?from=llms). ```bash pip install llama-index-llms-huggingface-api ``` ## Uso Una vez instalado, podemos ver los patrones de uso. Notaras que los caminos de importación siguen el comando de instalación! Debajo, podemos ver un ejemplo de la utilización de **la API de inferencia de Hugging Face para un componente LLM**. ```python from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI llm = HuggingFaceInferenceAPI( model_name="Qwen/Qwen2.5-Coder-32B-Instruct", temperature=0.7, max_tokens=100, token="hf_xxx", ) llm.completar(" Hola, cómo estás?") # Estoy bien, ¿cómo puedo ayudarte hoy? ``` Genial, ahora sabemos como encontrar, instalar y utilizar las integraciones para los componentes que necesitamos. **Vamos a profundizar en los componentes** y veremos como podemos utilizarlos para construir nuestros propios agentes.
agents-course/units/es/unit2/llama-index/llama-hub.mdx/0
{ "file_path": "agents-course/units/es/unit2/llama-index/llama-hub.mdx", "repo_id": "agents-course", "token_count": 728 }
8
![smolagents banner](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/license_to_call.png) # ¿Por qué usar smolagents? En este módulo, exploraremos los pros y contras de usar [smolagents](https://huggingface.co/docs/smolagents/en/index), ayudándote a tomar una decisión informada sobre si es el framework adecuado para tus necesidades. ## ¿Qué es `smolagents`? `smolagents` es un framework simple pero potente para construir agentes de IA. Proporciona a los LLMs la _capacidad de acción_ para interactuar con el mundo real, como buscar o generar imágenes. Como aprendimos en la unidad 1, los agentes de IA son programas que utilizan LLMs para generar **'pensamientos'** basados en **'observaciones'** para realizar **'acciones'**. Exploremos cómo se implementa esto en smolagents. ### Ventajas clave de `smolagents` - **Simplicidad:** Mínima complejidad de código y abstracciones, para hacer que el framework sea fácil de entender, adoptar y extender - **Soporte flexible para LLM:** Funciona con cualquier LLM a través de la integración con herramientas de Hugging Face y APIs externas - **Enfoque centrado en el código:** Soporte de primera clase para Agentes de Código que escriben sus acciones directamente en código, eliminando la necesidad de análisis y simplificando la llamada a herramientas - **Integración con HF Hub:** Integración perfecta con Hugging Face Hub, permitiendo el uso de Espacios Gradio como herramientas ### ¿Cuándo usar smolagents? Con estas ventajas en mente, ¿cuándo deberíamos usar smolagents en lugar de otros frameworks? smolagents es ideal cuando: - Necesitas una **solución ligera y mínima.** - Quieres **experimentar rápidamente** sin configuraciones complejas. - La **lógica de tu aplicación es sencilla.** ### Acciones de Código vs. JSON A diferencia de otros frameworks donde los agentes escriben acciones en JSON, `smolagents` **se centra en llamadas a herramientas en código**, simplificando el proceso de ejecución. Esto se debe a que no hay necesidad de analizar el JSON para construir código que llame a las herramientas: la salida puede ejecutarse directamente. El siguiente diagrama ilustra esta diferencia: ![Acciones de Código vs. JSON](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png) Para revisar la diferencia entre Acciones de Código vs Acciones JSON, puedes volver a visitar [la Sección de Acciones en la Unidad 1](https://huggingface.co/learn/agents-course/unit1/actions#actions-enabling-the-agent-to-engage-with-its-environment). ### Tipos de Agentes en `smolagents` Los agentes en `smolagents` operan como **agentes de múltiples pasos**. Cada [`MultiStepAgent`](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.MultiStepAgent) realiza: - Un pensamiento - Una llamada a herramienta y ejecución Además de usar **[CodeAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.CodeAgent)** como el tipo principal de agente, smolagents también soporta **[ToolCallingAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.ToolCallingAgent)**, que escribe llamadas a herramientas en JSON. Exploraremos cada tipo de agente con más detalle en las siguientes secciones. <Tip> En smolagents, las herramientas se definen usando el decorador <code>@tool</code> que envuelve una función de Python o la clase <code>Tool</code>. </Tip> ### Integración de Modelos en `smolagents` `smolagents` soporta una integración flexible de LLM, permitiéndote usar cualquier modelo invocable que cumpla con [ciertos criterios](https://huggingface.co/docs/smolagents/main/en/reference/models). El framework proporciona varias clases predefinidas para simplificar las conexiones de modelos: - **[TransformersModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.TransformersModel):** Implementa un pipeline local de `transformers` para una integración perfecta. - **[InferenceClientModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.InferenceClientModel):** Soporta llamadas de [inferencia sin servidor](https://huggingface.co/docs/huggingface_hub/main/en/guides/inference) a través de la [infraestructura de Hugging Face](https://huggingface.co/docs/api-inference/index), o a través de un número creciente de [proveedores de inferencia de terceros](https://huggingface.co/docs/huggingface_hub/main/en/guides/inference#supported-providers-and-tasks). - **[LiteLLMModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.LiteLLMModel):** Aprovecha [LiteLLM](https://www.litellm.ai/) para interacciones ligeras con modelos. - **[OpenAIServerModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.OpenAIServerModel):** Se conecta a cualquier servicio que ofrezca una interfaz de API de OpenAI. - **[AzureOpenAIServerModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.AzureOpenAIServerModel):** Soporta la integración con cualquier despliegue de Azure OpenAI. Esta flexibilidad asegura que los desarrolladores puedan elegir el modelo y servicio más adecuados para sus casos de uso específicos, y permite una fácil experimentación. Ahora que hemos entendido por qué y cuándo usar smolagents, ¡profundicemos en esta poderosa biblioteca! ## Recursos - [Blog de smolagents](https://huggingface.co/blog/smolagents) - Introducción a smolagents e interacciones de código
agents-course/units/es/unit2/smolagents/why_use_smolagents.mdx/0
{ "file_path": "agents-course/units/es/unit2/smolagents/why_use_smolagents.mdx", "repo_id": "agents-course", "token_count": 1992 }
9
# Conclusion [[conclusion]] Félicitations pour avoir terminé cette première Unité Bonus 🥳 Vous **maîtrisez la compréhension de l'appel de fonctions et comment finetuner votre modèle sur cette tâche** ! Nous vous conseillons à présent d'essayer de **finetuner différents modèles**. La **meilleure façon d'apprendre est en testant des choses.** Dans la prochaine Unité, vous allez apprendre comment utiliser **des *frameworks* de pointe tels que `smolagents`, `LlamaIndex` et `LangGraph`**. Enfin, nous serions ravis **d'entendre ce que vous pensez du cours et comment nous pourrions l'améliorer**. Si vous avez des retours, n'hésitez pas à 👉 [remplir ce formulaire](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog). ### Continuez à apprendre, restez géniaux 🤗
agents-course/units/fr/bonus-unit1/conclusion.mdx/0
{ "file_path": "agents-course/units/fr/bonus-unit1/conclusion.mdx", "repo_id": "agents-course", "token_count": 331 }
10
# Bienvenue dans le cours 🤗 [[introduction]] <figure> <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/thumbnail.jpg" alt="Vignette du cours AI Agents" width="100%"/> <figcaption>L'arrière-plan de l'image a été généré à l'aide de <a href="https://scenario.com/">Scenario.com</a> </figcaption> </figure> Bienvenue dans le sujet le plus passionnant de l'IA aujourd'hui : les **Agents** ! Ce cours gratuit vous guidera, du **niveau débutant à expert**, pour comprendre, utiliser et construire des agents. Cette première unité va vous aider à démarrer : - Découvrez le **programme du cours**. - **Choisissez le parcours** que vous souhaitez suivre (soit en autoformation, soit en suivant le processus de certification). - **Obtenez plus d'informations sur le processus de certification**. - Faites connaissance avec l'équipe derrière le cours. - Créez votre **compte Hugging Face**. - **Inscrivez-vous à notre serveur Discord** pour rencontrez vos camarades ainsi que nous. Commençons ! ## Que pouvez-vous attendre de ce cours ? [[expect]] Dans ce cours, vous allez : - 📖 Étudier les agents en IA par la **théorie, la conception et la pratique**. - 🧑‍💻 Apprendre à **utiliser des bibliothèques établies** telles que [smolagents](https://huggingface.co/docs/smolagents/en/index), [LlamaIndex](https://www.llamaindex.ai/), et [LangGraph](https://langchain-ai.github.io/langgraph/). - 💾 **Partager vos agents** sur le Hub d'Hugging Face et explorer les agents créés par la communauté. - 🏆 Participer à des défis où vous **évaluerez vos agents face à ceux des autres étudiants**. - 🎓 **Obtenir un certificat de réussite** en complétant les exercices. Et bien plus encore ! À la fin de ce cours, vous comprendrez **comment fonctionnent les agents et comment construire les votres en utilisant les dernières bibliothèques et outils**. N'oubliez pas de **<a href="https://bit.ly/hf-learn-agents">vous inscrire au cours !</a>** (Nous respectons votre vie privée. Nous collectons votre adresse email afin de pouvoir **vous envoyer les liens dès que chaque unité est publiée et vous fournir des informations sur les challenges et les mises à jour**.) ## À quoi ressemble le cours ? [[course-look-like]] Le cours structuré en : - *Unités fondamentales* : où vous apprenez les **concepts théoriques des agents**. - *Sessions pratiques* : où vous apprendrez **à utiliser des bibliothèques d'agents existantes** pour entraîner vos agents dans des environnements uniques. Ces sessions pratiques se feront dans des **Spaces** avec un environnement préconfiguré. - *Exercices basés sur des cas d'utilisation* : où vous appliquerez les concepts appris pour résoudre un problème réel de votre choix. - *Défis* : vous mettrez votre agent en compétition face à d'autres dans le cadre d'un *challenge*. Le tout sera suivi dans [un classement](https://huggingface.co/spaces/agents-course/Students_leaderboard) pour comparer les performances. Ce **cours est un projet vivant, évoluant avec vos retours et contributions !** N'hésitez pas à [ouvrir des *issues* et des PR sur GitHub](https://github.com/huggingface/agents-course) et à participer aux discussions sur notre serveur Discord. Après avoir suivi le cours, vous pouvez également nous envoyer vos retours [👉 via ce formulaire](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog). ## Quel est le programme ? [[syllabus]] Voici le **programme général du cours**. Une liste plus détaillée des sujets sera publiée avec chaque unité. | Chapitre | Sujet | Description | | :---- | :---- | :---- | | 0 | Intégration | Vous familiariser avec les outils et plateformes que vous utiliserez. | | 1 | Fondamentaux | Expliquer les outils, le raisonnement, les actions, les observations et leurs formats. Aborder les LLM, les messages, les *tokens* spéciaux et les patrons de chat. Présenter un cas d'usage simple en utilisant des fonctions Python comme outils. | | 2 | *Frameworks* | Comprendre comment les fondamentaux sont implémentés dans des bibliothèques populaires : smolagents, LangGraph et LlamaIndex | | 3 | Cas d'utilisation | Construire quelques cas d'utilisation réels | | 4 | Projet final | Construire un agent pour un *benchmark* sélectionné afin de démontrer votre compréhension des agents à travers le classement étudiant 🚀 | En plus du programme principal, il y a 3 unités bonus : - *Unité Bonus 1* : Finetuner un LLM pour l'appel de fonctions - *Unité Bonus 2* : Observabilité et évaluation des agents - *Unité Bonus 3* : Les agents dans les jeux vidéos via Pokemon Par exemple, dans l'Unité Bonus 3, vous apprendrez à construire votre agent pour jouer aux combats Pokemon 🥊. ## Quels sont les prérequis ? Pour pouvoir suivre ce cours, vous devez avoir : - Une connaissance de base de Python - Une connaissance de base des LLM (nous avons une section de rappel dans l'Unité 1) ## De quels outils ai-je besoin ? [[tools]] Vous n'avez besoin que de 2 choses : - Un *ordinateur* avec une connexion internet. - Un *compte Hugging Face* pour pousser et charger des modèles, des agents, et créer des *Spaces*. Si vous n'avez pas encore de compte, vous pouvez en créer un **[ici](https://hf.co/join)** (c'est gratuit). <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/tools.jpg" alt="Outils nécessaires pour le cours" width="100%"/> ## Le processus de certification [[certification-process]] <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/three-paths.jpg" alt="Deux voies" width="100%"/> Vous pouvez choisir de suivre ce cours en *mode auditeur libre* ou de réaliser les activités et *obtenir l'un des deux certificats que nous délivrerons*. Si vous suivez le cours en auditeur libre, vous pouvez participer à tous les défis et faire les exercices si vous le souhaitez sans avoir **besoin de nous en informer**. Le processus de certification est **entièrement gratuit** : - *Pour obtenir une certification des fondamentaux* : vous devez compléter l'Unité 1 du cours. Cela est destiné aux étudiants qui souhaitent se tenir à jour avec les dernières tendances en matière d'agents. - *Pour obtenir un certificat de réussite* : vous devez compléter l'Unité 1, l'un des exercices de cas d'utilisation que nous proposerons pendant le cours, ainsi que le défi final. Il n'y a **pas de date limite** pour le processus de certification. ## Quel est le rythme recommandé ? [[recommended-pace]] Chaque chapitre de ce cours est conçu **pour être complété en 1 semaine, avec environ 3 à 4 heures de travail par semaine**. Nous vous proposons un rythme recommandé : <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/recommended-pace.jpg" alt="Rythme recommandé" width="100%"/> ## Comment tirer le meilleur parti du cours ? [[advice]] Pour tirer le meilleur parti du cours, nous vous donnons quelques conseils : 1. <a href="https://discord.gg/UrrTSsSyjb">Rejoignez des groupes d'étude sur Discord</a> : étudier en groupe est toujours plus facile. Pour cela, vous devez rejoindre notre serveur Discord et vérifier votre compte Hugging Face. 2. **Faites les quiz et les exercices** : la meilleure façon d'apprendre est par la pratique et l'auto-évaluation. 3. **Définissez un planning pour rester en phase** : vous pouvez utiliser notre planning de rythme recommandé ci-dessous ou créer le vôtre. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/advice.jpg" alt="Conseils pour le cours" width="100%"/> ## Qui sommes-nous ? [[who-are-we]] Ce cours est maintenu par [Ben Burtenshaw](https://huggingface.co/burtenshaw) et [Sergio Paniego](https://huggingface.co/sergiopaniego). Si vous avez des questions, contactez-nous sur le Hub ! ## Remerciements Nous tenons à exprimer notre gratitude aux personnes suivantes pour leurs contributions inestimables à ce cours : - **[Joffrey Thomas](https://huggingface.co/Jofthomas)** - Pour la rédaction et le développement du cours. - **[Thomas Simonini](https://huggingface.co/ThomasSimonini)** - Pour la rédaction et le développement du cours. - **[Pedro Cuenca](https://huggingface.co/pcuenq)** - Pour avoir guidé le cours et fourni des *feedbacks*. - **[Aymeric Roucher](https://huggingface.co/m-ric)** - Pour ses incroyables *Spaces* de démonstration (décodage et agent final) ainsi que son aide sur les parties sur smolagents. - **[Joshua Lochner](https://huggingface.co/Xenova)** - Pour son incroyable *Space* de démonstration sur la tokenisation. - **[Quentin Gallouédec](https://huggingface.co/qgallouedec)** - Pour son aide sur le contenu du cours. - **[David Berenstein](https://huggingface.co/davidberenstein1957)** - Pour son aide sur le contenu du cours et la modération. - **[XiaXiao (ShawnSiao)](https://huggingface.co/SSSSSSSiao)** - Traducteur de la version chinoise du cours. - **[Jiaming Huang](https://huggingface.co/nordicsushi)** - Traducteur de la version chinoise du cours. - **[Kim Noel](https://github.com/knoel99)** - Traducteur de la version française du cours. - **[Loïck Bourdois](https://huggingface.co/lbourdois)** - Traducteur de la version française du cours via le [CATIE](https://www.catie.fr/). ## J'ai trouvé un bug, ou je souhaite améliorer le cours [[contribute]] Les contributions sont **les bienvenues** 🤗 - Si vous *avez trouvé un bug 🐛 dans un notebook*, veuillez <a href="https://github.com/huggingface/agents-course/issues">ouvrir une *issue*</a> et **décrire le problème**. - Si vous *souhaitez améliorer le cours*, vous pouvez <a href="https://github.com/huggingface/agents-course/pulls">ouvrir une *Pull Request*</a>. - Si vous *voulez ajouter une section complète ou une nouvelle unité*, le mieux est d'ouvrir <a href="https://github.com/huggingface/agents-course/issues">une *issue*</a> et **décrire le contenu que vous souhaitez ajouter avant de commencer à l'écrire afin que nous puissions vous guider**. ## J'ai encore des questions [[questions]] Veuillez poser vos questions sur notre <a href="https://discord.gg/UrrTSsSyjb">serveur Discord dans la section #agents-course-questions</a>. Maintenant que vous avez toutes les informations, embarquons ⛵ <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/time-to-onboard.jpg" alt="Il est temps de démarrer" width="100%"/>
agents-course/units/fr/unit0/introduction.mdx/0
{ "file_path": "agents-course/units/fr/unit0/introduction.mdx", "repo_id": "agents-course", "token_count": 3786 }
11
# Qu'est-ce qu'un agent ? <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-no-check.jpg" alt="Planification de l'Unité 1"/> À la fin de cette section, vous vous sentirez à l'aise avec le concept d'agents et leurs diverses applications an IA. Pour expliquer ce qu'est un agent, commençons par une analogie. ## La vue d'ensemble : Alfred l'Agent Voici Alfred. Alfred est un **Agent**. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/this-is-alfred.jpg" alt="Voici Alfred"/> Imaginez qu'Alfred **reçoive une commande**, par exemple : « Alfred, je voudrais un café s'il te plaît. » <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/coffee-please.jpg" alt="Je voudrais un café"/> Parce qu'Alfred **comprend le langage naturel**, il saisit rapidement notre demande. Avant de satisfaire la commande, Alfred se livre au **raisonnement et à la planification**, déterminant les étapes et les outils dont il a besoin pour : 1. Aller à la cuisine 2. Utiliser la machine à café 3. Préparer le café 4. Ramener le café <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/reason-and-plan.jpg" alt="Raisonnement et planification"/> Une fois qu'il a établi un plan, il **doit agir**. Pour exécuter son plan, **il peut utiliser les outils qu'il connaît**. Dans ce cas, pour préparer un café, il utilise une machine à café. Il active la machine à café pour préparer le café. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/make-coffee.jpg" alt="Préparer le café"/> Enfin, Alfred nous apporte le café fraîchement préparé. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/bring-coffee.jpg" alt="Apporter le café"/> Et voilà ce qu'est un agent : un **modèle capable de raisonner, de planifier et d'interagir avec son environnement**. On l'appelle agent parce qu'il possède la capacité d'agir, autrement dit, il peut interagir avec l'environnement. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/process.jpg" alt="Agent process"/> ## Soyons plus formels Maintenant que vous avez une vue d'ensemble, voici une définition plus précise : > Un Agent est un système qui utilise un modèle d'IA pour interagir avec son environnement afin d'atteindre un objectif défini par l'utilisateur. Il combine le raisonnement, la planification et l'exécution d'actions (souvent via des outils externes) pour accomplir des tâches. Pensez à l'agent comme ayant deux parties principales : 1. **Le Cerveau (modèle d'IA)** C'est là que toute la réflexion se passe. Le modèle **gère le raisonnement et la planification**. Il décide **quelles Actions entreprendre en fonction de la situation**. 2. **Le Corps (Capacités et Outils)** Cette partie représente **tout ce avec quoi l'agent est équipé**. La **portée des actions possibles** dépend de ce avec quoi l'agent **a été équipé**. Par exemple, comme les humains n'ont pas d'ailes, ils ne peuvent pas effectuer l'**action** « voler », mais ils peuvent exécuter des **actions** comme « marcher », « courir », « sauter », « saisir », etc. ### Le spectre de la capacité à agir Suivant cette définition, les agents existent sur un spectre de capacité d'action croissante : | Niveau de capacité | Description | Comment ça s'appelle | Exemple de modèle | | --- | --- | --- | --- | | ☆☆☆ | La sortie de l'agent n'a aucun impact sur le flux du programme | Processeur simple | `process_llm_output(llm_response)` | | ★☆☆ | La sortie de l'agent détermine le flux de contrôle de base | Routeur | `if llm_decision(): path_a() else: path_b()` | | ★★☆ | La sortie de l'agent détermine l'exécution de la fonction | Appeleur d'outils | `run_function(llm_chosen_tool, llm_chosen_args)` | | ★★★ | La sortie de l'agent contrôle l'itération et la continuation du programme | Agent multi-étapes | `while llm_should_continue(): execute_next_step()` | | ★★★ | Un flux de travail agentique peut en démarrer un autre | Multi-Agent | `if llm_trigger(): execute_agent()` | Tableau tiré du [guide conceptuel de smolagents](https://huggingface.co/docs/smolagents/conceptual_guides/intro_agents). ## Quel type de modèles d'IA utilisons-nous pour les agents ? Le modèle d'IA le plus courant dans les agents est un LLM (*Large Language Model*) qui prend du **texte** en entrée et produit du **texte** en sortie. Des exemples bien connus sont **GPT4** d'**OpenAI**, **LLama** de **Meta**, **Gemini** de **Google**, etc. Ces modèles ont été entraînés sur une vaste quantité de texte et sont capables de bien généraliser. Nous nous focaliserons davantage sur les LLM dans la [section suivante](what-are-llms). <Tip> Il est également possible d'utiliser des modèles qui acceptent d'autres entrées comme modèle central de l'agent. Par exemple, un <i>Vision Language Model</i> (VLM), qui est comme un LLM mais comprend aussi les images en entrée. Nous nous concentrerons sur les LLM pour l'instant et discuterons d'autres options plus tard. </Tip> ## Comment une IA peut-elle agir sur son environnement ? Les LLM sont des modèles incroyables, mais **ils ne peuvent générer que du texte**. Cependant, si vous demandez à une application de chat bien connue comme HuggingChat (interrompu) ou ChatGPT de générer une image, elle le peut ! Comment cela est-il possible ? La réponse est que les développeurs de ChatGPT et d'applications similaires ont implémenté des fonctionnalités supplémentaires (appelées **Outils**), que le LLM peut utiliser pour créer des images. <figure> <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/eiffel_brocolis.jpg" alt="Tour Eiffel en brocolis"/> <figcaption>Le modèle a utilisé un outil de génération d'images pour générer cette image. </figcaption> </figure> Nous en apprendrons plus sur les outils dans la section [Outils](tools). ## Quel type de tâches un agent peut-il accomplir ? Un agent peut effectuer n'importe quelle tâche que nous implémentons via des **outils** pour compléter des **actions**. Par exemple, si j'écris un agent pour qu'il agisse comme mon assistant personnel (à la Siri) sur mon ordinateur, et que je lui demande « d'envoyer un courriel à mon directeur pour lui demander de reporter la réunion d'aujourd'hui », je peux lui donner du code pour envoyer des courriels. Il s'agira d'un nouvel outil que l'agent pourra utiliser chaque fois qu'il aura besoin d'envoyer un courriel. Nous pouvons l'écrire en Python : ```python def send_message_to(recipient, message): """Utile pour envoyer un message e-mail à un destinataire""" ... ``` Le LLM, comme nous le verrons, générera du code pour exécuter l'outil quand il en aura besoin, et ainsi accomplir la tâche désirée. ```python send_message_to("Manager", "Pouvons-nous reporter la réunion d'aujourd'hui ?") ``` La **conception des outils est très importante et a un grand impact sur la qualité de votre agent**. Certaines tâches en nécessiteront d'en créer des très spécifiques, tandis que d'autres peuvent être résolues avec des outils à usage général comme "web_search". > Notez que **les actions ne sont pas la même chose que les outils**. Une action peut par exemple impliquer l'utilisation de plusieurs outils pour être complétée. Autoriser à un agent d'interagir avec son environnement **permet une utilisation réelle pour les entreprises et les particuliers**. ### Exemple 1 : Assistants Virtuels Personnels Les assistants virtuels tels que Siri, Alexa ou Google Assistant fonctionnent comme des agents lorsqu'ils interagissent au nom des utilisateurs dans leur environnement numérique. Ils répondent aux demandes des utilisateurs, analysent le contexte, récupèrent des informations dans des bases de données et fournissent des réponses ou lancent des actions (comme l'établissement de rappels, l'envoi de messages ou le contrôle d'appareils intelligents). ### Exemple 2 : Chatbots de Service Client Beaucoup d'entreprises déploient des chatbots comme agents qui interagissent avec les clients en langage naturel. Ces agents peuvent répondre aux questions, guider les utilisateurs à travers des étapes de dépannage, ouvrir des tickets dans les bases de données internes, ou même compléter des transactions. Leurs objectifs prédéfinis peuvent inclure l'amélioration de la satisfaction utilisateur, la réduction des temps d'attente, ou l'augmentation des taux de conversion des ventes. En interagissant directement avec les clients, en apprenant des dialogues, et en adaptant leurs réponses au fil du temps, ils démontrent les principes fondamentaux d'un agent en action. ### Exemple 3 : Personnage Non-Joueur dans un jeu vidéo Les agents alimentés par des LLM peuvent rendre les Personnages Non-Joueurs (PNJ) plus dynamiques et imprévisibles. Au lieu de suivre des arbres de comportement rigides, ils peuvent **répondre de façon contextuelle, s'adapter aux interactions des joueurs**, et générer des dialogues plus nuancés. Cette flexibilité aide à créer des personnages plus réalistes et engageants qui évoluent aux côtés des actions du joueur. --- Pour résumer, un agent est un système qui utilise un modèle d'IA (typiquement un LLM) comme moteur de raisonnement principal, pour : - **Comprendre le langage naturel :** Interpréter et répondre aux instructions humaines de manière significative. - **Raisonner et planifier :** Analyser l'information, prendre des décisions, et concevoir des stratégies pour résoudre des problèmes. - **Interagir avec son environnement :** Rassembler des informations, entreprendre des actions, et observer les résultats de ces actions. Maintenant que vous avez une bonne compréhension de ce que sont les agents, renforçons votre compréhension avec un court quiz non noté. Après ça, nous plongerons dans le « le cerveau des agents » : les [LLM](what-are-llms).
agents-course/units/fr/unit1/what-are-agents.mdx/0
{ "file_path": "agents-course/units/fr/unit1/what-are-agents.mdx", "repo_id": "agents-course", "token_count": 3519 }
12
# Quiz rapide 1 (non noté) [[quiz1]] Jusqu'à présent, nous avons discuté des *components* et outils clés utilisés dans LlamaIndex. Il est temps de faire un petit quiz, car **se tester soi-même** est la meilleure façon d'apprendre et [d'éviter l'illusion de compétence](https://www.coursera.org/lecture/learning-how-to-learn/illusions-of-competence-BuFzf). Cela vous aidera à trouver **où vous devez renforcer vos connaissances**. Ceci est un quiz optionnel et il n'est pas noté. ### Q1 : Qu'est-ce qu'un `QueryEngine` ? Laquelle des affirmations suivantes décrit le mieux un *component* `QueryEngine` ? <Question choices={[ { text: "Un système qui traite uniquement du texte statique sans aucune capacité de récupération.", explain: "Un <code>QueryEngine</code> doit être capable de récupérer et traiter des informations pertinentes.", }, { text: "Un component qui trouve et récupère des informations pertinentes dans le cadre du processus de RAG.", explain: "Cela capture l'objectif principal d'un <code>QueryEngine</code>.", correct: true }, { text: "Un outil qui ne fait que stocker des embeddings vectoriels sans fonctionnalité de recherche.", explain: "Un <code>QueryEngine</code> fait plus que simplement stocker des embeddings ; il recherche et récupère activement des informations.", }, { text: "Un component qui évalue uniquement la qualité des réponses.", explain: "L'évaluation est séparée de l'objectif principal de récupération du <code>QueryEngine</code>.", } ]} /> --- ### Q2 : Quel est le but des `FunctionTools` ? Pourquoi les <code>FunctionTools</code> sont-ils importants pour un agent ? <Question choices={[ { text: "Pour gérer de grandes quantités de stockage de données.", explain: "Les <code>FunctionTools</code> ne sont pas principalement pour le stockage de données.", }, { text: "Pour convertir des fonctions Python en outils qu'un agent peut utiliser.", explain: "Les <code>FunctionTools</code> enveloppent les fonctions Python pour les rendre accessibles aux agents.", correct: true }, { text: "Pour permettre aux agents de créer des définitions de fonctions aléatoires.", explain: "Les <code>FunctionTools</code> servent l'objectif spécifique de rendre les fonctions disponibles aux agents.", }, { text: "Pour traiter uniquement des données textuelles.", explain: "Les <code>FunctionTools</code> peuvent fonctionner avec différents types de fonctions, pas seulement le traitement de texte.", } ]} /> --- ### Q3 : Que sont les `Toolspecs` dans LlamaIndex ? Quel est l'objectif principal des `Toolspecs` ? <Question choices={[ { text: "Ce sont des components redondants qui n'ajoutent pas de fonctionnalité.", explain: "Les <code>Toolspecs</code> servent un objectif important dans l'écosystème LlamaIndex.", }, { text: "Ce sont des ensembles d'outils créés par la communauté qui étendent les capacités des agents.", explain: "Les <code>Toolspecs</code> permettent à la communauté de partager et réutiliser des outils.", correct: true }, { text: "Ils sont utilisés uniquement pour la gestion mémoire.", explain: "Les <code>Toolspecs</code> concernent la fourniture d'outils, pas la gestion mémoire.", }, { text: "Ils ne fonctionnent qu'avec le traitement de texte.", explain: "Les <code>Toolspecs</code> peuvent inclure différents types d'outils, pas seulement le traitement de texte.", } ]} /> --- ### Q4 : Qu'est-ce qui est requis pour créer un outil ? Quelles informations doivent être incluses lors de la création d'un outil ? <Question choices={[ { text: "Une fonction, un nom et une description doivent être définis.", explain: "Bien que tous ceux-ci constituent un outil, le nom et la description peuvent être analysés à partir de la fonction et de la <i>docstring</i>.", }, { text: "Seul le nom est requis.", explain: "Une fonction et une description/<i>docstring</i> sont également requises pour une documentation appropriée de l'outil.", }, { text: "Seule la description est requise.", explain: "Une fonction est requise pour que nous ayons du code à exécuter quand un agent sélectionne un outil", }, { text: "Seule la fonction est requise.", explain: "Le nom et la description sont par défaut le nom et la <i>docstring</i> de la fonction fournie", correct: true } ]} /> --- Félicitations pour avoir terminé ce Quiz 🥳, si vous avez manqué certains éléments, prenez le temps de relire le chapitre pour renforcer vos connaissances. Si vous le réussissez, vous êtes prêt à plonger plus profondément dans la construction avec ces *components* !
agents-course/units/fr/unit2/llama-index/quiz1.mdx/0
{ "file_path": "agents-course/units/fr/unit2/llama-index/quiz1.mdx", "repo_id": "agents-course", "token_count": 1578 }
13
# 온보딩(Onboarding): 첫 걸음 내딛기 ⛵ <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/time-to-onboard.jpg" alt="Time to Onboard" width="100%"/> 이제 모든 필요한 정보를 확인했으니, 본격적으로 시작해 봅시다! 이 섹션에서는 다음 네 가지를 진행할 예정입니다 : 1. **Hugging Face 계정 생성** (아직 계정이 없으신 경우) 2. **Discord 가입 후 자기 소개** (수줍어 마세요 🤗) 3. **Hub에서 Hugging Face Agents 코스 팔로우** 4. **코스 널리 알리기** ### Step 1: Hugging Face 계정 생성 (아직 계정이 없으신 경우) <a href='https://huggingface.co/join' target='_blank'>여기에서</a> Hugging Face 계정을 만들어주세요. ### Step 2: Discord 커뮤니티에 가입하기 👉🏻 <a href="https://discord.gg/UrrTSsSyjb" target="_blank">여기에서</a> Discord 서버에 가입하세요. 가입 후, `#introduce-yourself` 채널에서 간단하게 자기소개를 남겨주세요. 이 서버에는 AI 에이전트와 관련된 채널을 제공하고 있습니다: - `agents-course-announcements`: **최신 코스 소식**을 확인하는 공간 - `🎓-agents-course-general`: **자유로운 대화와 토론** 을 위한 공간 - `agents-course-questions`: **질문 & 동료들과 도움을**주고 받는 공간 - `agents-course-showcase`: **자신이 만든 AI 에이전트를 공유** 하는 공간 추가로: - `smolagents`: **라이브러리에 대한 논의 및 지원** 을 받을 수 있습니다. Discord 사용이 처음이신 분들을 위해, Discord 101 가이드를 준비했습니다. [다음 섹션](discord101)에서 확인해 보세요! ### Step 3: Hugging Face Agent 코스 팔로우하기 최신 강의 자료, 업데이트, 공지를 놓치지 않으려면 ** Hugging Face Agents 코스를 팔로우하세요** 👉 Go <a href="https://huggingface.co/agents-course" target="_blank">여기</a>에서 **팔로우(follow)**버튼을 클릭하세요! <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/hf_course_follow.gif" alt="Follow" width="100%"/> ### Step 4: 코스 널리 알리기 이 코스가 더 많은 사람들에게 알려질 수 있도록 도와주세요 :) 두 가지 기여 방법을 제안합니다 : 1. <a href="https://github.com/huggingface/agents-course" target="_blank">Github</a>에서 ⭐로 코스 응원하기 <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/please_star.gif" alt="Repo star"/> 2. 배움의 여정 공유하기 : **이 코스를 듣고 있다는 것을 많은 사람들에게 알려주세요!** 소셜미디어에 사용하실 수 있도록 이미지도 준비해두었습니다 ! <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/share.png"> 👉 [여기](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/share.png?download=true) 에서 이미지를 다운로드 할 수 있습니다. 축하합니다! 🎉 **온보딩 과정을 완료하셨습니다!** 이제 본격적으로 AI 에이전트에 대해 배울 준비가 되었습니다 ! 즐거운 학습되세요. Keep Learning, stay awesome 🤗
agents-course/units/ko/unit0/onboarding.mdx/0
{ "file_path": "agents-course/units/ko/unit0/onboarding.mdx", "repo_id": "agents-course", "token_count": 2170 }
14
# LLM이란?[[what-are-llms]] <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-check-1.jpg" alt="Unit 1 planning"/> 이전 섹션에서 각 에이전트는 **코어에 AI 모델**이 필요하며, LLM(대규모 언어 모델)이 이 목적에 부합하는 가장 일반적인 AI 모델 유형임을 배웠습니다. 이제 LLM이 무엇이고, LLM이 어떻게 에이전트를 지원하는지 알아보겠습니다. 이 섹션에서는 LLM의 기술적 개요를 간결하게 설명합니다. 더 깊이 학습하고 싶으시다면 <a href="https://huggingface.co/learn/nlp-course/chapter1/1" target="_blank">자연어 처리 코스</a>를 확인해 주세요! ## 대규모 언어 모델 (LLM)이란? [[what-is-a-large-language-model]] LLM은 **사람의 언어를 이해하고 생성**하는 능력에 뛰어난 AI 모델입니다. 모델은 방대한 양의 텍스트 데이터를 학습하여 언어의 패턴, 구조, 뉘앙스를 익히며, 일반적으로 수백만 개에서 수십억 개의 매개변수를 가집니다. 대부분의 현대 LLM은 **트랜스포머(Transformer) 아키텍처**를 기반으로 합니다. 트랜스포머는 Google이 2018년에 발표한 BERT 이후로 크게 주목받고 있는 "어텐션(Attention)" 알고리즘을 사용한 딥러닝 아키텍처입니다. <figure> <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/transformer.jpg" alt="Transformer"/> <figcaption>The original Transformer architecture looked like this, with an encoder on the left and a decoder on the right. </figcaption> </figure> 트랜스포머(transformers)의 3가지 유형 : 1. **인코더(Encoders)** 인코더 기반 트랜스포머는 인풋 텍스트(또는 다른 데이터)를 밀집 표현(임베딩)으로 변환합니다. - **예시**: Google의 BERT - **사용 사례**: 텍스트 분류, 의미 검색(semantic search), 개체명 인식(NER) - **일반적인 규모**: 수백만 개의 매개변수 2. **디코더(Decoders)** 디코더 기반 트랜스포머는 **한 번에 하나의 토큰을 생성하며 시퀀스를 완성**합니다. - **예시**: Meta의 Llama - **사용 사례**: 텍스트 생성, 챗봇, 코드 생성 - **일반적인 규모**: 수십억 개의 매개변수 3. **Seq2Seq (Encoder–Decoder)** Seq2Seq 트랜스포머는 인코더와 디코더를 _결합_한 형태입니다. 인코더는 입력 시퀀스를 컨텍스트 표현(컨텍스트 벡터)으로 변환하고, 디코더가 출력 시퀀스를 생성합니다. - **예시**: T5, BART - **사용 사례**: 번역, 요약, 패러프레이징(Paraphrasing) - **일반적인 규모**: 수백만 개의 매개변수 LLM은 다양한 형태가 있지만, 일반적으로 LLM은 수십억 개의 매개변수를 가진 디코더 기반 모델입니다. 대표적인 LLM은 다음과 같습니다 : | **모델** | **제공 업체** | |-----------------------------------|-------------------------------------------| | **Deepseek-R1** | 딥시크(DeepSeek) | | **GPT4** | OpenAI | | **Llama 3** | Meta (페이스북 인공지능 연구소) | | **SmolLM2** | 허깅페이스(Hugging Face) | | **Gemma** | 구글(Google) | | **Mistral** | 미스트랄(Mistral) | 간단하지만 매우 효과적인 LLM의 핵심 원리: **이전 시퀀스를 기반으로 다음 토큰을 예측**하는 것입니다. "토큰" 이란 LLM이 작업하는 정보의 단위입니다. 토큰을 "단어"로 인식하셔도 되나, LLM은 효율성 문제로 전체 단어를 사용하지 않습니다. 예를 들어, 영어에는 약 60만 개의 단어가 있지만, LLM(대규모 언어 모델)의 어휘는 약 32,000개의 토큰으로 구성될 수 있습니다(예: Llama 2). 토큰화(tokenization)은 종종 하위 단어 단위에서 일어나고, 이러한 하위 단위들을 결합할 수 있습니다. 예를 들어, "interest"와 "ing"라는 토큰을 결합하여 "interesting"을 만들거나, "ed"를 추가하여 "interested"를 만들 수 있습니다. 아래 플레이그라운드에서 다양한 토크나이저를 실습해보세요: <iframe src="https://agents-course-the-tokenizer-playground.static.hf.space" frameborder="0" width="850" height="450" ></iframe> 각 LLM에는 모델별로 고유한 **특수 토큰**이 존재합니다. LLM은 이 토큰들을 사용하여 생성하는 텍스트를 구조적으로 열고 닫습니다. 예를 들어, 시퀀스의 시작과 끝, 메시지 또는 응답을 나타내기 위해 사용됩니다. 또한, 우리가 모델에 입력하는 입력 프롬프트도 특수 토큰을 포함한 구조로 작성됩니다. 그중 가장 중요한 것은 **EOS(End of Sequence) 토큰, 시퀀스 종료 토큰**입니다. 특수 토큰의 형태는 모델 제공업체마다 매우 다양합니다. 다음 표는 다양한 LLM의 특수 토큰을 보여줍니다. <table> <thead> <tr> <th><strong>모델</strong></th> <th><strong>제공업체</strong></th> <th><strong>EOS 토큰</strong></th> <th><strong>기능</strong></th> </tr> </thead> <tbody> <tr> <td><strong>GPT4</strong></td> <td>OpenAI</td> <td><code>&lt;|endoftext|&gt;</code></td> <td>메세지 텍스트의 끝</td> </tr> <tr> <td><strong>Llama 3</strong></td> <td>Meta (Facebook AI Research)</td> <td><code>&lt;|eot_id|&gt;</code></td> <td>시퀀스의 끝</td> </tr> <tr> <td><strong>Deepseek-R1</strong></td> <td>DeepSeek</td> <td><code>&lt;|end_of_sentence|&gt;</code></td> <td>메세지 텍스트의 끝</td> </tr> <tr> <td><strong>SmolLM2</strong></td> <td>Hugging Face</td> <td><code>&lt;|im_end|&gt;</code></td> <td>지시 / 메세지의 끝</td> </tr> <tr> <td><strong>Gemma</strong></td> <td>Google</td> <td><code>&lt;end_of_turn&gt;</code></td> <td>대화 턴 끝</td> </tr> </tbody> </table> <Tip> 이러한 특수 토큰을 외울 필요는 없지만, 다양성과 LLM 내에서의 역할을 이해하는 것은 중요합니다. 특정 모델의 특수 토큰에 대해 더 알고 싶다면, 해당 모델의 Hub 저장소에서 설정 파일을 확인할 수 있습니다. 예를 들어, SmolLM2 모델의 특수 토큰은 <a href="https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct/blob/main/tokenizer_config.json">tokenizer_config.json</a>에서 확인할 수 있습니다. </Tip> ## 다음 토큰 예측 [[understanding-next-token-prediction]] LLM은 **자기 회귀(autoregressive) ** 방식으로 작동합니다. 즉, **이전 출력이 다음 입력**이 되는 방식으로 동작하며, 이 과정이 반복됩니다. 모델이 다음 토큰을 EOS 토큰으로 예측하면, 텍스트 생성을 중단합니다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/AutoregressionSchema.gif" alt="Visual Gif of autoregressive decoding" width="60%"> 즉, LLM은 EOS에 도달할 때까지 텍스트를 생성합니다. 하지만 단일 디코딩 루프 내에서 어떤 일이 일어날까요? 텍스트 생성 과정은 복잡하지만, 기본적인 개요는 다음과 같습니다 : - 입력 텍스트가 **토큰화(tokenization)** 되면, 모델은 시퀀스 내 각 토큰의 의미와 토큰의 위치 정보를 나타내는 표현(representation)을 계산합니다. - 이 표현이 모델로 입력되며, 모델은 각 토큰 별로 다음 토큰이 될 가능성을 랭킹화한 점수를 출력합니다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/DecodingFinal.gif" alt="Visual Gif of decoding" width="60%"> 이러한 점수를 기반으로, 여러 가지 전략을 사용하여 다음 토큰을 선택합니다. - 가장 간단한 디코딩 전략은 매번 최대 점수를 가진 토큰을 선택하는 것입니다. 아래에서 SmolLM2 모델을 활용해 디코딩을 실습해보세요!(이 모델의 **EOS 토큰**은 <|im_end|> 입니다.) <iframe src="https://agents-course-decoding-visualizer.hf.space" frameborder="0" width="850" height="450" ></iframe> - 더 발전된 디코딩 전략도 있습니다. 예를 들어, **빔 서치(beam search)** 는 여러 후보 시퀀스를 탐색하여 전체 점수가 가장 높은 시퀀스를 찾습니다. 이는 일부 개별 토큰의 점수가 낮더라도 전체 점수가 높은 결과를 찾을 수 있도록 합니다. <iframe src="https://agents-course-beam-search-visualizer.hf.space" frameborder="0" width="850" height="450" ></iframe> 디코딩에 대해 더 자세히 알고 싶으시다면, [NLP 코스](https://huggingface.co/learn/nlp-course)를 참고해주세요! ## 당신에게 필요한건 어텐션(Attention) 하나뿐 (Attention is all you need) [[attention-is-all-you-need]] Transformer 아키텍처에서 가장 중요한 요소 중 하나는 **어텐션(Attention)** 입니다. 다음 단어를 예측할 때, 문장의 모든 단어가 동일한 중요도를 가지지는 않습니다. 예를 들어, *"The capital of France is ..."*라는 문장에서 "France"와 "capital"이 가장 중요한 의미를 가집니다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/AttentionSceneFinal.gif" alt="Visual Gif of Attention" width="60%"> 이처럼, 다음 토큰을 예측하는 데 가장 관련성이 높은 단어를 식별하는 과정은 매우 효과적인 기법으로 입증되었습니다. GPT-2 이후로 LLM의 기본 원리인 '다음 토큰 예측'은 변하지 않았지만, 신경망을 확장하고 어텐션 메커니즘을 사용하여 더 긴 시퀀스에서도 작동할 수 있게 큰 발전이 있었습니다. LLM을 사용해 본 경험이 있으시다면, *컨텍스트 길이(context length)* 라는 용어를 들어보셨을 것입니다. 이는 LLM이 처리할 수 있는 최대 토큰 수이자, 모델의 최대 _어텐션 스팬(attention span)_ 를 의미합니다. ## LLM에 어떻게 프롬프트(Prompt)를 입력할지가 중요한 이유 [[prompting-the-llm-is-important]] LLM의 역할은 입력된 모든 토큰을 기반으로 다음 토큰을 예측하고, 어떤 토큰이 "중요한"지를 결정하는 것입니다. 따라서 입력하는 문장의 구성 방식이 매우 중요합니다. LLM에 제공하는 입력 시퀀스를 _프롬프트(prompt)_ 라고 합니다.**프롬프트를 신중하게 설계하면 원하는 출력**을 얻기 쉬워집니다. ## LLM은 어떻게 학습될까? [[how-are-llms-trained]] LLM은 방대한 텍스트 데이터셋을 학습하며, 자기지도 학습(self-supervised learning) 또는 마스킹 언어 모델링(masked language modeling)을 이용해 문장 내 다음 단어를 예측하는 방식으로 훈련됩니다. 이러한 비지도 학습(unsupervised learning) 을 통해 모델은 언어의 구조와 **텍스트의 패턴**을 학습하여, 새로운 데이터에도 일반화(generalization) 할 수 있게 됩니다. 이 사전 학습(pre-training) 이후, LLM은 특정 작업을 수행하도록 지도 학습(supervised learning) 방식으로 미세 조정(fine-tuning)됩니다. 예를 들어, 일부 모델은 대화 구조나 도구 활용에 맞춰 훈련되며, 다른 모델들은 분류(classification)나 코드 생성(code generation)에 초점을 맞춰 학습됩니다. ## LLM을 어떻게 사용할 수 있을까? [[how-can-i-use-llms]] LLM을 사용하는 방법은 크게 두가지로 나뉩니다: 1. **로컬에서 실행하기** (하드웨어 자원이 갖춰져 있는 경우) 2. **클라우드/API 사용하기** (예:Hugging Face Serverless Inference API) 이 코스에서는 주로 Hugging Face Hub의 API를 사용하여 모델을 실행합니다. 추가로, 개인 하드웨어에서 직접 실행하는 방법도 살펴볼 예정입니다. ## LLM은 AI 에이전트에서 어떻게 사용될까? [[how-are-llms-used-in-ai-agents]] LLM은 AI 에이전트의 핵심 구성 요소로, 자연어를 이해하고 생성하는 역할을 합니다. LLM은 사용자 명령을 해석하고, 대화의 문맥을 유지하며, 계획을 세우고, 어떤 도구를 사용할 지 결정할 수 있습니다. 이 단계들에 대해 이번 단원에서 좀 더 자세히 살펴볼 예정이지만, 지금 알아야 할 가장 중요한 포인트는**LLM이 에이전트의 "두뇌"역할을 한다는 것**입니다! --- 지금까지 많은 정보를 다뤘네요! 이번 섹션에서는 LLM이 무엇인지, 어떻게 작동하는지, 그리고 LLM이 AI 에이전트에서 어떤 역할을 하는지를 살펴보았습니다. 언어 모델과 자연어 처리에 대해 더 깊이 공부하고 싶다면, Hugging Face의 <a href="https://huggingface.co/learn/nlp-course/chapter1/1" target="_blank">무료 NLP 강의 </a>를 확인해 보세요! 이제 우리는 LLM이 어떻게 작동하는지에 대해 배웠으니, **LLM이 대화형 환경에서 어떻게 텍스트를 생성하는지** 살펴볼 차례입니다! <a href="https://huggingface.co/agents-course/notebooks/blob/main/dummy_agent_library.ipynb" target="_blank">이 노트북</a>을 실행하려면, **yHugging Face 토큰** 을 이곳에서 <a href="https://hf.co/settings/tokens" target="_blank">https://hf.co/settings/tokens</a> 발급하세요! Jupyter Notebook 실행 방법에 대한 자세한 내용은 <a href="https://huggingface.co/docs/hub/notebooks">Hugging Face Hub의 Jupyter Notebooks문서 </a>를 참고해주세요. 또한, <a href="https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct" target="_blank"> Meta Llama 모델</a>에 대한 엑세스를 요청해야 합니다.
agents-course/units/ko/unit1/what-are-llms.mdx/0
{ "file_path": "agents-course/units/ko/unit1/what-are-llms.mdx", "repo_id": "agents-course", "token_count": 10294 }
15
# Раздел 1 Тест <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub4DONE.jpg" alt="Раздел 1 планирование"/> Отлично справились с первым разделом! Давайте проверим ваше понимание ключевых понятий, рассмотренных до сих пор. Когда вы пройдете этот тест, перейдите к следующему разделу, чтобы получить свой сертификат. Удачи! ## Тест Вот интерактивный тест. Этот тест размещен в пространстве Hugging Face Hub. В ней вам предстоит ответить на ряд вопросов с несколькими вариантами ответов, чтобы проверить ваше понимание ключевых понятий, рассмотренных в этом разделе. После завершения теста вы сможете увидеть свой результат и распределение правильных ответов. Один важный момент: **не забудьте нажать на кнопку Submit после прохождения теста, иначе ваша оценка не будет сохранена!** <iframe src="https://agents-course-unit-1-quiz.hf.space" frameborder="0" width="850" height="450" ></iframe> Вы также можете пройти этот тест 👉 [здесь](https://huggingface.co/spaces/agents-course/unit_1_quiz)
agents-course/units/ru-RU/unit1/final-quiz.mdx/0
{ "file_path": "agents-course/units/ru-RU/unit1/final-quiz.mdx", "repo_id": "agents-course", "token_count": 924 }
16
# Function Calling là gì? Function-calling là **cách để LLM thực hiện hành động trên môi trường của nó**. Tính năng này được [giới thiệu lần đầu trong GPT-4](https://openai.com/index/function-calling-and-other-api-updates/), sau đó được áp dụng ở các model khác. Giống như Tools của Agent, function-calling cho phép model **tương tác với môi trường**. Tuy nhiên, khả năng gọi hàm **được model học** và ít phụ thuộc vào prompting hơn các kỹ thuật Agent khác. Trong chương 1, Agent **không học cách sử dụng Tools** mà chỉ được cung cấp danh sách Tools, dựa trên khả năng tổng quát hóa của model để lập kế hoạch sử dụng chúng. Còn với function-calling, **Agent được fine-tuning (tinh chỉnh) để sử dụng Tools**. ## Model "học" cách thực hiện hành động như thế nào? Ở chương 1, ta đã tìm hiểu workflow tổng quan của Agent. Khi người dùng cung cấp Tools và đưa ra truy vấn, model sẽ lặp qua các bước: 1. *Suy nghĩ*: Xác định hành động cần thực hiện để đạt mục tiêu 2. *Hành động*: Định dạng hành động với tham số chính xác và dừng generation 3. *Quan sát*: Nhận kết quả từ việc thực thi Trong hội thoại thông thường qua API, cuộc trò chuyện sẽ luân phiên giữa user và assistant: ```python conversation = [ {"role": "user", "content": "I need help with my order"}, {"role": "assistant", "content": "I'd be happy to help. Could you provide your order number?"}, {"role": "user", "content": "It's ORDER-123"}, ] ``` Function-calling mang đến **vai trò mới trong hội thoại**: 1. Vai trò mới cho **Hành động** 2. Vai trò mới cho **Quan sát** Ví dụ từ [Mistral API](https://docs.mistral.ai/capabilities/function_calling/): ```python conversation = [ { "role": "user", "content": "What's the status of my transaction T1001?" }, { "role": "assistant", "content": "", "function_call": { "name": "retrieve_payment_status", "arguments": "{\"transaction_id\": \"T1001\"}" } }, { "role": "tool", "name": "retrieve_payment_status", "content": "{\"status\": \"Paid\"}" }, { "role": "assistant", "content": "Your transaction T1001 has been successfully paid." } ] ``` > ...Nhưng bạn nói có vai trò mới cho function calls? **Vừa đúng vừa sai**. Trong trường hợp này và nhiều API khác, model định dạng hành động dưới dạng message "assistant". Chat template sẽ biểu diễn điều này qua **Special Token** (Token đặc biệt): - `[AVAILABLE_TOOLS]` – Bắt đầu danh sách Tools - `[/AVAILABLE_TOOLS]` – Kết thúc danh sách Tools - `[TOOL_CALLS]` – Gọi Tool (thực hiện "Hành động") - `[TOOL_RESULTS]` – "Quan sát" kết quả - `[/TOOL_RESULTS]` – Kết thúc quan sát (model có thể tiếp tục decode) Chúng ta sẽ tìm hiểu thêm về function-calling trong khóa học. Bạn có thể xem [tài liệu chi tiết](https://docs.mistral.ai/capabilities/function_calling/) để hiểu sâu hơn. --- Sau khi hiểu function-calling là gì và cách hoạt động, hãy **thêm khả năng function-calling cho model chưa hỗ trợ**: [google/gemma-2-2b-it](https://huggingface.co/google/gemma-2-2b-it) bằng cách thêm Special Token mới. **Trước tiên cần hiểu về fine-tuning và LoRA**.
agents-course/units/vi/bonus-unit1/what-is-function-calling.mdx/0
{ "file_path": "agents-course/units/vi/bonus-unit1/what-is-function-calling.mdx", "repo_id": "agents-course", "token_count": 1978 }
17
# Tư duy: Lập luận nội bộ và phương pháp Re-Act <Tip> Trong phần này, ta sẽ tìm hiểu cách thức hoạt động bên trong của một AI agent—khả năng lập luận và lập kế hoạch. Ta sẽ khám phá cách agent tận dụng cuộc đối thoại nội bộ để phân tích thông tin, chia nhỏ vấn đề phức tạp thành các bước quản lý được, và quyết định hành động tiếp theo. Ngoài ra, ta sẽ giới thiệu phương pháp Re-Act, một kỹ thuật prompting khuyến khích mô hình suy nghĩ "từng bước một" trước khi hành động. </Tip> Tư duy đại diện cho **quá trình lập luận và lập kế hoạch nội bộ của Agent** để giải quyết nhiệm vụ. Điều này sử dụng khả năng LLM (Mô hình ngôn ngữ lớn) của agent **để phân tích thông tin được trình bày trong prompt**. Hãy xem đây như cuộc đối thoại nội bộ của agent, nơi nó xem xét nhiệm vụ hiện tại và lên chiến lược tiếp cận. Tư duy của Agent chịu trách nhiệm truy cập các quan sát hiện tại và quyết định hành động tiếp theo nên là gì. Thông qua quá trình này, agent có thể **chia nhỏ các vấn đề phức tạp thành các bước nhỏ hơn, dễ quản lý hơn**, phản ánh từ kinh nghiệm trước đó, và liên tục điều chỉnh kế hoạch dựa trên thông tin mới. Dưới đây là một số ví dụ về các loại tư duy phổ biến: | Loại tư duy | Ví dụ | |----------------------|---------| | Lập kế hoạch | "Tôi cần chia nhiệm vụ này thành ba bước: 1) thu thập dữ liệu, 2) phân tích xu hướng, 3) tạo báo cáo" | | Phân tích | "Dựa trên thông báo lỗi, vấn đề có vẻ liên quan đến tham số kết nối cơ sở dữ liệu" | | Ra quyết định | "Với hạn chế về ngân sách của người dùng, tôi nên đề xuất tùy chọn tầm trung" | | Giải quyết vấn đề | "Để tối ưu hóa đoạn mã này, tôi nên chạy phân tích hiệu suất để xác định điểm nghẽn" | | Tích hợp bộ nhớ | "Người dùng đã đề cập rằng họ thích Python trước đó, vì vậy tôi sẽ cung cấp ví dụ bằng Python" | | Tự phản ánh | "Cách tiếp cận trước của tôi không hiệu quả, tôi nên thử một chiến lược khác" | | Thiết lập mục tiêu | "Để hoàn thành nhiệm vụ này, tôi cần xác định tiêu chí chấp nhận trước tiên" | | Ưu tiên hóa | "Lỗ hổng bảo mật cần được giải quyết trước khi thêm tính năng mới" | > **Lưu ý:** Trường hợp với các LLM đã được tinh chỉnh cho function-calling, quá trình tư duy là tùy chọn. > *Nếu bạn chưa quen với function-calling, sẽ có thêm chi tiết trong phần Hành động.* ## Phương pháp Re-Act Một phương pháp quan trọng là **ReAct**, kết hợp giữa "Lập luận / Tư duy" và "Hành động". ReAct là kỹ thuật prompting đơn giản bằng cách thêm "Let's think step by step" (hãy suy nghĩ hay tư duy từng bước một) trước khi để LLM giải mã các token tiếp theo. Việc nhắc mô hình tư duy "từng bước" thực sự khuyến khích quá trình giải mã tạo ra **một kế hoạch**, thay vì giải pháp cuối cùng ngay lập tức, vì mô hình được khuyến khích **chia nhỏ** vấn đề thành các *nhiệm vụ con*. Cách này cho phép mô hình xem xét các bước con chi tiết hơn, thường dẫn đến ít lỗi hơn so với việc cố gắng tạo ra giải pháp cuối cùng trực tiếp. <figure> <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/ReAct.png" alt="ReAct"/> <figcaption>Hình (d) là ví dụ về phương pháp Re-Act khi ta prompt "Let's think step by step" </figcaption> </figure> <Tip> Gần đây chúng ta thấy nhiều sự quan tâm đến các chiến lược lập luận. Đây là nền tảng của các mô hình như Deepseek R1 hay OpenAI's o1 - những mô hình đã được tinh chỉnh để "nghĩ trước khi trả lời". Những mô hình này được huấn luyện để luôn bao gồm các phần _tư duy_ cụ thể (được đặt giữa các token đặc biệt `<think>` và `</think>`). Đây không chỉ là kỹ thuật prompting như ReAct, mà là phương pháp training nơi mô hình học cách tạo ra các phần này sau khi phân tích hàng ngàn ví dụ thể hiện điều chúng ta mong đợi. </Tip> --- Bây giờ chúng ta đã hiểu rõ hơn về quá trình Tư duy, hãy đi sâu vào phần thứ hai của quy trình: Hành động.
agents-course/units/vi/unit1/thoughts.mdx/0
{ "file_path": "agents-course/units/vi/unit1/thoughts.mdx", "repo_id": "agents-course", "token_count": 3238 }
18
# AI 智能体可观测性与评估 ## 🔎 什么是可观测性? 可观测性是指通过查看日志、指标和追踪等外部信号来理解你的 AI 智能体内部正在发生什么。对于 AI 智能体而言,这意味着追踪行为、工具使用情况、模型调用和响应,以便调试和改进智能体性能。 ![Observability dashboard](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/langfuse-dashboard.png) ## 🔭 为何智能体可观测性如此重要 没有可观测性,AI 智能体就是“黑匣子”。可观测性工具使智能体变得透明,让你能够: - 理解成本与准确性的权衡 - 测量延迟 - 检测有害语言和提示注入 - 监测用户反馈 换句话说,它使你的演示智能体为生产环境做好准备! ## 🔨 可观测性工具 常见的 AI 智能体可观测性工具包括像 [Langfuse](https://langfuse.com) 和 [Arize](https://www.arize.com) 这样的平台。这些工具有助于收集详细的追踪信息,并提供仪表板来实时监测指标,从而轻松检测问题并优化性能。 可观测性工具的功能和能力差异很大。有些工具是开源的,受益于庞大的社区,这些社区塑造了它们的路线图并提供了广泛的集成。此外,某些工具专注于 LLMOps 的特定方面——例如可观测性、评估或提示管理——而另一些工具则旨在覆盖整个 LLMOps 工作流程。我们鼓励你探索不同选项的文档,以选择一个适合你的解决方案。 许多智能体框架,例如 [smolagents](https://huggingface.co/docs/smolagents/v1.12.0/en/index),使用 [OpenTelemetry](https://opentelemetry.io/docs/) 标准向可观测性工具公开元数据。除此之外,可观测性工具还会构建自定义的检测(instrumentations),以便在快速发展的 LLM 世界中提供更大的灵活性。你应该查阅你正在使用的工具的文档,以了解其支持的功能。 ## 🔬追踪与跨度(Traces and Spans) 可观测性工具通常将智能体运行表示为追踪(traces)和跨度(spans)。 - **追踪(Traces)** 代表一个从开始到结束的完整智能体任务(例如处理用户查询)。 - **跨度(Spans)** 是追踪内的单个步骤(例如调用语言模型或检索数据)。 ![Example of a smolagent trace in Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/trace-tree.png) ## 📊 需要监控的关键指标(Key Metrics to Monitor) 以下是可观测性工具监控的一些最常见的指标: **延迟:** 智能体响应有多快?漫长的等待时间会对用户体验产生负面影响。你应该通过追踪智能体运行来测量任务和单个步骤的延迟。例如,一个所有模型调用需要 20 秒的智能体可以通过使用更快的模型或并行运行模型调用来加速。 **成本:** 每次智能体运行的费用是多少?AI 智能体依赖于按 token 计费的 LLM 调用或外部 API。频繁的工具使用或多个提示会迅速增加成本。例如,如果一个智能体为了边际的质量提升而调用 LLM 五次,你必须评估成本是否合理,或者是否可以减少调用次数或使用更便宜的模型。实时监控也有助于识别意外的峰值(例如,导致过度 API 循环的 bug)。 **请求错误:** 智能体失败了多少次请求?这可能包括 API 错误或工具调用失败。为了使你的智能体在生产环境中对这些情况更具鲁棒性,你可以设置回退(fallbacks)或重试。例如,如果 LLM 提供商 A宕机,你可以切换到 LLM 提供商 B 作为备用。 **用户反馈:** 实施直接的用户评估可以提供有价值的见解。这可以包括明确的评分(👍赞/👎踩,⭐1-5 星)或文本评论。持续的负面反馈应该引起你的警惕,因为这表明智能体没有按预期工作。 **隐式用户反馈:** 即使用户没有明确评分,他们的行为也能提供间接反馈。这可能包括立即改述问题、重复查询或点击重试按钮。例如,如果你看到用户反复问同一个问题,这表明智能体没有按预期工作。 **准确性:** 智能体产生正确或期望输出的频率如何?准确性的定义各不相同(例如,解决问题的正确性、信息检索的准确性、用户满意度)。第一步是为你的智能体定义成功的标准。你可以通过自动化检查、评估分数或任务完成标签来追踪准确性。例如,将追踪标记为“成功”或“失败”。 **自动化评估指标:** 你也可以设置自动化评估。例如,你可以使用一个 LLM 来对智能体的输出进行评分,例如判断它是否有用、准确与否。还有一些开源库可以帮助你对智能体的不同方面进行评分。例如,用于 RAG 智能体的 [RAGAS](https://docs.ragas.io/) 或用于检测有害语言或提示注入的 [LLM Guard](https://llm-guard.com/)。 在实践中,结合使用这些指标可以最好地覆盖 AI 智能体的健康状况。在本章的[示例 notebook](https://huggingface.co/learn/agents-course/en/bonus-unit2/monitoring-and-evaluating-agents-notebook) 中,我们将向你展示这些指标在实际示例中的样子,但首先,我们将了解典型的评估工作流程是怎样的。 ## 👍 评估 AI 智能体 可观测性为我们提供了指标,但评估是分析这些数据(并执行测试)的过程,以确定 AI 智能体的表现如何以及如何改进它。换句话说,一旦你有了那些追踪和指标,你如何使用它们来评判智能体并做出决策? 定期评估很重要,因为 AI 智能体通常是非确定性的,并且会演变(通过更新或模型行为漂移)——没有评估,你就不知道你的“智能体”是否真的做得很好,或者是否出现了退化。 AI 智能体的评估有两类:**在线评估**和**离线评估**。两者都有价值,并且相辅相成。我们通常从离线评估开始,因为这是部署任何智能体之前的最低必要步骤。 ### 🥷 离线评估(Offline Evaluation) ![Dataset items in Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/example-dataset.png) 这涉及在受控环境中评估智能体,通常使用测试数据集,而不是实时用户查询。你使用精心策划的数据集,在这些数据集中你知道预期的输出或正确的行为是什么,然后让你的智能体在这些数据集上运行。 例如,如果你构建了一个数学应用题智能体,你可能会有一个包含 100 个已知答案问题的[测试数据集](https://huggingface.co/datasets/gsm8k)。离线评估通常在开发期间进行(并且可以作为 CI/CD 管道的一部分),以检查改进或防止性能退化。其好处在于它是**可重复的,并且由于你有基准答案(ground truth),你可以获得清晰的准确性指标**。你也可以模拟用户查询,并根据理想答案衡量智能体的响应,或使用上面描述的自动化指标。 离线评估的关键挑战是确保你的测试数据集全面且保持相关性——智能体可能在固定的测试集上表现良好,但在生产环境中遇到截然不同的查询。因此,你应该用新的边缘案例和反映真实世界场景的示例来更新测试集。混合使用小型“冒烟测试”用例和大型评估集是很有用的:小型集用于快速检查,大型集用于更广泛的性能指标。 ### 🔄 在线评估(Online Evaluation) 这是指在实时的、真实世界的环境中评估智能体,即在生产环境中的实际使用期间。在线评估涉及监控智能体在真实用户交互中的性能,并持续分析结果。 例如,你可能会追踪实时流量中的成功率、用户满意度分数或其他指标。在线评估的优势在于它**能捕捉到你在实验室环境中可能预料不到的情况**——你可以观察模型随时间的漂移(如果智能体的有效性随着输入模式的变化而下降),并捕捉到测试数据中没有的意外查询或情况。它提供了智能体在实际应用中行为的真实写照。 在线评估通常涉及收集隐式和显式用户反馈(如前所述),并可能运行影子测试或 A/B 测试(其中新版本的智能体与旧版本并行运行以进行比较)。挑战在于为实时交互获取可靠的标签或分数可能很棘手——你可能需要依赖用户反馈或下游指标(例如用户是否点击了结果)。 ### 🤝 两者结合 在实践中,成功的 AI 智能体评估融合了**在线**和**离线**方法。你可能会定期运行离线基准测试,以量化评分你的智能体在定义任务上的表现,并持续监控实时使用情况,以捕捉基准测试遗漏的问题。例如,离线测试可以发现代码生成智能体在一组已知问题上的成功率是否在提高,而在线监控可能会提醒你用户开始提出智能体难以处理的新类别问题。结合两者可以提供更稳健的全局视图。 事实上,许多团队采用一个循环:_离线评估 → 部署新智能体版本 → 监控在线指标并收集新的失败示例 → 将这些示例添加到离线测试集 → 迭代_。通过这种方式,评估是持续且不断改进的。 ## 🧑‍💻 让我们看看这在实践中是如何运作的 在下一节中,我们将看到如何使用可观测性工具来监测和评估我们的智能体的示例。
agents-course/units/zh-CN/bonus_unit2/what-is-agent-observability-and-evaluation.mdx/0
{ "file_path": "agents-course/units/zh-CN/bonus_unit2/what-is-agent-observability-and-evaluation.mdx", "repo_id": "agents-course", "token_count": 6542 }
19
# 快速自测(不计分)[[quiz2]] 什么?!还有测验?我们理解,我们理解... 😅 但这个简短的不计分测验旨在**帮助您巩固刚学习的关键概念**。 本测验涵盖大型语言模型(LLMs)、消息系统和工具——这些是理解和构建 AI 智能体的核心组件。 ### 问题1:以下哪项最能描述 AI 工具? <Question choices={[ { text: "仅生成文本响应的流程", explain: "", }, { text: "允许智能体执行特定任务并与外部环境交互的可执行流程或外部 API", explain: "工具是可执行函数,智能体可用其执行特定任务并与外部环境交互", correct: true }, { text: "存储智能体对话的功能", explain: "" } ]} /> --- ### 问题2: AI 智能体如何将工具作为"行动"在环境中使用? <Question choices={[ { text: "通过被动等待用户指令", explain: "", }, { text: "仅使用预编程响应", explain: "", }, { text: "在适当时要求 LLM 生成工具调用代码并代表模型运行工具", explain: "智能体可调用工具,并根据获得的信息进行规划与重新规划", correct: true } ]} /> --- ### 问题3:什么是大语言模型(LLM)? <Question choices={[ { text: "使用预定义答案进行回复的简单聊天机器人", explain: "", }, { text: "通过大量文本训练的深度学习模型,能理解并生成类人语言", explain: "", correct: true }, { text: "遵循严格预定义命令的基于规则 AI", explain: "" } ]} /> --- ### 问题4:以下哪项最能描述特殊标记(special tokens)在 LLMs 中的作用? <Question choices={[ { text: "存储在模型词汇表中用于提升文本生成质量的附加词汇", explain: "", }, { text: "用于实现特定功能,例如标记序列结束(EOS)或区分聊天模型中的不同消息角色", explain: "", correct: true }, { text: "随机插入用于提高响应多样性的标记", explain: "" } ]} /> --- ### 问题5: AI 聊天模型如何处理用户消息的内部流程? <Question choices={[ { text: "直接将消息作为结构化命令解析且不做转换", explain: "", }, { text: "通过将系统消息、用户消息和助手消息拼接成格式化提示", explain: "", correct: true }, { text: "根据历史对话随机生成响应", explain: "" } ]} /> --- 都明白了吗?很好!现在让我们**深入完整的智能体流程,开始构建你的第一个 AI 智能体!**
agents-course/units/zh-CN/unit1/quiz2.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit1/quiz2.mdx", "repo_id": "agents-course", "token_count": 1640 }
20
# LlamaIndex 中的组件是什么? 还记得第一单元中我们那位得力的管家智能体 Alfred 吗? 要有效协助我们,Alfred 需要理解我们的请求,并**准备、查找和使用相关信息来帮助完成任务**。 这正是 LlamaIndex 组件发挥作用的地方。 虽然 LlamaIndex 包含众多组件,但**我们将重点关注 `QueryEngine` 组件**。 为什么?因为它可以作为智能体的检索增强生成(RAG)工具。 那么什么是 RAG?大语言模型通过海量数据训练获得通用知识, 但它们可能缺乏相关且最新的特定领域数据。 RAG 通过从您的数据中检索相关信息并传递给 LLM 来解决这个问题。 ![RAG](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/rag.png) 试想 Alfred 的工作机制: 1. 您让 Alfred 帮忙策划晚宴 2. Alfred 需要查看您的日历、饮食偏好和过往成功菜单 3. `QueryEngine` 帮助 Alfred 查找这些信息并用于晚宴策划 这使得 `QueryEngine` 成为在 LlamaIndex 中**构建智能 RAG 工作流的核心组件**。 正如 Alfred 需要检索家庭信息才能发挥作用,任何智能体都需要理解和查找相关数据的能力。 `QueryEngine` 正好提供了这种核心能力。 现在让我们深入探讨如何**组合组件来创建 RAG 流程**。 ## 使用组件构建 RAG 流程 <Tip> 您可以通过 <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/llama-index/components.ipynb" target="_blank">这个 Notebook</a> 跟随代码实践(使用 Google Colab 运行)。 </Tip> RAG 包含五个关键阶段,这些阶段将构成您构建的大部分应用: 1. **加载**:将数据从原始位置(文本文件、PDF、网站、数据库或 API)导入工作流。LlamaHub 提供数百种集成方案 2. **索引**:创建便于查询的数据结构。对于 LLM 通常意味着创建向量嵌入——数据的语义数值表示,也可以包含其他元数据策略 3. **存储**:索引完成后需要持久化存储,避免重复构建 4. **查询**:支持多种检索策略,包括子查询、多步查询和混合策略 5. **评估**:通过客观指标评估响应准确性、忠实度和响应速度,对比不同策略效果 接下来我们将演示如何使用组件实现这些阶段。 ### 数据加载与嵌入 如前所述,LlamaIndex 可以基于您的自有数据进行操作,但**在访问数据之前,我们需要先完成加载**。 LlamaIndex 提供三种主要的数据加载方式: 1. `SimpleDirectoryReader`: 内置加载器,支持从本地目录加载多种文件类型 2. `LlamaParse`: LlamaIndex 官方 PDF 解析工具,提供托管 API 服务 3. `LlamaHub`: 包含数百个数据加载库的注册中心,支持从任意数据源获取数据 <Tip>对于复杂数据源,建议深入了解 <a href="https://docs.llamaindex.ai/en/stable/module_guides/loading/connector/">LlamaHub</a> 加载器和 <a href="https://github.com/run-llama/llama_cloud_services/blob/main/parse.md">LlamaParse</a> 解析器的使用方法。</Tip> **最简单的数据加载方式是使用 `SimpleDirectoryReader`**。 这个多功能组件可以从文件夹中加载各类文件,并将其转换为 LlamaIndex 可处理的 `Document` 对象。 以下是具体使用方法: ```python from llama_index.core import SimpleDirectoryReader reader = SimpleDirectoryReader(input_dir="path/to/directory") documents = reader.load_data() ``` 加载文档后,我们需要将其分解为更小的单元——`Node`对象。 `Node`是原始文档中的文本片段,既便于AI处理,又保留了对原`Document`对象的引用。 `IngestionPipeline`通过两个关键转换步骤帮助我们创建这些节点: 1. `SentenceSplitter`通过自然语句边界将文档拆分为可管理的文本块 2. `HuggingFaceInferenceAPIEmbedding`将每个文本块转换为数值化的向量表示——这种以AI能高效处理的方式捕捉语义信息 该流程能帮助我们以更适合搜索和分析的方式组织文档。 ```python from llama_index.core import Document from llama_index.embeddings.huggingface_api import HuggingFaceInferenceAPIEmbedding from llama_index.core.node_parser import SentenceSplitter from llama_index.core.ingestion import IngestionPipeline # 通过转换创建管道 pipeline = IngestionPipeline( transformations=[ SentenceSplitter(chunk_overlap=0), HuggingFaceInferenceAPIEmbedding(model_name="BAAI/bge-small-en-v1.5"), ] ) nodes = await pipeline.arun(documents=[Document.example()]) ``` ### 存储与索引文档 创建完`节点`对象后,我们需要对其进行索引,使其可以被搜索,但在此之前,我们需要一个存储数据的地方。 由于我们使用的是摄取管道,因此可以直接在管道上附加一个向量存储来填充数据。 在本例中,我们将使用 `Chroma` 来存储我们的文档。 <details> <summary>安装 ChromaDB</summary> 正如在[关于 LlamaHub 的章节](llama-hub)中所介绍的,我们可以使用以下命令安装 ChromaDB 向量存储: ```bash pip install llama-index-vector-stores-chroma ``` </details> ```python import chromadb from llama_index.vector_stores.chroma import ChromaVectorStore db = chromadb.PersistentClient(path="./alfred_chroma_db") chroma_collection = db.get_or_create_collection("alfred") vector_store = ChromaVectorStore(chroma_collection=chroma_collection) pipeline = IngestionPipeline( transformations=[ SentenceSplitter(chunk_size=25, chunk_overlap=0), HuggingFaceInferenceAPIEmbedding(model_name="BAAI/bge-small-en-v1.5"), ], vector_store=vector_store, ) ``` <Tip>An overview of the different vector stores can be found in the <a href="https://docs.llamaindex.ai/en/stable/module_guides/storing/vector_stores/">LlamaIndex documentation</a>.</Tip> 这就是向量嵌入的作用所在--通过将查询和节点嵌入同一向量空间,我们可以找到相关的匹配项。 `向量存储索引`会为我们处理这个问题,使用我们在摄取时使用的相同嵌入模型来确保一致性。 让我们看看如何从向量存储和嵌入中创建该索引: ```python from llama_index.core import VectorStoreIndex from llama_index.embeddings.huggingface_api import HuggingFaceInferenceAPIEmbedding embed_model = HuggingFaceInferenceAPIEmbedding(model_name="BAAI/bge-small-en-v1.5") index = VectorStoreIndex.from_vector_store(vector_store, embed_model=embed_model) ``` 所有信息都会自动保存在 `ChromaVectorStore` 对象和传递的目录路径中。 太棒了 现在我们可以轻松保存和加载索引了,让我们探索一下如何以不同方式查询索引。 ### 使用提示词和 LLM 查询 VectorStoreIndex 在查询索引之前,我们需要将其转换为查询接口。最常见的转换选项包括: - `as_retriever`:用于基础文档检索,返回带有相似度得分的`NodeWithScore`对象列表 - `as_query_engine`:用于单次问答交互,返回书面响应 - `as_chat_engine`:用于需要保持跨消息记忆的对话交互,通过聊天历史记录和索引上下文返回书面响应 我们将重点介绍查询引擎(query engine),因为它在类智能体交互中更为常见。 我们还需要向查询引擎传入一个大语言模型(LLM)用于生成响应。 ```python from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") query_engine = index.as_query_engine( llm=llm, response_mode="tree_summarize", ) query_engine.query("What is the meaning of life?") # The meaning of life is 42 ``` ### 响应处理 底层实现中,查询引擎不仅使用 LLM 来回答问题,还会采用 `ResponseSynthesizer` 作为响应处理策略。 同样,该组件完全可定制,但默认提供三种高效的工作策略: - `refine`(迭代优化): 通过逐个处理每个检索到的文本块来创建并优化答案。每个 Node/文本块都会触发独立的 LLM 调用 - `compact`(紧凑模式,默认): 与迭代优化类似,但会预先拼接文本块,从而减少 LLM 调用次数 - `tree_summarize`(树状归纳): 通过遍历所有检索到的文本块并构建答案的树状结构来生成详细响应 <Tip>通过<a href="https://docs.llamaindex.ai/en/stable/module_guides/deploying/query_engine/usage_pattern/#low-level-composition-api">底层组合 API</a> 实现查询流程的精细控制。该 API 允许您自定义和优化查询流程的每个步骤,与 <a href="https://docs.llamaindex.ai/en/stable/module_guides/workflow/">Workflows</a> 配合使用效果更佳</Tip> 由于语言模型的输出具有不可预测性,我们需要**通过评估答案质量**来确保结果的可靠性。 ### 评估与可观测性 LlamaIndex 提供**内置评估工具来量化响应质量**。 这些评估器利用 LLM 对回答进行多维度分析。 主要评估器包括: - `FaithfulnessEvaluator`(忠实性评估器): 验证答案是否得到上下文的支持 - `AnswerRelevancyEvaluator`(答案相关性评估器): 评估答案与问题的关联程度 - `CorrectnessEvaluator`(正确性评估器): 检验答案的正确性 ```python from llama_index.core.evaluation import FaithfulnessEvaluator query_engine = # from the previous section llm = # from the previous section # 查询索引 evaluator = FaithfulnessEvaluator(llm=llm) response = query_engine.query( "What battles took place in New York City in the American Revolution?" ) eval_result = evaluator.evaluate_response(response=response) eval_result.passing ``` 即使没有直接评估,我们也可以**通过可观察性深入了解我们的系统是如何运行的。** 当我们构建更复杂的工作流程并想要了解每个组件是如何运行的时候,这尤其有用。 <details> <summary>安装 LlamaTrace</summary> 正如 [LlamaHub 部分](llama-hub) 中介绍的那样,我们可以使用以下命令从 Arize Phoenix 安装 LlamaTrace 回调: ```bash pip install -U llama-index-callbacks-arize-phoenix ``` 此外,我们需要将 `PHOENIX_API_KEY` 环境变量设置为我们的 LlamaTrace API 密钥。我们可以通过以下方式获取此密钥: - 在 [LlamaTrace](https://llamatrace.com/login) 创建一个帐户 - 在您的帐户设置中生成 API 密钥 - 使用下面代码中的 API 密钥启用跟踪 </details> ```python import llama_index import os PHOENIX_API_KEY = "<PHOENIX_API_KEY>" os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"api_key={PHOENIX_API_KEY}" llama_index.core.set_global_handler( "arize_phoenix", endpoint="https://llamatrace.com/v1/traces" ) ``` <Tip>想要了解有关组件的更多信息以及如何使用它们?继续您的旅程,阅读<a href="https://docs.llamaindex.ai/en/stable/module_guides/">组件指南</a>或<a href="https://docs.llamaindex.ai/en/stable/understanding/rag/">RAG 指南</a>。</Tip> 我们已经了解了如何使用组件创建 `QueryEngine`。现在,让我们看看如何**将 `QueryEngine` 用作智能体的工具!**
agents-course/units/zh-CN/unit2/llama-index/components.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit2/llama-index/components.mdx", "repo_id": "agents-course", "token_count": 6545 }
21
<CourseFloatingBanner chapter={2} classNames="absolute z-10 right-0 top-0" notebooks={[ {label: "Google Colab", value: "https://colab.research.google.com/#fileId=https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/tool_calling_agents.ipynb"}, ]} /> # 将操作编写为代码片段或 JSON 结构 <Tip> 您可以通过 <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/tool_calling_agents.ipynb" target="_blank">此 Notebook</a> 跟随代码实践,该文件支持在 Google Colab 中运行。 </Tip> 工具调用智能体(Tool Calling Agents)是 `smolagents` 中提供的第二种智能体类型。与使用 Python 代码片段的代码智能体(Code Agents)不同,这类智能体**利用 LLM 提供商的内置工具调用能力**来生成 **JSON 结构**的工具调用指令。这是 OpenAI、Anthropic 等主流提供商采用的标准方法。 当 Alfred 想要搜索餐饮服务和派对创意时,`CodeAgent` 会生成并运行如下 Python 代码: ```python for query in [ "Best catering services in Gotham City", "Party theme ideas for superheroes" ]: print(web_search(f"Search for: {query}")) ``` 而 `ToolCallingAgent` 则会创建 JSON 结构: ```python [ {"name": "web_search", "arguments": "Best catering services in Gotham City"}, {"name": "web_search", "arguments": "Party theme ideas for superheroes"} ] ``` 该 JSON 结构随后会被用于执行工具调用。 尽管 `smolagents` 主要专注于 `CodeAgents`(因为[它们整体表现更好](https://huggingface.co/papers/2402.01030)),但对于不需要变量处理或复杂工具调用的简单系统,`ToolCallingAgents` 仍然可以高效工作。 ![代码操作与 JSON 操作对比](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png) ## 工具调用智能体的工作原理 工具调用智能体遵循与代码智能体相同的多步骤工作流程(详见[前一章节](./code_agents))。关键区别在于**操作结构方式**:智能体不再生成可执行代码,而是**生成指定工具名称和参数的 JSON 对象**,系统随后**解析这些指令**来执行相应工具。 ## 示例:运行工具调用智能体 让我们重新审视 Alfred 开始筹备派对的示例,这次使用 `ToolCallingAgent` 来展示区别。我们将构建一个能够使用 DuckDuckGo 进行网页搜索的智能体,与代码智能体示例的唯一区别在于智能体类型——框架会处理其他所有细节: ```python from smolagents import ToolCallingAgent, DuckDuckGoSearchTool, InferenceClientModel agent = ToolCallingAgent(tools=[DuckDuckGoSearchTool()], model=InferenceClientModel()) agent.run("Search for the best music recommendations for a party at the Wayne's mansion.") ``` 当查看智能体的执行跟踪时,您将看到类似以下内容而非 `Executing parsed code:`: ```text ╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Calling tool: 'web_search' with arguments: {'query': "best music recommendations for a party at Wayne's │ │ mansion"} │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ``` 智能体生成结构化的工具调用指令,系统通过处理这些指令来生成输出,而非像 `CodeAgent` 那样直接执行代码。 现在我们已经了解两种智能体类型,可以根据需求选择合适的一种。让我们继续探索 `smolagents`,让 Alfred 的派对大获成功!🎉 ## 资源 - [ToolCallingAgent 文档](https://huggingface.co/docs/smolagents/v1.8.1/en/reference/agents#smolagents.ToolCallingAgent) - ToolCallingAgent 的官方文档
agents-course/units/zh-CN/unit2/smolagents/tool_calling_agents.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit2/smolagents/tool_calling_agents.mdx", "repo_id": "agents-course", "token_count": 2069 }
22
# 什么是GAIA? [GAIA](https://huggingface.co/papers/2311.12983) 是一个**用于评估AI助手在需要核心能力组合的真实世界任务上的表现的基准**,这些核心能力包括推理、多模态理解、网页浏览和熟练的工具使用。 此论文介绍了GAIA _"[GAIA: A Benchmark for General AI Assistants](https://huggingface.co/papers/2311.12983)"_。 该基准包含**466个精心策划的问题**,这些问题对人类来说**在概念上简单**,但对当前的AI系统来说却**极具挑战性**。 为了说明差距: - **人类**:约92%的成功率 - **带有插件的GPT-4**:约15% - **深度研究(OpenAI)**:在验证集上的得分为67.36% GAIA突出了AI模型的当前局限性,并提供了一个严格的基准来评估向真正通用AI助手发展的进展。 ## 🌱 GAIA的核心原则 GAIA围绕以下支柱精心设计: - 🔍 **现实世界的难度**:任务需要多步骤推理、多模态理解和工具交互。 - 🧾 **人类可解释性**:尽管对AI来说很难,但每个任务在概念上对人类来说仍然简单易懂。 - 🛡️ **不可游戏化**:正确答案需要完整的任务执行,使得蛮力破解无效。 - 🧰 **评估的简单性**:答案简洁、事实性强且明确———作为一个理想的基准测试。 ## 难度等级 GAIA任务被组织为**三个递增复杂度的等级**,每个等级测试特定技能: - **一级**:需要少于5个步骤和最少的工具使用。 - **二级**:涉及更复杂的推理和多个工具之间的协调以及5-10个步骤。 - **三级**:需要长期规划和各种工具的高级集成。 ![GAIA等级](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit4/gaia_levels.png) ## 困难GAIA等级(Hard GAIA)的问题示例 > 在2008年画作“乌兹别克斯坦的刺绣”中展示的水果中,哪些曾在1949年10月的早餐菜单中被提供,作为后来用于电影《最后航程》的远洋班轮的一部分?请将这些水果以逗号分隔的列表形式给出,按照它们在画作中从12点位置开始的顺时针排列顺序,并使用每种水果的复数形式。 正如您所见,这个问题在几个方面对AI系统提出了挑战: - 需要一个**结构化的响应格式** - 涉及**多模态推理**(例如,分析图像) - 需要**多跳检索**相互依赖的事实: - 识别画作中的水果 - 发现哪个远洋班轮用于*最后航程* - 查找该船1949年10月的早餐菜单 - 需要**正确的排序**和高级规划以按正确顺序解决 这种任务突出了单独的LLM往往不足的地方,使GAIA成为**基于智能体的系统**的理想基准,这些系统可以在多个步骤和模态上进行推理、检索和执行。 ![GAIA capabilities plot](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit4/gaia_capabilities.png) ## 实时评估 为了鼓励持续的基准测试,**GAIA在Hugging Face上提供了一个公共排行榜**,您可以在其中测试您的模型对**300个测试问题**的表现。 👉 在[这里](https://huggingface.co/spaces/gaia-benchmark/leaderboard)查看排行榜 <iframe src="https://gaia-benchmark-leaderboard.hf.space" frameborder="0" width="850" height="450" ></iframe> 想深入了解GAIA? - 📄 [阅读完整论文](https://huggingface.co/papers/2311.12983) - 📄 [OpenAI的深度研究发布文章](https://openai.com/index/introducing-deep-research/) - 📄 [开源DeepResearch – 释放我们的搜索智能体](https://huggingface.co/blog/open-deep-research)
agents-course/units/zh-CN/unit4/what-is-gaia.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit4/what-is-gaia.mdx", "repo_id": "agents-course", "token_count": 2365 }
23
[package] name = "candle-book" version.workspace = true edition.workspace = true description.workspace = true repository.workspace = true keywords.workspace = true categories.workspace = true license.workspace = true readme = "README.md" [dependencies] accelerate-src = { workspace = true, optional = true } candle = { workspace = true } candle-datasets = { workspace = true } candle-nn = { workspace = true } candle-transformers = { workspace = true } candle-flash-attn = { workspace = true, optional = true } safetensors = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } num-traits = { workspace = true } intel-mkl-src = { workspace = true, optional = true } cudarc = { workspace = true, optional = true } half = { workspace = true, optional = true } image = { workspace = true, optional = true } anyhow = { workspace = true } tokio = "1.43.0" [dev-dependencies] byteorder = { workspace = true } hf-hub = { workspace = true, features=["tokio"]} clap = { workspace = true } memmap2 = { workspace = true } rand = { workspace = true } tokenizers = { workspace = true, features = ["onig"] } tracing = { workspace = true } tracing-chrome = { workspace = true } tracing-subscriber = { workspace = true } # Necessary to disambiguate with tokio in wasm examples which are 1.28.1 parquet = { workspace = true } image = { workspace = true } [build-dependencies] anyhow = { workspace = true } [features] default = []
candle/candle-book/Cargo.toml/0
{ "file_path": "candle/candle-book/Cargo.toml", "repo_id": "candle", "token_count": 459 }
24
# Installation ## 1. Create a new rust app or library ```bash cargo new myapp cd myapp ``` ## 2. Add the correct candle version ### Standard ```bash cargo add --git https://github.com/huggingface/candle.git candle-core ``` ### CUDA First, make sure that Cuda is correctly installed. - `nvcc --version` should print information about your Cuda compiler driver. - `nvidia-smi --query-gpu=compute_cap --format=csv` should print your GPUs compute capability, e.g. something like: ```bash compute_cap 8.9 ``` You can also compile the Cuda kernels for a specific compute cap using the `CUDA_COMPUTE_CAP=<compute cap>` environment variable. If any of the above commands errors out, please make sure to update your Cuda version. Add the `candle-core` crate with the cuda feature: ```bash cargo add --git https://github.com/huggingface/candle.git candle-core --features "cuda" ``` ### MKL You can also see the `mkl` feature which can get faster inference on CPU. Add the `candle-core` crate with the mkl feature: ```bash cargo add --git https://github.com/huggingface/candle.git candle-core --features "mkl" ``` ### Metal Metal is exclusive to MacOS. Add the `candle-core` crate with the metal feature: ```bash cargo add --git https://github.com/huggingface/candle.git candle-core --features "metal" ``` ## 3. Building Run `cargo build` to make sure everything can be correctly built. ```bash cargo build ```
candle/candle-book/src/guide/installation.md/0
{ "file_path": "candle/candle-book/src/guide/installation.md", "repo_id": "candle", "token_count": 464 }
25
# Simplified ## How its works This program implements a neural network to predict the winner of the second round of elections based on the results of the first round. Basic moments: 1. A multilayer perceptron with two hidden layers is used. The first hidden layer has 4 neurons, the second has 2 neurons. 2. The input is a vector of 2 numbers - the percentage of votes for the first and second candidates in the first stage. 3. The output is the number 0 or 1, where 1 means that the first candidate will win in the second stage, 0 means that he will lose. 4. For training, samples with real data on the results of the first and second stages of different elections are used. 5. The model is trained by backpropagation using gradient descent and the cross-entropy loss function. 6. Model parameters (weights of neurons) are initialized randomly, then optimized during training. 7. After training, the model is tested on a deferred sample to evaluate the accuracy. 8. If the accuracy on the test set is below 100%, the model is considered underfit and the learning process is repeated. Thus, this neural network learns to find hidden relationships between the results of the first and second rounds of voting in order to make predictions for new data. ```rust,ignore {{#include ../simplified.rs:book_training_simplified1}} ``` ```rust,ignore {{#include ../simplified.rs:book_training_simplified2}} ``` ```rust,ignore {{#include ../simplified.rs:book_training_simplified3}} ``` ## Example output ```bash Trying to train neural network. Epoch: 1 Train loss: 4.42555 Test accuracy: 0.00% Epoch: 2 Train loss: 0.84677 Test accuracy: 33.33% Epoch: 3 Train loss: 2.54335 Test accuracy: 33.33% Epoch: 4 Train loss: 0.37806 Test accuracy: 33.33% Epoch: 5 Train loss: 0.36647 Test accuracy: 100.00% real_life_votes: [13, 22] neural_network_prediction_result: 0.0 ```
candle/candle-book/src/training/simplified.md/0
{ "file_path": "candle/candle-book/src/training/simplified.md", "repo_id": "candle", "token_count": 530 }
26
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::Result; use candle_core::{Device, Tensor}; fn main() -> Result<()> { let a = Tensor::new(&[[0.0f32, 1.0, 2.0], [3.0, 4.0, 5.0]], &Device::Cpu)?; let b = Tensor::new(&[[88.0f32, 99.0]], &Device::Cpu)?; let new_a = a.slice_scatter(&b, 1, 2)?; assert_eq!(a.to_vec2::<f32>()?, [[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]); assert_eq!(new_a.to_vec2::<f32>()?, [[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]); Ok(()) }
candle/candle-core/examples/basics.rs/0
{ "file_path": "candle/candle-core/examples/basics.rs", "repo_id": "candle", "token_count": 287 }
27
/// Helper functions to write CPU kernels. use crate::backend::BackendStorage; use crate::{Error, Layout, Result, WithDType}; type C = super::CpuStorage; pub trait Map1 { fn f<T: WithDType>(&self, vs: &[T], layout: &Layout) -> Result<Vec<T>>; fn map(&self, vs: &C, layout: &Layout) -> Result<C> { match vs { C::U8(vs) => Ok(C::U8(self.f(vs, layout)?)), C::U32(vs) => Ok(C::U32(self.f(vs, layout)?)), C::I64(vs) => Ok(C::I64(self.f(vs, layout)?)), C::BF16(vs) => Ok(C::BF16(self.f(vs, layout)?)), C::F16(vs) => Ok(C::F16(self.f(vs, layout)?)), C::F32(vs) => Ok(C::F32(self.f(vs, layout)?)), C::F64(vs) => Ok(C::F64(self.f(vs, layout)?)), C::F8E4M3(vs) => Ok(C::F8E4M3(self.f(vs, layout)?)), } } } pub trait Map1Any { fn f<T: WithDType, W: Fn(Vec<T>) -> C>(&self, vs: &[T], layout: &Layout, wrap: W) -> Result<C>; fn map(&self, vs: &C, layout: &Layout) -> Result<C> { match vs { C::U8(vs) => Ok(self.f(vs, layout, C::U8)?), C::U32(vs) => Ok(self.f(vs, layout, C::U32)?), C::I64(vs) => Ok(self.f(vs, layout, C::I64)?), C::BF16(vs) => Ok(self.f(vs, layout, C::BF16)?), C::F16(vs) => Ok(self.f(vs, layout, C::F16)?), C::F32(vs) => Ok(self.f(vs, layout, C::F32)?), C::F64(vs) => Ok(self.f(vs, layout, C::F64)?), C::F8E4M3(vs) => Ok(self.f(vs, layout, C::F8E4M3)?), } } } pub trait Map2 { const OP: &'static str; fn f<T: WithDType>(&self, v1: &[T], l1: &Layout, v2: &[T], l2: &Layout) -> Result<Vec<T>>; fn map(&self, v1: &C, l1: &Layout, v2: &C, l2: &Layout) -> Result<C> { match (v1, v2) { (C::U8(v1), C::U8(v2)) => Ok(C::U8(self.f(v1, l1, v2, l2)?)), (C::U32(v1), C::U32(v2)) => Ok(C::U32(self.f(v1, l1, v2, l2)?)), (C::I64(v1), C::I64(v2)) => Ok(C::I64(self.f(v1, l1, v2, l2)?)), (C::BF16(v1), C::BF16(v2)) => Ok(C::BF16(self.f(v1, l1, v2, l2)?)), (C::F16(v1), C::F16(v2)) => Ok(C::F16(self.f(v1, l1, v2, l2)?)), (C::F32(v1), C::F32(v2)) => Ok(C::F32(self.f(v1, l1, v2, l2)?)), (C::F64(v1), C::F64(v2)) => Ok(C::F64(self.f(v1, l1, v2, l2)?)), (C::F8E4M3(v1), C::F8E4M3(v2)) => Ok(C::F8E4M3(self.f(v1, l1, v2, l2)?)), _ => Err(Error::DTypeMismatchBinaryOp { lhs: v1.dtype(), rhs: v2.dtype(), op: Self::OP, } .bt()), } } } pub trait Map2InPlace { const OP: &'static str; fn f<T: WithDType>(&self, v1: &mut [T], l1: &Layout, v2: &[T], l2: &Layout) -> Result<()>; fn map(&self, v1: &mut C, l1: &Layout, v2: &C, l2: &Layout) -> Result<()> { match (v1, v2) { (C::U8(v1), C::U8(v2)) => self.f(v1, l1, v2, l2)?, (C::U32(v1), C::U32(v2)) => self.f(v1, l1, v2, l2)?, (C::I64(v1), C::I64(v2)) => self.f(v1, l1, v2, l2)?, (C::BF16(v1), C::BF16(v2)) => self.f(v1, l1, v2, l2)?, (C::F16(v1), C::F16(v2)) => self.f(v1, l1, v2, l2)?, (C::F32(v1), C::F32(v2)) => self.f(v1, l1, v2, l2)?, (C::F64(v1), C::F64(v2)) => self.f(v1, l1, v2, l2)?, (v1, v2) => Err(Error::DTypeMismatchBinaryOp { lhs: v1.dtype(), rhs: v2.dtype(), op: Self::OP, } .bt())?, }; Ok(()) } } pub trait Map2U8 { const OP: &'static str; fn f<T: WithDType>(&self, v1: &[T], l1: &Layout, v2: &[T], l2: &Layout) -> Result<Vec<u8>>; fn map(&self, v1: &C, l1: &Layout, v2: &C, l2: &Layout) -> Result<C> { match (v1, v2) { (C::U8(v1), C::U8(v2)) => Ok(C::U8(self.f(v1, l1, v2, l2)?)), (C::U32(v1), C::U32(v2)) => Ok(C::U8(self.f(v1, l1, v2, l2)?)), (C::I64(v1), C::I64(v2)) => Ok(C::U8(self.f(v1, l1, v2, l2)?)), (C::BF16(v1), C::BF16(v2)) => Ok(C::U8(self.f(v1, l1, v2, l2)?)), (C::F16(v1), C::F16(v2)) => Ok(C::U8(self.f(v1, l1, v2, l2)?)), (C::F32(v1), C::F32(v2)) => Ok(C::U8(self.f(v1, l1, v2, l2)?)), (C::F64(v1), C::F64(v2)) => Ok(C::U8(self.f(v1, l1, v2, l2)?)), (C::F8E4M3(v1), C::F8E4M3(v2)) => Ok(C::U8(self.f(v1, l1, v2, l2)?)), _ => Err(Error::DTypeMismatchBinaryOp { lhs: v1.dtype(), rhs: v2.dtype(), op: Self::OP, } .bt()), } } } pub fn binary_map<T: Copy, U: Copy, F: FnMut(T, T) -> U>( lhs_l: &Layout, rhs_l: &Layout, lhs: &[T], rhs: &[T], mut f: F, ) -> Vec<U> { match (lhs_l.contiguous_offsets(), rhs_l.contiguous_offsets()) { (Some((o_l1, o_l2)), Some((o_r1, o_r2))) => lhs[o_l1..o_l2] .iter() .zip(rhs[o_r1..o_r2].iter()) .map(|(&l, &r)| f(l, r)) .collect(), (Some((o_l1, o_l2)), None) => { // TODO: Maybe we want to avoid going through the layout twice. match rhs_l.offsets_b() { Some(ob) => { let mut i_in_block = 0; let mut i_right_broadcast = 0; lhs[o_l1..o_l2] .iter() .map(|&l| { let r = unsafe { rhs.get_unchecked(i_in_block + ob.start) }; i_right_broadcast += 1; if i_right_broadcast >= ob.right_broadcast { i_in_block += 1; i_right_broadcast = 0; } if i_in_block >= ob.len { i_in_block = 0 } f(l, *r) }) .collect() } None => lhs_l .strided_index() .zip(rhs_l.strided_index()) .map(|(lhs_i, rhs_i)| f(lhs[lhs_i], rhs[rhs_i])) .collect(), } } (None, Some((o_r1, o_r2))) => { // TODO: Maybe we want to avoid going through the layout twice. match lhs_l.offsets_b() { Some(ob) => { let mut i_in_block = 0; let mut i_right_broadcast = 0; rhs[o_r1..o_r2] .iter() .map(|&r| { let l = unsafe { lhs.get_unchecked(i_in_block + ob.start) }; i_right_broadcast += 1; if i_right_broadcast >= ob.right_broadcast { i_in_block += 1; i_right_broadcast = 0; } if i_in_block >= ob.len { i_in_block = 0 } f(*l, r) }) .collect() } None => lhs_l .strided_index() .zip(rhs_l.strided_index()) .map(|(lhs_i, rhs_i)| f(lhs[lhs_i], rhs[rhs_i])) .collect(), } } _ => lhs_l .strided_index() .zip(rhs_l.strided_index()) .map(|(lhs_i, rhs_i)| f(lhs[lhs_i], rhs[rhs_i])) .collect(), } } // Similar to binary_map but with vectorized variants. pub fn binary_map_vec<T: Copy, F: FnMut(T, T) -> T, FV: FnMut(&[T], &[T], &mut [T])>( lhs_l: &Layout, rhs_l: &Layout, lhs: &[T], rhs: &[T], mut f: F, mut f_vec: FV, ) -> Vec<T> { let el_count = lhs_l.shape().elem_count(); match (lhs_l.contiguous_offsets(), rhs_l.contiguous_offsets()) { (Some((o_l1, o_l2)), Some((o_r1, o_r2))) => { let mut ys: Vec<T> = Vec::with_capacity(el_count); let ys_to_set = ys.spare_capacity_mut(); let ys_to_set = unsafe { std::mem::transmute::<&mut [std::mem::MaybeUninit<T>], &mut [T]>(ys_to_set) }; f_vec(&lhs[o_l1..o_l2], &rhs[o_r1..o_r2], ys_to_set); // SAFETY: values are all set by f_vec. unsafe { ys.set_len(el_count) }; ys } (Some((o_l1, o_l2)), None) => match rhs_l.offsets_b() { Some(ob) if ob.right_broadcast == 1 => { let rhs = &rhs[ob.start..ob.start + ob.len]; let mut ys: Vec<T> = Vec::with_capacity(el_count); let ys_to_set = ys.spare_capacity_mut(); let ys_to_set = unsafe { std::mem::transmute::<&mut [std::mem::MaybeUninit<T>], &mut [T]>(ys_to_set) }; let mut dst_i = 0; for src_i in (o_l1..o_l2).step_by(ob.len) { f_vec( &lhs[src_i..src_i + ob.len], rhs, &mut ys_to_set[dst_i..dst_i + ob.len], ); dst_i += ob.len; } // SAFETY: values are all set by f_vec. unsafe { ys.set_len(el_count) }; ys } Some(ob) => { let rhs = &rhs[ob.start..ob.start + ob.len]; let mut ys = lhs[o_l1..o_l2].to_vec(); for idx_l in 0..ob.left_broadcast { let start = idx_l * ob.len * ob.right_broadcast; for (i, &r) in rhs.iter().enumerate() { let start = start + i * ob.right_broadcast; for v in ys[start..start + ob.right_broadcast].iter_mut() { *v = f(*v, r) } } } ys } None => lhs_l .strided_index() .zip(rhs_l.strided_index()) .map(|(lhs_i, rhs_i)| f(lhs[lhs_i], rhs[rhs_i])) .collect(), }, (None, Some((o_r1, o_r2))) => match lhs_l.offsets_b() { Some(ob) if ob.right_broadcast == 1 => { let lhs = &lhs[ob.start..ob.start + ob.len]; let mut ys: Vec<T> = Vec::with_capacity(el_count); let ys_to_set = ys.spare_capacity_mut(); let ys_to_set = unsafe { std::mem::transmute::<&mut [std::mem::MaybeUninit<T>], &mut [T]>(ys_to_set) }; let mut dst_i = 0; for src_i in (o_r1..o_r2).step_by(ob.len) { f_vec( lhs, &rhs[src_i..src_i + ob.len], &mut ys_to_set[dst_i..dst_i + ob.len], ); dst_i += ob.len; } // SAFETY: values are all set by f_vec. unsafe { ys.set_len(el_count) }; ys } Some(ob) => { let lhs = &lhs[ob.start..ob.start + ob.len]; let mut ys = rhs[o_r1..o_r2].to_vec(); for idx_l in 0..ob.left_broadcast { let start = idx_l * ob.len * ob.right_broadcast; for (i, &l) in lhs.iter().enumerate() { let start = start + i * ob.right_broadcast; for v in ys[start..start + ob.right_broadcast].iter_mut() { *v = f(l, *v) } } } ys } None => lhs_l .strided_index() .zip(rhs_l.strided_index()) .map(|(lhs_i, rhs_i)| f(lhs[lhs_i], rhs[rhs_i])) .collect(), }, _ => lhs_l .strided_index() .zip(rhs_l.strided_index()) .map(|(lhs_i, rhs_i)| f(lhs[lhs_i], rhs[rhs_i])) .collect(), } } pub fn unary_map<T: Copy, U: Copy, F: FnMut(T) -> U>( vs: &[T], layout: &Layout, mut f: F, ) -> Vec<U> { match layout.strided_blocks() { crate::StridedBlocks::SingleBlock { start_offset, len } => vs [start_offset..start_offset + len] .iter() .map(|&v| f(v)) .collect(), crate::StridedBlocks::MultipleBlocks { block_start_index, block_len, } => { let mut result = Vec::with_capacity(layout.shape().elem_count()); // Specialize the case where block_len is one to avoid the second loop. if block_len == 1 { for index in block_start_index { let v = unsafe { vs.get_unchecked(index) }; result.push(f(*v)) } } else { for index in block_start_index { for offset in 0..block_len { let v = unsafe { vs.get_unchecked(index + offset) }; result.push(f(*v)) } } } result } } } pub fn unary_map_vec<T: Copy, U: Copy, F: FnMut(T) -> U, FV: FnMut(&[T], &mut [U])>( vs: &[T], layout: &Layout, mut f: F, mut f_vec: FV, ) -> Vec<U> { match layout.strided_blocks() { crate::StridedBlocks::SingleBlock { start_offset, len } => { let mut ys: Vec<U> = Vec::with_capacity(len); let ys_to_set = ys.spare_capacity_mut(); let ys_to_set = unsafe { std::mem::transmute::<&mut [std::mem::MaybeUninit<U>], &mut [U]>(ys_to_set) }; f_vec(&vs[start_offset..start_offset + len], ys_to_set); // SAFETY: values are all set by f_vec. unsafe { ys.set_len(len) }; ys } crate::StridedBlocks::MultipleBlocks { block_start_index, block_len, } => { let el_count = layout.shape().elem_count(); // Specialize the case where block_len is one to avoid the second loop. if block_len == 1 { let mut result = Vec::with_capacity(el_count); for index in block_start_index { let v = unsafe { vs.get_unchecked(index) }; result.push(f(*v)) } result } else { let mut ys: Vec<U> = Vec::with_capacity(el_count); let ys_to_set = ys.spare_capacity_mut(); let ys_to_set = unsafe { std::mem::transmute::<&mut [std::mem::MaybeUninit<U>], &mut [U]>(ys_to_set) }; let mut dst_index = 0; for src_index in block_start_index { let vs = &vs[src_index..src_index + block_len]; let ys = &mut ys_to_set[dst_index..dst_index + block_len]; f_vec(vs, ys); dst_index += block_len; } // SAFETY: values are all set by f_vec. unsafe { ys.set_len(el_count) }; ys } } } }
candle/candle-core/src/cpu_backend/utils.rs/0
{ "file_path": "candle/candle-core/src/cpu_backend/utils.rs", "repo_id": "candle", "token_count": 9870 }
28
use crate::{DType, Result}; use candle_metal_kernels::Kernels; use metal::{Buffer, CommandBuffer, CommandQueue, MTLResourceOptions, NSUInteger}; use std::collections::HashMap; use std::path::Path; use std::sync::{Arc, Mutex, RwLock}; use super::MetalError; /// Unique identifier for cuda devices. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct DeviceId(usize); impl DeviceId { pub(crate) fn new() -> Self { // https://users.rust-lang.org/t/idiomatic-rust-way-to-generate-unique-id/33805 use std::sync::atomic; static COUNTER: atomic::AtomicUsize = atomic::AtomicUsize::new(1); Self(COUNTER.fetch_add(1, atomic::Ordering::Relaxed)) } } type BufferMap = HashMap<(NSUInteger, MTLResourceOptions), Vec<Arc<Buffer>>>; pub(crate) struct Commands { /// Single command queue for the entire device. command_queue: CommandQueue, /// One command buffer at a time. /// The scheduler works by allowing multiple /// [ComputeCommandEncoder](https://developer.apple.com/documentation/metal/mtlcomputecommandencoder?language=objc) /// on a single command buffer. Using a single command buffer would be fastest on the GPU but /// prevents overlapping of CPU and GPU commands (because command buffer needs to be committed /// to start to work). /// Despite what the documentation says, command buffers are NOT ordered. They are ordered /// for their START time, but there's no guarantee that command buffer1 will finish before /// command buffer2 starts (or there are metal bugs there) command_buffer: CommandBuffer, /// Keeps track of the current amount of compute command encoders on the current /// command buffer /// Arc, RwLock because of the interior mutability. command_buffer_index: usize, /// The maximum amount of [compute command encoder](https://developer.apple.com/documentation/metal/mtlcomputecommandencoder?language=objc) per [command buffer](https://developer.apple.com/documentation/metal/mtlcommandbuffer?language=objc) compute_per_buffer: usize, } impl Commands { pub(crate) fn new(command_queue: CommandQueue) -> Result<Self> { let command_buffer = command_queue.new_command_buffer().to_owned(); command_buffer.enqueue(); let compute_per_buffer = match std::env::var("CANDLE_METAL_COMPUTE_PER_BUFFER") { Ok(val) => val.parse()?, _ => 50, }; Ok(Self { command_queue, command_buffer, command_buffer_index: 0, compute_per_buffer, }) } pub fn command_buffer(&mut self) -> Result<(bool, CommandBuffer)> { let mut command_buffer = self.command_buffer.to_owned(); let mut flushed = false; if self.command_buffer_index > self.compute_per_buffer { self.command_buffer.commit(); command_buffer = self.command_queue.new_command_buffer().to_owned(); self.command_buffer = command_buffer.clone(); self.command_buffer_index = 0; flushed = true; } self.command_buffer_index += 1; Ok((flushed, command_buffer)) } pub fn wait_until_completed(&mut self) -> Result<()> { match self.command_buffer.status() { metal::MTLCommandBufferStatus::Committed | metal::MTLCommandBufferStatus::Scheduled | metal::MTLCommandBufferStatus::Completed => { panic!("Already committed"); } _ => {} } self.command_buffer.commit(); self.command_buffer.wait_until_completed(); self.command_buffer = self.command_queue.new_command_buffer().to_owned(); Ok(()) } } #[derive(Clone)] pub struct MetalDevice { /// Unique identifier, the registryID is not sufficient as it identifies the GPU rather than /// the device itself. pub(crate) id: DeviceId, /// Raw metal device: <https://developer.apple.com/documentation/metal/mtldevice?language=objc> pub(crate) device: metal::Device, pub(crate) commands: Arc<RwLock<Commands>>, /// Simple allocator struct. /// The buffers are stored in size buckets since ML tends to use similar shapes over and over. /// We store the buffers in [`Arc`] because it's much faster than Obj-c internal ref counting /// (could be linked to FFI communication overhead). /// /// Whenever a buffer has a strong_count==1, we can reuse it, it means it was dropped in the /// graph calculation, and only we the allocator kept a reference to it, therefore it's free /// to be reused. However, in order for this to work, we need to guarantee the order of /// operation, so that this buffer is not being used by another kernel at the same time. /// Arc is the CPU reference count, it doesn't mean anything on the GPU side of things. /// /// Whenever we actually allocate a new buffer, we make a full sweep to clean up unused buffers /// (strong_count = 1). pub(crate) buffers: Arc<RwLock<BufferMap>>, /// Simple keeper struct to keep track of the already compiled kernels so we can reuse them. /// Heavily used by [`candle_metal_kernels`] pub(crate) kernels: Arc<Kernels>, /// Seed for random number generation. pub(crate) seed: Arc<Mutex<Buffer>>, } impl std::fmt::Debug for MetalDevice { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "MetalDevice({:?})", self.id) } } impl std::ops::Deref for MetalDevice { type Target = metal::DeviceRef; fn deref(&self) -> &Self::Target { &self.device } } impl MetalDevice { #[cfg(not(target_arch = "wasm32"))] pub fn compile( &self, func_name: &'static str, kernel: ug::lang::ssa::Kernel, ) -> Result<metal::ComputePipelineState> { let mut buf = vec![]; ug_metal::code_gen::gen(&mut buf, func_name, &kernel)?; let metal_code = String::from_utf8(buf)?; let lib = self .device .new_library_with_source(&metal_code, &metal::CompileOptions::new()) .map_err(MetalError::from)?; let func = lib .get_function(func_name, None) .map_err(MetalError::from)?; let pl = self .device .new_compute_pipeline_state_with_function(&func) .map_err(MetalError::from)?; Ok(pl) } pub fn id(&self) -> DeviceId { self.id } pub fn metal_device(&self) -> &metal::Device { &self.device } fn drop_unused_buffers(&self) -> Result<()> { let mut buffers = self.buffers.write().map_err(MetalError::from)?; for subbuffers in buffers.values_mut() { let newbuffers = subbuffers .iter() .filter(|s| Arc::strong_count(*s) > 1) .map(Arc::clone) .collect(); *subbuffers = newbuffers; } Ok(()) } pub fn command_buffer(&self) -> Result<CommandBuffer> { let mut commands = self.commands.write().map_err(MetalError::from)?; let (flushed, command_buffer) = commands.command_buffer()?; if flushed { self.drop_unused_buffers()? } Ok(command_buffer) } pub fn wait_until_completed(&self) -> Result<()> { let mut commands = self.commands.write().map_err(MetalError::from)?; commands.wait_until_completed() } pub fn kernels(&self) -> &Kernels { &self.kernels } pub fn device(&self) -> &metal::Device { &self.device } /// Creates a new buffer (not necessarily zeroed). /// The buffer is [MTLPrivate](https://developer.apple.com/documentation/metal/mtlstoragemode) /// This means the buffer data cannot be read on the CPU directly. /// /// [`name`] is only used to keep track of the resource origin in case of bugs pub fn new_buffer( &self, element_count: usize, dtype: DType, name: &str, ) -> Result<Arc<Buffer>> { let size = (element_count * dtype.size_in_bytes()) as NSUInteger; self.allocate_buffer(size, MTLResourceOptions::StorageModePrivate, name) } /// Creates a new buffer (not necessarily zeroed). /// The buffer is [MTLManaged](https://developer.apple.com/documentation/metal/mtlstoragemode) /// This means the buffer can be read on the CPU but will require manual /// synchronization when the CPU memory is modified /// Used as a bridge to gather data back from the GPU pub fn new_buffer_managed(&self, size: NSUInteger) -> Result<Arc<Buffer>> { self.allocate_buffer(size, MTLResourceOptions::StorageModeManaged, "managed") } /// Creates a new buffer from data. /// The buffer is [MTLManaged](https://developer.apple.com/documentation/metal/mtlstoragemode) /// /// Does not require synchronization, as [newBufferWithBytes](https://developer.apple.com/documentation/metal/mtldevice/1433429-newbufferwithbytes) /// allocates the buffer and copies over the existing data before returning the MTLBuffer. pub fn new_buffer_with_data<T>(&self, data: &[T]) -> Result<Arc<Buffer>> { let size = core::mem::size_of_val(data) as NSUInteger; let new_buffer = self.device.new_buffer_with_data( data.as_ptr().cast(), size, MTLResourceOptions::StorageModeManaged, ); let mut buffers = self.buffers.write().map_err(MetalError::from)?; let subbuffers = buffers .entry((size, MTLResourceOptions::StorageModeManaged)) .or_insert(vec![]); let new_buffer = Arc::new(new_buffer); subbuffers.push(new_buffer.clone()); Ok(new_buffer) } pub fn allocate_zeros(&self, size_in_bytes: usize) -> Result<Arc<Buffer>> { let buffer = self.allocate_buffer( size_in_bytes as NSUInteger, MTLResourceOptions::StorageModePrivate, "allocate_zeros", )?; let command_buffer = self.command_buffer()?; command_buffer.set_label("zeros"); let blit = command_buffer.new_blit_command_encoder(); blit.fill_buffer( &buffer, metal::NSRange { location: 0, length: buffer.length(), }, 0, ); blit.end_encoding(); Ok(buffer) } /// The critical allocator algorithm fn allocate_buffer( &self, size: NSUInteger, option: MTLResourceOptions, _name: &str, ) -> Result<Arc<Buffer>> { let mut buffers = self.buffers.write().map_err(MetalError::from)?; if let Some(b) = find_available_buffer(size, option, &buffers) { // Cloning also ensures we increment the strong count return Ok(b.clone()); } let size = buf_size(size); let subbuffers = buffers.entry((size, option)).or_insert(vec![]); let new_buffer = self.device.new_buffer(size as NSUInteger, option); let new_buffer = Arc::new(new_buffer); subbuffers.push(new_buffer.clone()); Ok(new_buffer) } /// Create a metal GPU capture trace on [`path`]. pub fn capture<P: AsRef<Path>>(&self, path: P) -> Result<()> { let capture = metal::CaptureManager::shared(); let descriptor = metal::CaptureDescriptor::new(); descriptor.set_destination(metal::MTLCaptureDestination::GpuTraceDocument); descriptor.set_capture_device(self); // The [set_output_url] call requires an absolute path so we convert it if needed. if path.as_ref().is_absolute() { descriptor.set_output_url(path); } else { let path = std::env::current_dir()?.join(path); descriptor.set_output_url(path); } capture .start_capture(&descriptor) .map_err(MetalError::from)?; Ok(()) } } fn buf_size(size: NSUInteger) -> NSUInteger { size.saturating_sub(1).next_power_of_two() as NSUInteger } fn find_available_buffer( size: NSUInteger, option: MTLResourceOptions, buffers: &BufferMap, ) -> Option<Arc<Buffer>> { let mut best_buffer: Option<&Arc<Buffer>> = None; let mut best_buffer_size: NSUInteger = NSUInteger::MAX; for ((buffer_size, buffer_option), subbuffers) in buffers.iter() { if buffer_size >= &size && buffer_size < &best_buffer_size && buffer_option == &option { for sub in subbuffers { if Arc::strong_count(sub) == 1 { best_buffer = Some(sub); best_buffer_size = *buffer_size; } } } } best_buffer.cloned() }
candle/candle-core/src/metal_backend/device.rs/0
{ "file_path": "candle/candle-core/src/metal_backend/device.rs", "repo_id": "candle", "token_count": 5226 }
29
use super::k_quants::{BlockQ2K, BlockQ4K, BlockQ4_0, BlockQ6K, BlockQ8K, BlockQ8_0, QK8_0, QK_K}; use crate::Result; use byteorder::{ByteOrder, LittleEndian}; use half::f16; use core::arch::wasm32::*; #[inline(always)] pub(crate) fn vec_dot_q4_0_q8_0(n: usize, xs: &[BlockQ4_0], ys: &[BlockQ8_0]) -> Result<f32> { let qk = QK8_0; if n % QK8_0 != 0 { crate::bail!("vec_dot_q4_0_q8_0: {n} is not divisible by {qk}") } unsafe { let mut acc = f32x4_splat(0.0f32); for (x, y) in xs.iter().zip(ys.iter()) { let x1234 = v128_load(x.qs.as_ptr() as *const v128); let x12 = v128_and(x1234, u8x16_splat(0x0F)); let x12 = i8x16_sub(x12, i8x16_splat(8)); let x34 = u8x16_shr(x1234, 4); let x34 = i8x16_sub(x34, i8x16_splat(8)); let x1 = i16x8_extend_low_i8x16(x12); let y1 = i16x8_load_extend_i8x8(y.qs.as_ptr()); let sum_xy = i32x4_dot_i16x8(x1, y1); let x2 = i16x8_extend_high_i8x16(x12); let y2 = i16x8_load_extend_i8x8(y.qs.as_ptr().add(8)); let sum_xy = i32x4_add(sum_xy, i32x4_dot_i16x8(x2, y2)); let x3 = i16x8_extend_low_i8x16(x34); let y3 = i16x8_load_extend_i8x8(y.qs.as_ptr().add(16)); let sum_xy = i32x4_add(sum_xy, i32x4_dot_i16x8(x3, y3)); let x4 = i16x8_extend_high_i8x16(x34); let y4 = i16x8_load_extend_i8x8(y.qs.as_ptr().add(24)); let sum_xy = i32x4_add(sum_xy, i32x4_dot_i16x8(x4, y4)); let sum_xy = f32x4_convert_i32x4(sum_xy); // f32x4_relaxed_madd is nightly only. let d = f32x4_splat(f16::to_f32(x.d) * f16::to_f32(y.d)); let scaled = f32x4_mul(sum_xy, d); acc = f32x4_add(acc, scaled) } let res = f32x4_extract_lane::<0>(acc) + f32x4_extract_lane::<1>(acc) + f32x4_extract_lane::<2>(acc) + f32x4_extract_lane::<3>(acc); Ok(res) } } #[inline(always)] pub(crate) fn vec_dot_q8_0_q8_0(n: usize, xs: &[BlockQ8_0], ys: &[BlockQ8_0]) -> Result<f32> { let qk = QK8_0; if n % QK8_0 != 0 { crate::bail!("vec_dot_q8_0_q8_0: {n} is not divisible by {qk}") } unsafe { let mut acc = f32x4_splat(0.0f32); for (x, y) in xs.iter().zip(ys.iter()) { let x1 = i16x8_load_extend_i8x8(x.qs.as_ptr()); let y1 = i16x8_load_extend_i8x8(y.qs.as_ptr()); let sum_xy = i32x4_dot_i16x8(x1, y1); let x2 = i16x8_load_extend_i8x8(x.qs.as_ptr().add(8)); let y2 = i16x8_load_extend_i8x8(y.qs.as_ptr().add(8)); let sum_xy = i32x4_add(sum_xy, i32x4_dot_i16x8(x2, y2)); let x3 = i16x8_load_extend_i8x8(x.qs.as_ptr().add(16)); let y3 = i16x8_load_extend_i8x8(y.qs.as_ptr().add(16)); let sum_xy = i32x4_add(sum_xy, i32x4_dot_i16x8(x3, y3)); let x4 = i16x8_load_extend_i8x8(x.qs.as_ptr().add(24)); let y4 = i16x8_load_extend_i8x8(y.qs.as_ptr().add(24)); let sum_xy = i32x4_add(sum_xy, i32x4_dot_i16x8(x4, y4)); let sum_xy = f32x4_convert_i32x4(sum_xy); // f32x4_relaxed_madd is nightly only. let d = f32x4_splat(f16::to_f32(x.d) * f16::to_f32(y.d)); let scaled = f32x4_mul(sum_xy, d); acc = f32x4_add(acc, scaled) } let res = f32x4_extract_lane::<0>(acc) + f32x4_extract_lane::<1>(acc) + f32x4_extract_lane::<2>(acc) + f32x4_extract_lane::<3>(acc); Ok(res) } } #[inline(always)] pub(crate) fn vec_dot_q2k_q8k(n: usize, xs: &[BlockQ2K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q2k_q8k: {n} is not divisible by {QK_K}") } unsafe { let mut sumf = f32x4_splat(0f32); for (x, y) in xs.iter().zip(ys.iter()) { let mut q2: &[_] = &x.qs; let mut q8: &[_] = &y.qs; let sc = &x.scales; let mut summs = i32x4_splat(0); for i in (0..(QK_K / 16)).step_by(4) { let bsums = i32x4_load_extend_i16x4(y.bsums.as_ptr().add(i)); let scales = i32x4_shr( i32x4( sc[i] as i32, sc[i + 1] as i32, sc[i + 2] as i32, sc[i + 3] as i32, ), 4, ); summs = i32x4_add(summs, i32x4_mul(bsums, scales)) } let summs = f32x4_convert_i32x4(summs); let dall = y.d * x.d.to_f32(); let dmin = y.d * x.dmin.to_f32(); let mut isum = i32x4_splat(0); let mut is = 0; for _ in 0..(QK_K / 128) { let mut shift = 0; for _ in 0..4 { let d = (sc[is] & 0xF) as i32; is += 1; let mut isuml = i16x8_splat(0); for l in (0..16).step_by(8) { let q8 = i16x8_load_extend_i8x8(q8.as_ptr().add(l)); let q2 = i16x8_load_extend_u8x8(q2.as_ptr().add(l)); let q2 = v128_and(i16x8_shr(q2, shift), i16x8_splat(3)); isuml = i16x8_add(isuml, i16x8_mul(q2, q8)) } let dd = i32x4_splat(d); isum = i32x4_add(isum, i32x4_mul(i32x4_extend_low_i16x8(isuml), dd)); isum = i32x4_add(isum, i32x4_mul(i32x4_extend_high_i16x8(isuml), dd)); let d = (sc[is] & 0xF) as i32; is += 1; let mut isuml = i16x8_splat(0); for l in (16..32).step_by(8) { let q8 = i16x8_load_extend_i8x8(q8.as_ptr().add(l)); let q2 = i16x8_load_extend_u8x8(q2.as_ptr().add(l)); let q2 = v128_and(i16x8_shr(q2, shift), i16x8_splat(3)); isuml = i16x8_add(isuml, i16x8_mul(q2, q8)) } let dd = i32x4_splat(d); isum = i32x4_add(isum, i32x4_mul(i32x4_extend_low_i16x8(isuml), dd)); isum = i32x4_add(isum, i32x4_mul(i32x4_extend_high_i16x8(isuml), dd)); shift += 2; // adjust the indexing q8 = &q8[32..]; } // adjust the indexing q2 = &q2[32..]; } let isum = f32x4_convert_i32x4(isum); sumf = f32x4_add( sumf, f32x4_sub( f32x4_mul(isum, f32x4_splat(dall)), f32x4_mul(summs, f32x4_splat(dmin)), ), ); } let sumf = f32x4_extract_lane::<0>(sumf) + f32x4_extract_lane::<1>(sumf) + f32x4_extract_lane::<2>(sumf) + f32x4_extract_lane::<3>(sumf); Ok(sumf) } } #[inline(always)] pub(crate) fn vec_dot_q4k_q8k(n: usize, xs: &[BlockQ4K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q4k_q8k: {n} is not divisible by {QK_K}") } const KMASK1: u32 = 0x3f3f3f3f; const KMASK2: u32 = 0x0f0f0f0f; const KMASK3: u32 = 0x03030303; let mut utmp: [u32; 4] = [0; 4]; let mut scales: [u8; 8] = [0; 8]; let mut mins: [u8; 8] = [0; 8]; let mut aux8: [u8; QK_K] = [0; QK_K]; let mut sums = f32x4_splat(0f32); unsafe { for (y, x) in ys.iter().zip(xs.iter()) { let q4 = &x.qs; let q8 = &y.qs; for j in 0..QK_K / 64 { let q4_1 = v128_load(q4.as_ptr().add(32 * j) as *const v128); let q4_2 = v128_load(q4.as_ptr().add(32 * j + 16) as *const v128); v128_store( aux8.as_mut_ptr().add(64 * j) as *mut v128, v128_and(q4_1, u8x16_splat(0x0F)), ); v128_store( aux8.as_mut_ptr().add(64 * j + 16) as *mut v128, v128_and(q4_2, u8x16_splat(0x0F)), ); v128_store( aux8.as_mut_ptr().add(64 * j + 32) as *mut v128, u8x16_shr(q4_1, 4), ); v128_store( aux8.as_mut_ptr().add(64 * j + 48) as *mut v128, u8x16_shr(q4_2, 4), ); } LittleEndian::read_u32_into(&x.scales, &mut utmp[0..3]); utmp[3] = ((utmp[2] >> 4) & KMASK2) | (((utmp[1] >> 6) & KMASK3) << 4); let uaux = utmp[1] & KMASK1; utmp[1] = (utmp[2] & KMASK2) | (((utmp[0] >> 6) & KMASK3) << 4); utmp[2] = uaux; utmp[0] &= KMASK1; //extract scales and mins LittleEndian::write_u32_into(&utmp[0..2], &mut scales); LittleEndian::write_u32_into(&utmp[2..4], &mut mins); let mut sumi = i32x4_splat(0); for j in (0..QK_K / 16).step_by(4) { let bsums = i32x4_load_extend_i16x4(y.bsums.as_ptr().add(j)); let (m1, m2) = (mins[j / 2] as i32, mins[j / 2 + 1] as i32); let mins = i32x4(m1, m1, m2, m2); sumi = i32x4_add(sumi, i32x4_mul(bsums, mins)); } let mut aux32 = i32x4_splat(0i32); for (scale_i, scale) in scales.iter().enumerate() { let scale = i32x4_splat(*scale as i32); for j in 0..4 { let i = 32 * scale_i + 8 * j; let q8 = i16x8_load_extend_i8x8(q8.as_ptr().add(i)); let aux8 = i16x8_load_extend_u8x8(aux8.as_ptr().add(i)); let aux16 = i16x8_mul(q8, aux8); aux32 = i32x4_add(aux32, i32x4_mul(scale, i32x4_extend_low_i16x8(aux16))); aux32 = i32x4_add(aux32, i32x4_mul(scale, i32x4_extend_high_i16x8(aux16))); } } let aux32 = f32x4_convert_i32x4(aux32); let d = f32x4_splat(x.d.to_f32() * y.d); sums = f32x4_add(sums, f32x4_mul(aux32, d)); let dmin = x.dmin.to_f32() * y.d; let dmin = f32x4_splat(dmin); let sumi = f32x4_convert_i32x4(sumi); sums = f32x4_sub(sums, f32x4_mul(sumi, dmin)); } let sums = f32x4_extract_lane::<0>(sums) + f32x4_extract_lane::<1>(sums) + f32x4_extract_lane::<2>(sums) + f32x4_extract_lane::<3>(sums); Ok(sums) } } #[inline(always)] pub(crate) fn vec_dot_q6k_q8k(n: usize, xs: &[BlockQ6K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q6k_q8k: {n} is not divisible by {QK_K}") } let mut aux8 = [0i8; QK_K]; unsafe { let mut sums = f32x4_splat(0f32); for (x, y) in xs.iter().zip(ys.iter()) { let q4 = &x.ql; let qh = &x.qh; let q8 = &y.qs; let mut aux32 = f32x4_splat(0f32); for j in (0..QK_K).step_by(128) { let aux8 = aux8.as_mut_ptr().add(j); let q4 = &q4.as_ptr().add(j / 2); let qh = &qh.as_ptr().add(j / 4); for l in (0..32).step_by(16) { // aux8[l] = (((q4[l] & 0xF) | ((qh[l] & 3) << 4)) as i32 - 32) as i8; let a8 = v128_or( v128_and(v128_load(q4.add(l) as *const v128), u8x16_splat(0xF)), u8x16_shl( v128_and(v128_load(qh.add(l) as *const v128), u8x16_splat(3)), 4, ), ); let a8_low = i16x8_sub(i16x8_extend_low_u8x16(a8), i16x8_splat(32)); let a8_high = i16x8_sub(i16x8_extend_high_u8x16(a8), i16x8_splat(32)); v128_store( aux8.add(l) as *mut v128, i8x16_narrow_i16x8(a8_low, a8_high), ); // aux8[l + 32] = // (((q4[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) as i32 - 32) as i8; let a8 = v128_or( v128_and(v128_load(q4.add(l + 32) as *const v128), u8x16_splat(0xF)), u8x16_shl( v128_and( u8x16_shr(v128_load(qh.add(l) as *const v128), 2), u8x16_splat(3), ), 4, ), ); let a8_low = i16x8_sub(i16x8_extend_low_u8x16(a8), i16x8_splat(32)); let a8_high = i16x8_sub(i16x8_extend_high_u8x16(a8), i16x8_splat(32)); v128_store( aux8.add(l + 32) as *mut v128, i8x16_narrow_i16x8(a8_low, a8_high), ); // aux8[l + 64] = (((q4[l] >> 4) | (((qh[l] >> 4) & 3) << 4)) as i32 - 32) as i8; let a8 = v128_or( u8x16_shr(v128_load(q4.add(l) as *const v128), 4), u8x16_shl( v128_and( u8x16_shr(v128_load(qh.add(l) as *const v128), 4), u8x16_splat(3), ), 4, ), ); let a8_low = i16x8_sub(i16x8_extend_low_u8x16(a8), i16x8_splat(32)); let a8_high = i16x8_sub(i16x8_extend_high_u8x16(a8), i16x8_splat(32)); v128_store( aux8.add(l + 64) as *mut v128, i8x16_narrow_i16x8(a8_low, a8_high), ); // aux8[l + 96] = // (((q4[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) as i32 - 32) as i8; let a8 = v128_or( u8x16_shr(v128_load(q4.add(l + 32) as *const v128), 4), u8x16_shl( v128_and( u8x16_shr(v128_load(qh.add(l) as *const v128), 6), u8x16_splat(3), ), 4, ), ); let a8_low = i16x8_sub(i16x8_extend_low_u8x16(a8), i16x8_splat(32)); let a8_high = i16x8_sub(i16x8_extend_high_u8x16(a8), i16x8_splat(32)); v128_store( aux8.add(l + 96) as *mut v128, i8x16_narrow_i16x8(a8_low, a8_high), ); } } for (j, &scale) in x.scales.iter().enumerate() { let scale = f32x4_splat(scale as f32); for offset in [0, 8] { let aux16 = i16x8_mul( i16x8_load_extend_i8x8(q8.as_ptr().add(16 * j + offset)), i16x8_load_extend_i8x8(aux8.as_ptr().add(16 * j + offset)), ); aux32 = f32x4_add( aux32, f32x4_mul(f32x4_convert_i32x4(i32x4_extend_low_i16x8(aux16)), scale), ); aux32 = f32x4_add( aux32, f32x4_mul(f32x4_convert_i32x4(i32x4_extend_high_i16x8(aux16)), scale), ); } } let d = f32x4_splat(x.d.to_f32() * y.d); sums = f32x4_add(sums, f32x4_mul(aux32, d)); } let sums = f32x4_extract_lane::<0>(sums) + f32x4_extract_lane::<1>(sums) + f32x4_extract_lane::<2>(sums) + f32x4_extract_lane::<3>(sums); Ok(sums) } } #[inline(always)] pub(crate) fn vec_dot_q8k_q8k(n: usize, xs: &[BlockQ8K], ys: &[BlockQ8K]) -> Result<f32> { let qk = QK_K; if n % QK_K != 0 { crate::bail!("vec_dot_q8k_q8k: {n} is not divisible by {qk}") } unsafe { let mut acc = f32x4_splat(0.0f32); for (xs, ys) in xs.iter().zip(ys.iter()) { let x_qs = xs.qs.as_ptr(); let y_qs = ys.qs.as_ptr(); let mut sumi = i32x4_splat(0); for j in (0..QK_K).step_by(8) { let xs = i16x8_load_extend_i8x8(x_qs.add(j)); let ys = i16x8_load_extend_i8x8(y_qs.add(j)); let sum_xy = i32x4_dot_i16x8(xs, ys); sumi = i32x4_add(sumi, sum_xy) } let d = f32x4_splat(xs.d * ys.d); acc = f32x4_add(acc, f32x4_mul(f32x4_convert_i32x4(sumi), d)) } let res = f32x4_extract_lane::<0>(acc) + f32x4_extract_lane::<1>(acc) + f32x4_extract_lane::<2>(acc) + f32x4_extract_lane::<3>(acc); Ok(res) } }
candle/candle-core/src/quantized/simd128.rs/0
{ "file_path": "candle/candle-core/src/quantized/simd128.rs", "repo_id": "candle", "token_count": 11617 }
30
use anyhow::Result; use candle_core::{DType, Device::Cpu, Tensor}; #[test] fn display_scalar() -> Result<()> { let t = Tensor::new(1234u32, &Cpu)?; let s = format!("{t}"); assert_eq!(&s, "[1234]\nTensor[[], u32]"); let t = t.to_dtype(DType::F32)?.neg()?; let s = format!("{}", (&t / 10.0)?); assert_eq!(&s, "[-123.4000]\nTensor[[], f32]"); let s = format!("{}", (&t / 1e8)?); assert_eq!(&s, "[-1.2340e-5]\nTensor[[], f32]"); let s = format!("{}", (&t * 1e8)?); assert_eq!(&s, "[-1.2340e11]\nTensor[[], f32]"); let s = format!("{}", (&t * 0.)?); assert_eq!(&s, "[0.]\nTensor[[], f32]"); Ok(()) } #[test] fn display_vector() -> Result<()> { let t = Tensor::new::<&[u32; 0]>(&[], &Cpu)?; let s = format!("{t}"); assert_eq!(&s, "[]\nTensor[[0], u32]"); let t = Tensor::new(&[0.1234567, 1.0, -1.2, 4.1, f64::NAN], &Cpu)?; let s = format!("{t}"); assert_eq!( &s, "[ 0.1235, 1.0000, -1.2000, 4.1000, NaN]\nTensor[[5], f64]" ); let t = (Tensor::ones(50, DType::F32, &Cpu)? * 42.)?; let s = format!("\n{t}"); let expected = r#" [42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42., 42.] Tensor[[50], f32]"#; assert_eq!(&s, expected); let t = (Tensor::ones(11000, DType::F32, &Cpu)? * 42.)?; let s = format!("{t}"); assert_eq!( &s, "[42., 42., 42., ..., 42., 42., 42.]\nTensor[[11000], f32]" ); Ok(()) } #[test] fn display_multi_dim() -> Result<()> { let t = (Tensor::ones((200, 100), DType::F32, &Cpu)? * 42.)?; let s = format!("\n{t}"); let expected = r#" [[42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.], ... [42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.]] Tensor[[200, 100], f32]"#; assert_eq!(&s, expected); let t = t.reshape(&[2, 1, 1, 100, 100])?; let t = format!("\n{t}"); let expected = r#" [[[[[42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.], ... [42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.]]]], [[[[42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.], ... [42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.], [42., 42., 42., ..., 42., 42., 42.]]]]] Tensor[[2, 1, 1, 100, 100], f32]"#; assert_eq!(&t, expected); Ok(()) }
candle/candle-core/tests/display_tests.rs/0
{ "file_path": "candle/candle-core/tests/display_tests.rs", "repo_id": "candle", "token_count": 1395 }
31
use candle::{DType, Device, Tensor}; use candle_nn::VarBuilder; use candle_transformers::generation::LogitsProcessor; use candle_transformers::models::codegeex4_9b::*; use clap::Parser; use hf_hub::{Repo, RepoType}; use tokenizers::Tokenizer; struct TextGeneration { model: Model, device: Device, tokenizer: Tokenizer, logits_processor: LogitsProcessor, repeat_penalty: f32, repeat_last_n: usize, verbose: bool, dtype: DType, } impl TextGeneration { #[allow(clippy::too_many_arguments)] fn new( model: Model, tokenizer: Tokenizer, seed: u64, temp: f64, top_p: f64, repeat_penalty: f32, repeat_last_n: usize, verbose: bool, device: &Device, dtype: DType, ) -> Self { let logits_processor = LogitsProcessor::new(seed, Some(temp), Some(top_p)); Self { model, tokenizer, logits_processor, repeat_penalty, repeat_last_n, verbose, device: device.clone(), dtype, } } fn run(&mut self, prompt: &str, sample_len: usize) -> anyhow::Result<()> { use std::io::Write; println!("starting the inference loop"); let tokens = self.tokenizer.encode(prompt, true).expect("tokens error"); if tokens.is_empty() { panic!("Empty prompts are not supported in the chatglm model.") } if self.verbose { for (token, id) in tokens.get_tokens().iter().zip(tokens.get_ids().iter()) { let token = token.replace('▁', " ").replace("<0x0A>", "\n"); println!("{id:7} -> '{token}'"); } } let eos_token = match self.tokenizer.get_vocab(true).get("<|endoftext|>") { Some(token) => *token, None => panic!("cannot find the endoftext token"), }; let mut tokens = tokens.get_ids().to_vec(); let mut generated_tokens = 0usize; print!("{prompt}"); std::io::stdout().flush().expect("output flush error"); let start_gen = std::time::Instant::now(); println!("\n start_gen"); println!("samplelen {sample_len}"); let mut count = 0; let mut result = vec![]; for index in 0..sample_len { count += 1; let context_size = if index > 0 { 1 } else { tokens.len() }; let ctxt = &tokens[tokens.len().saturating_sub(context_size)..]; let input = Tensor::new(ctxt, &self.device)?.unsqueeze(0)?; let logits = self.model.forward(&input)?; let logits = logits.squeeze(0)?.to_dtype(self.dtype)?; let logits = if self.repeat_penalty == 1. { logits } else { let start_at = tokens.len().saturating_sub(self.repeat_last_n); candle_transformers::utils::apply_repeat_penalty( &logits, self.repeat_penalty, &tokens[start_at..], )? }; let next_token = self.logits_processor.sample(&logits)?; tokens.push(next_token); generated_tokens += 1; if next_token == eos_token { break; } let token = self .tokenizer .decode(&[next_token], true) .expect("Token error"); if self.verbose { println!("[Count: {count}] [Raw Token: {next_token}] [Decode Token: {token}]"); } result.push(token); std::io::stdout().flush()?; } let dt = start_gen.elapsed(); println!( "\n{generated_tokens} tokens generated ({:.2} token/s)", generated_tokens as f64 / dt.as_secs_f64(), ); println!("Result:"); for tokens in result { print!("{tokens}"); } Ok(()) } } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { #[arg(name = "cache", short)] cache_path: Option<String>, /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Display the token for the specified prompt. #[arg(long)] prompt: String, /// Display the tokens for the specified prompt and outputs. #[arg(long)] verbose: bool, /// The temperature used to generate samples. #[arg(long, default_value_t = 0.95)] temperature: f64, /// Nucleus sampling probability cutoff. #[arg(long, default_value_t = 0.8)] top_p: f64, /// The seed to use when generating random samples. #[arg(long, default_value_t = 299792458)] seed: u64, /// The length of the sample to generate (in tokens). #[arg(long, short = 'n', default_value_t = 8192)] sample_len: usize, #[arg(long)] model_id: Option<String>, #[arg(long)] revision: Option<String>, #[arg(long)] weight_path: Option<String>, #[arg(long)] tokenizer: Option<String>, /// Penalty to be applied for repeating tokens, 1. means no penalty. #[arg(long, default_value_t = 1.2)] repeat_penalty: f32, /// The context size to consider for the repeat penalty. #[arg(long, default_value_t = 64)] repeat_last_n: usize, } fn main() -> anyhow::Result<()> { let args = Args::parse(); println!( "avx: {}, neon: {}, simd128: {}, f16c: {}", candle::utils::with_avx(), candle::utils::with_neon(), candle::utils::with_simd128(), candle::utils::with_f16c() ); println!( "temp: {:.2} repeat-penalty: {:.2} repeat-last-n: {}", args.temperature, args.repeat_penalty, args.repeat_last_n ); let start = std::time::Instant::now(); let api = match args.cache_path.as_ref() { None => hf_hub::api::sync::Api::new()?, Some(path) => { hf_hub::api::sync::ApiBuilder::from_cache(hf_hub::Cache::new(path.to_string().into())) .build() .map_err(anyhow::Error::msg)? } }; let model_id = match args.model_id { Some(model_id) => model_id.to_string(), None => "THUDM/codegeex4-all-9b".to_string(), }; let revision = match args.revision { Some(rev) => rev.to_string(), None => "main".to_string(), }; let repo = api.repo(Repo::with_revision(model_id, RepoType::Model, revision)); let tokenizer_filename = match args.tokenizer { Some(file) => std::path::PathBuf::from(file), None => api .model("THUDM/codegeex4-all-9b".to_string()) .get("tokenizer.json") .map_err(anyhow::Error::msg)?, }; let config_filename = match &args.weight_path { Some(path) => std::path::Path::new(path).join("config.json"), None => repo.get("config.json")?, }; let filenames = match &args.weight_path { Some(path) => { candle_examples::hub_load_local_safetensors(path, "model.safetensors.index.json")? } _ => candle_examples::hub_load_safetensors(&repo, "model.safetensors.index.json")?, }; println!("retrieved the files in {:?}", start.elapsed()); let tokenizer = Tokenizer::from_file(tokenizer_filename).expect("Tokenizer Error"); let start = std::time::Instant::now(); let config: Config = serde_json::from_slice(&std::fs::read(config_filename)?)?; let device = candle_examples::device(args.cpu)?; let dtype = if device.is_cuda() { DType::BF16 } else { DType::F32 }; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, &device)? }; let model = Model::new(&config, vb)?; println!("loaded the model in {:?}", start.elapsed()); let mut pipeline = TextGeneration::new( model, tokenizer, args.seed, args.temperature, args.top_p, args.repeat_penalty, args.repeat_last_n, args.verbose, &device, dtype, ); pipeline.run(&args.prompt, args.sample_len)?; Ok(()) }
candle/candle-examples/examples/codegeex4-9b/main.rs/0
{ "file_path": "candle/candle-examples/examples/codegeex4-9b/main.rs", "repo_id": "candle", "token_count": 3865 }
32
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use std::fmt::Display; use std::path::PathBuf; use anyhow::bail; use anyhow::{Error as E, Result}; use candle::{Device, Tensor}; use candle_nn::ops::softmax; use candle_nn::VarBuilder; use candle_transformers::models::debertav2::{Config as DebertaV2Config, DebertaV2NERModel}; use candle_transformers::models::debertav2::{DebertaV2SeqClassificationModel, Id2Label}; use candle_transformers::models::debertav2::{NERItem, TextClassificationItem}; use clap::{ArgGroup, Parser, ValueEnum}; use hf_hub::{api::sync::Api, Repo, RepoType}; use tokenizers::{Encoding, PaddingParams, Tokenizer}; enum TaskType { Ner(Box<DebertaV2NERModel>), TextClassification(Box<DebertaV2SeqClassificationModel>), } #[derive(Parser, Debug, Clone, ValueEnum)] enum ArgsTask { /// Named Entity Recognition Ner, /// Text Classification TextClassification, } impl Display for ArgsTask { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { ArgsTask::Ner => write!(f, "ner"), ArgsTask::TextClassification => write!(f, "text-classification"), } } } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] #[command(group(ArgGroup::new("model") .required(true) .args(&["model_id", "model_path"])))] struct Args { /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, /// The model id to use from HuggingFace #[arg(long, requires_if("model_id", "revision"))] model_id: Option<String>, /// Revision of the model to use (default: "main") #[arg(long, default_value = "main")] revision: String, /// Specify a sentence to inference. Specify multiple times to inference multiple sentences. #[arg(long = "sentence", name="sentences", num_args = 1..)] sentences: Vec<String>, /// Use the pytorch weights rather than the by-default safetensors #[arg(long)] use_pth: bool, /// Perform a very basic benchmark on inferencing, using N number of iterations #[arg(long)] benchmark_iters: Option<usize>, /// Which task to run #[arg(long, default_value_t = ArgsTask::Ner)] task: ArgsTask, /// Use model from a specific directory instead of HuggingFace local cache. /// Using this ignores model_id and revision args. #[arg(long)] model_path: Option<PathBuf>, /// Pass in an Id2Label if the model config does not provide it, in JSON format. Example: --id2label='{"0": "True", "1": "False"}' #[arg(long)] id2label: Option<String>, } impl Args { fn build_model_and_tokenizer( &self, ) -> Result<(TaskType, DebertaV2Config, Tokenizer, Id2Label)> { let device = candle_examples::device(self.cpu)?; // Get files from either the HuggingFace API, or from a specified local directory. let (config_filename, tokenizer_filename, weights_filename) = { match &self.model_path { Some(base_path) => { if !base_path.is_dir() { bail!("Model path {} is not a directory.", base_path.display()) } let config = base_path.join("config.json"); let tokenizer = base_path.join("tokenizer.json"); let weights = if self.use_pth { base_path.join("pytorch_model.bin") } else { base_path.join("model.safetensors") }; (config, tokenizer, weights) } None => { let repo = Repo::with_revision( self.model_id.as_ref().unwrap().clone(), RepoType::Model, self.revision.clone(), ); let api = Api::new()?; let api = api.repo(repo); let config = api.get("config.json")?; let tokenizer = api.get("tokenizer.json")?; let weights = if self.use_pth { api.get("pytorch_model.bin")? } else { api.get("model.safetensors")? }; (config, tokenizer, weights) } } }; let config = std::fs::read_to_string(config_filename)?; let config: DebertaV2Config = serde_json::from_str(&config)?; // Command-line id2label takes precedence. Otherwise, use model config's id2label. // If neither is specified, then we can't proceed. let id2label = if let Some(id2labelstr) = &self.id2label { serde_json::from_str(id2labelstr.as_str())? } else if let Some(id2label) = &config.id2label { id2label.clone() } else { bail!("Id2Label not found in the model configuration nor specified as a parameter") }; let mut tokenizer = Tokenizer::from_file(tokenizer_filename) .map_err(|e| candle::Error::Msg(format!("Tokenizer error: {e}")))?; tokenizer.with_padding(Some(PaddingParams::default())); let vb = if self.use_pth { VarBuilder::from_pth( &weights_filename, candle_transformers::models::debertav2::DTYPE, &device, )? } else { unsafe { VarBuilder::from_mmaped_safetensors( &[weights_filename], candle_transformers::models::debertav2::DTYPE, &device, )? } }; let vb = vb.set_prefix("deberta"); match self.task { ArgsTask::Ner => Ok(( TaskType::Ner(DebertaV2NERModel::load(vb, &config, Some(id2label.clone()))?.into()), config, tokenizer, id2label, )), ArgsTask::TextClassification => Ok(( TaskType::TextClassification( DebertaV2SeqClassificationModel::load(vb, &config, Some(id2label.clone()))? .into(), ), config, tokenizer, id2label, )), } } } fn get_device(model_type: &TaskType) -> &Device { match model_type { TaskType::Ner(ner_model) => &ner_model.device, TaskType::TextClassification(classification_model) => &classification_model.device, } } struct ModelInput { encoding: Vec<Encoding>, input_ids: Tensor, attention_mask: Tensor, token_type_ids: Tensor, } fn main() -> Result<()> { use tracing_chrome::ChromeLayerBuilder; use tracing_subscriber::prelude::*; let args = Args::parse(); let _guard = if args.tracing { let (chrome_layer, guard) = ChromeLayerBuilder::new().build(); tracing_subscriber::registry().with(chrome_layer).init(); Some(guard) } else { None }; let model_load_time = std::time::Instant::now(); let (task_type, _model_config, tokenizer, id2label) = args.build_model_and_tokenizer()?; println!( "Loaded model and tokenizers in {:?}", model_load_time.elapsed() ); let device = get_device(&task_type); let tokenize_time = std::time::Instant::now(); let model_input: ModelInput = { let tokenizer_encodings = tokenizer .encode_batch(args.sentences, true) .map_err(E::msg)?; let mut encoding_stack: Vec<Tensor> = Vec::default(); let mut attention_mask_stack: Vec<Tensor> = Vec::default(); let mut token_type_id_stack: Vec<Tensor> = Vec::default(); for encoding in &tokenizer_encodings { encoding_stack.push(Tensor::new(encoding.get_ids(), device)?); attention_mask_stack.push(Tensor::new(encoding.get_attention_mask(), device)?); token_type_id_stack.push(Tensor::new(encoding.get_type_ids(), device)?); } ModelInput { encoding: tokenizer_encodings, input_ids: Tensor::stack(&encoding_stack[..], 0)?, attention_mask: Tensor::stack(&attention_mask_stack[..], 0)?, token_type_ids: Tensor::stack(&token_type_id_stack[..], 0)?, } }; println!( "Tokenized and loaded inputs in {:?}", tokenize_time.elapsed() ); match task_type { TaskType::Ner(ner_model) => { if let Some(num_iters) = args.benchmark_iters { create_benchmark(num_iters, model_input)( |input_ids, token_type_ids, attention_mask| { ner_model.forward(input_ids, Some(token_type_ids), Some(attention_mask))?; Ok(()) }, )?; std::process::exit(0); } let inference_time = std::time::Instant::now(); let logits = ner_model.forward( &model_input.input_ids, Some(model_input.token_type_ids), Some(model_input.attention_mask), )?; println!("Inferenced inputs in {:?}", inference_time.elapsed()); let max_scores_vec = softmax(&logits, 2)?.max(2)?.to_vec2::<f32>()?; let max_indices_vec: Vec<Vec<u32>> = logits.argmax(2)?.to_vec2()?; let input_ids = model_input.input_ids.to_vec2::<u32>()?; let mut results: Vec<Vec<NERItem>> = Default::default(); for (input_row_idx, input_id_row) in input_ids.iter().enumerate() { let mut current_row_result: Vec<NERItem> = Default::default(); let current_row_encoding = model_input.encoding.get(input_row_idx).unwrap(); let current_row_tokens = current_row_encoding.get_tokens(); let current_row_max_scores = max_scores_vec.get(input_row_idx).unwrap(); for (input_id_idx, _input_id) in input_id_row.iter().enumerate() { // Do not include special characters in output if current_row_encoding.get_special_tokens_mask()[input_id_idx] == 1 { continue; } let max_label_idx = max_indices_vec .get(input_row_idx) .unwrap() .get(input_id_idx) .unwrap(); let label = id2label.get(max_label_idx).unwrap().clone(); // Do not include those labeled as "O" ("Other") if label == "O" { continue; } current_row_result.push(NERItem { entity: label, word: current_row_tokens[input_id_idx].clone(), score: current_row_max_scores[input_id_idx], start: current_row_encoding.get_offsets()[input_id_idx].0, end: current_row_encoding.get_offsets()[input_id_idx].1, index: input_id_idx, }); } results.push(current_row_result); } println!("\n{results:?}"); } TaskType::TextClassification(classification_model) => { let inference_time = std::time::Instant::now(); let logits = classification_model.forward( &model_input.input_ids, Some(model_input.token_type_ids), Some(model_input.attention_mask), )?; println!("Inferenced inputs in {:?}", inference_time.elapsed()); let predictions = logits.argmax(1)?.to_vec1::<u32>()?; let scores = softmax(&logits, 1)?.max(1)?.to_vec1::<f32>()?; let mut results = Vec::<TextClassificationItem>::default(); for (idx, prediction) in predictions.iter().enumerate() { results.push(TextClassificationItem { label: id2label[prediction].clone(), score: scores[idx], }); } println!("\n{results:?}"); } } Ok(()) } fn create_benchmark<F>( num_iters: usize, model_input: ModelInput, ) -> impl Fn(F) -> Result<(), candle::Error> where F: Fn(&Tensor, Tensor, Tensor) -> Result<(), candle::Error>, { move |code: F| -> Result<(), candle::Error> { println!("Running {num_iters} iterations..."); let mut durations = Vec::with_capacity(num_iters); for _ in 0..num_iters { let token_type_ids = model_input.token_type_ids.clone(); let attention_mask = model_input.attention_mask.clone(); let start = std::time::Instant::now(); code(&model_input.input_ids, token_type_ids, attention_mask)?; let duration = start.elapsed(); durations.push(duration.as_nanos()); } let min_time = *durations.iter().min().unwrap(); let max_time = *durations.iter().max().unwrap(); let avg_time = durations.iter().sum::<u128>() as f64 / num_iters as f64; println!("Min time: {:.3} ms", min_time as f64 / 1_000_000.0); println!("Avg time: {:.3} ms", avg_time / 1_000_000.0); println!("Max time: {:.3} ms", max_time as f64 / 1_000_000.0); Ok(()) } }
candle/candle-examples/examples/debertav2/main.rs/0
{ "file_path": "candle/candle-examples/examples/debertav2/main.rs", "repo_id": "candle", "token_count": 6735 }
33
# candle-endocec [EnCodec](https://huggingface.co/facebook/encodec_24khz) is a high-quality audio compression model using an encoder/decoder architecture with residual vector quantization. ## Running one example ```bash cargo run --example encodec --features encodec --release -- code-to-audio \ candle-examples/examples/encodec/jfk-codes.safetensors \ jfk.wav ``` This decodes the EnCodec tokens stored in `jfk-codes.safetensors` and generates an output wav file containing the audio data. Instead of `code-to-audio` one can use: - `audio-to-audio in.mp3 out.wav`: encodes the input audio file then decodes it to a wav file. - `audio-to-code in.mp3 out.safetensors`: generates a safetensors file containing EnCodec tokens for the input audio file. If the audio output file name is set to `-`, the audio content directly gets played on default audio output device. If the audio input file is set to `-`, the audio gets recorded from the default audio input.
candle/candle-examples/examples/encodec/README.md/0
{ "file_path": "candle/candle-examples/examples/encodec/README.md", "repo_id": "candle", "token_count": 305 }
34
## GLM4 GLM-4-9B-0414 is a new architecture in the GLM-4 series developed by Zhipu AI. This model is not compatible with previous versions of GLM-4, such as THUDM/glm-4-9b, due to differences in model architecture and internal implementation. Users must explicitly specify the correct model type when loading it, as using the wrong configuration may lead to initialization errors or runtime failures. ### GLM4-0414 Arch: - [GLM4-0414 Collection](https://huggingface.co/collections/THUDM/glm-4-0414-67f3cbcb34dd9d252707cb2e) - [GLM-4-9B-0414 Weight](https://huggingface.co/THUDM/GLM-4-9B-0414) ### Old GLM4 Arch: - [GitHub](https://github.com/THUDM/GLM4) - [GLM-4-9B Weight](https://huggingface.co/THUDM/glm-4-9b) ### Running with CUDA Use `--which` to distinguish two archs ```bash cargo run --example glm4 --release --features cuda -- --which "glm4-new" --model-id THUDM/GLM-4-9B-0414 --prompt "How are you today?" cargo run --example glm4 --release --features cuda -- --which "glm4-old" --model-id THUDM/glm-4-9b --prompt "How are you today?" ``` ### Running with local file (CUDA) ```bash cargo run --example glm4 --release --features cuda -- --which "glm4-new" --weight-path /path/GLM-4-9B-0414 --prompt "How are you today?" cargo run --example glm4 --release --features cuda -- --which "glm4-old" --weight-path /path/glm-4-9b --prompt "How are you today?" ``` ### Running with local file (Metal) ```bash cargo run --example glm4 --release --features metal -- --which "glm4-new" --weight-path /path/GLM-4-9B-0414 --prompt "How are you today?" cargo run --example glm4 --release --features metal -- --which "glm4-old" --weight-path /path/glm-4-9b --prompt "How are you today?" ``` ### Running with CPU ```bash cargo run --example glm4 --release -- --cpu --which "glm4-new" --model-id THUDM/GLM-4-9B-0414 --prompt "How are you today?" ``` ### Output Example (GLM-4-9B-0414) ``` avx: true, neon: false, simd128: false, f16c: true temp: 0.80 repeat-penalty: 1.20 repeat-last-n: 64 retrieved the files in 158.728989ms loaded the model in 3.714556129s starting the inference loop How are you today? I'm just a computer program, so I don't have feelings or emotions. But thank you for asking! How can I assist you today? 31 tokens generated (28.77 token/s) ```
candle/candle-examples/examples/glm4/README.md/0
{ "file_path": "candle/candle-examples/examples/glm4/README.md", "repo_id": "candle", "token_count": 829 }
35
// An implementation of LLaMA https://github.com/facebookresearch/llama // // This is based on nanoGPT in a similar way to: // https://github.com/Lightning-AI/lit-llama/blob/main/lit_llama/model.py // // The tokenizer config can be retrieved from: // https://huggingface.co/hf-internal-testing/llama-tokenizer/raw/main/tokenizer.json #[cfg(feature = "mkl")] extern crate intel_mkl_src; use anyhow::{bail, Error as E, Result}; use clap::{Parser, ValueEnum}; use candle::{DType, Device, Tensor}; use candle_transformers::generation::LogitsProcessor; use candle_transformers::models::llama::LlamaEosToks; use cudarc::driver::safe::CudaDevice; use cudarc::nccl::safe::{Comm, Id}; use hf_hub::{api::sync::Api, Repo, RepoType}; use std::io::Write; use std::rc::Rc; mod model; use model::{Config, Llama}; const MAX_SEQ_LEN: usize = 4096; const DEFAULT_PROMPT: &str = "My favorite theorem is "; #[derive(Clone, Debug, Copy, PartialEq, Eq, ValueEnum)] enum Which { V2_7b, V2_70b, V3_8b, V3_70b, } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { #[arg(long)] num_shards: usize, #[arg(long)] rank: Option<usize>, /// The temperature used to generate samples. #[arg(long, default_value_t = 0.8)] temperature: f64, /// Nucleus sampling probability cutoff. #[arg(long)] top_p: Option<f64>, /// The seed to use when generating random samples. #[arg(long, default_value_t = 299792458)] seed: u64, /// The length of the sample to generate (in tokens). #[arg(long, default_value_t = 100)] sample_len: usize, /// Disable the key-value cache. #[arg(long)] no_kv_cache: bool, /// The initial prompt. #[arg(long)] prompt: Option<String>, #[arg(long)] model_id: Option<String>, #[arg(long)] revision: Option<String>, #[arg(long)] dtype: Option<String>, #[arg(long, default_value = "v3-8b")] which: Which, #[arg(long, default_value = "nccl_id.txt")] comm_file: String, } fn main() -> Result<()> { use tokenizers::Tokenizer; let args = Args::parse(); let dtype = match args.dtype.as_deref() { Some("f16") => DType::F16, Some("bf16") => DType::BF16, Some("f32") => DType::F32, Some(dtype) => bail!("Unsupported dtype {dtype}"), None => match args.which { Which::V2_7b | Which::V2_70b => DType::F16, Which::V3_8b | Which::V3_70b => DType::BF16, }, }; let comm_file = std::path::PathBuf::from(&args.comm_file); if comm_file.exists() { bail!("comm file {comm_file:?} already exists, please remove it first") } let api = Api::new()?; let model_id = match args.model_id { Some(model) => model, None => match args.which { Which::V2_7b => "meta-llama/Llama-2-7b-hf".to_string(), Which::V2_70b => "meta-llama/Llama-2-70b-hf".to_string(), Which::V3_8b => "meta-llama/Meta-Llama-3-8B".to_string(), Which::V3_70b => "meta-llama/Meta-Llama-3-70B".to_string(), }, }; println!("loading the model weights from {model_id}"); let revision = args.revision.unwrap_or("main".to_string()); let api = api.repo(Repo::with_revision(model_id, RepoType::Model, revision)); let config_filename = api.get("config.json")?; let config: Config = serde_json::from_slice(&std::fs::read(config_filename)?)?; let tokenizer_filename = api.get("tokenizer.json")?; let filenames = candle_examples::hub_load_safetensors(&api, "model.safetensors.index.json")?; let rank = match args.rank { None => { println!("creating {} child processes", args.num_shards); let children: Vec<_> = (0..args.num_shards) .map(|rank| { let mut args: std::collections::VecDeque<_> = std::env::args().collect(); args.push_back("--rank".to_string()); args.push_back(format!("{rank}")); let name = args.pop_front().unwrap(); std::process::Command::new(name).args(args).spawn().unwrap() }) .collect(); for mut child in children { child.wait()?; } return Ok(()); } Some(rank) => rank, }; let num_shards = args.num_shards; // Primitive IPC let id = if rank == 0 { let id = Id::new().unwrap(); let tmp_file = comm_file.with_extension(".comm.tgz"); std::fs::File::create(&tmp_file)? .write_all(&id.internal().iter().map(|&i| i as u8).collect::<Vec<_>>())?; std::fs::rename(&tmp_file, &comm_file)?; id } else { while !comm_file.exists() { std::thread::sleep(std::time::Duration::from_secs(1)); } let data = std::fs::read(&comm_file)?; let internal: [i8; 128] = data .into_iter() .map(|i| i as i8) .collect::<Vec<_>>() .try_into() .unwrap(); let id: Id = Id::uninit(internal); id }; let device = CudaDevice::new(rank)?; let comm = match Comm::from_rank(device, rank, num_shards, id) { Ok(comm) => Rc::new(comm), Err(err) => anyhow::bail!("nccl error {:?}", err.0), }; if rank == 0 { std::fs::remove_file(comm_file)?; } println!("Rank {rank:?} spawned"); let device = Device::new_cuda(rank)?; let cache = model::Cache::new(dtype, &config, &device)?; println!("building the model"); let vb = unsafe { candle_nn::var_builder::ShardedSafeTensors::var_builder(&filenames, dtype, &device)? }; let llama = Llama::load(vb, &cache, &config, comm)?; let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?; let prompt = args.prompt.as_ref().map_or(DEFAULT_PROMPT, |p| p.as_str()); let mut tokens = tokenizer .encode(prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); let mut tokenizer = candle_examples::token_output_stream::TokenOutputStream::new(tokenizer); println!("starting the inference loop"); let temperature = if args.temperature <= 0. { None } else { Some(args.temperature) }; let mut logits_processor = LogitsProcessor::new(args.seed, temperature, args.top_p); let mut new_tokens = vec![]; let mut start_gen = std::time::Instant::now(); let mut index_pos = 0; for index in 0..args.sample_len { // Only start timing at the second token as processing the first token waits for all the // weights to be loaded in an async way. if index == 1 { start_gen = std::time::Instant::now() }; let context_size = if index > 0 { 1 } else { tokens.len() }; let ctxt = &tokens[tokens.len().saturating_sub(context_size)..]; let input = Tensor::new(ctxt, &device)?.unsqueeze(0)?; let logits = llama.forward(&input, index_pos)?; let logits = logits.squeeze(0)?; index_pos += ctxt.len(); let next_token = logits_processor.sample(&logits)?; tokens.push(next_token); new_tokens.push(next_token); match config.eos_token_id { Some(LlamaEosToks::Single(eos_tok_id)) if next_token == eos_tok_id => { break; } Some(LlamaEosToks::Multiple(ref eos_ids)) if eos_ids.contains(&next_token) => { break; } _ => (), } if rank == 0 { if let Some(t) = tokenizer.next_token(next_token)? { print!("{t}"); std::io::stdout().flush()?; } } } println!(); if rank == 0 { let dt = start_gen.elapsed(); println!( "\n\n{} tokens generated ({} token/s)\n", args.sample_len, (args.sample_len - 1) as f64 / dt.as_secs_f64(), ); } Ok(()) }
candle/candle-examples/examples/llama_multiprocess/main.rs/0
{ "file_path": "candle/candle-examples/examples/llama_multiprocess/main.rs", "repo_id": "candle", "token_count": 3774 }
36