Auto Classes
In many cases, the architecture you want to use can be guessed from the name or the path of the pretrained model you
are supplying to the from_pretrained()
method. AutoClasses are here to do this job for you so that you
automatically retrieve the relevant model given the name/path to the pretrained weights/config/vocabulary.
Instantiating one of AutoConfig, AutoModel, and AutoTokenizer will directly create a class of the relevant architecture. For instance
model = AutoModel.from_pretrained("google-bert/bert-base-cased")
will create a model that is an instance of BertModel.
There is one class of AutoModel
for each task, and for each backend (PyTorch, TensorFlow, or Flax).
Extending the Auto Classes
Each of the auto classes has a method to be extended with your custom classes. For instance, if you have defined a
custom class of model NewModel
, make sure you have a NewModelConfig
then you can add those to the auto
classes like this:
from transformers import AutoConfig, AutoModel
AutoConfig.register("new-model", NewModelConfig)
AutoModel.register(NewModelConfig, NewModel)
You will then be able to use the auto classes like you would usually do!
If your NewModelConfig
is a subclass of PretrainedConfig, make sure its
model_type
attribute is set to the same key you use when registering the config (here "new-model"
).
Likewise, if your NewModel
is a subclass of PreTrainedModel, make sure its
config_class
attribute is set to the same class you use when registering the model (here
NewModelConfig
).
AutoConfig
This is a generic configuration class that will be instantiated as one of the configuration classes of the library when created with the from_pretrained() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_pretrained
< source >( pretrained_model_name_or_path **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model configuration hosted inside a model repo on huggingface.co.
- A path to a directory containing a configuration file saved using the
save_pretrained() method, or the save_pretrained() method,
e.g.,
./my_model_directory/
. - A path or url to a saved configuration JSON file, e.g.,
./my_model_directory/configuration.json
.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download the model weights and configuration files and override the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - return_unused_kwargs (
bool
, optional, defaults toFalse
) — IfFalse
, then this function returns just the final configuration object.If
True
, then this functions returns aTuple(config, unused_kwargs)
where unused_kwargs is a dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the part ofkwargs
which has not been used to updateconfig
and is otherwise ignored. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - kwargs(additional keyword arguments, optional) —
The values in kwargs of any keys which are configuration attributes will be used to override the loaded
values. Behavior concerning key/value pairs whose keys are not configuration attributes is controlled
by the
return_unused_kwargs
keyword parameter.
Instantiate one of the configuration classes of the library from a pretrained model configuration.
The configuration class to instantiate is selected based on the model_type
property of the config object that
is loaded, or when itβs missing, by falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β AlbertConfig (ALBERT model)
- align β AlignConfig (ALIGN model)
- altclip β AltCLIPConfig (AltCLIP model)
- aria β AriaConfig (Aria model)
- aria_text β AriaTextConfig (AriaText model)
- audio-spectrogram-transformer β ASTConfig (Audio Spectrogram Transformer model)
- autoformer β AutoformerConfig (Autoformer model)
- bamba β BambaConfig (Bamba model)
- bark β BarkConfig (Bark model)
- bart β BartConfig (BART model)
- beit β BeitConfig (BEiT model)
- bert β BertConfig (BERT model)
- bert-generation β BertGenerationConfig (Bert Generation model)
- big_bird β BigBirdConfig (BigBird model)
- bigbird_pegasus β BigBirdPegasusConfig (BigBird-Pegasus model)
- biogpt β BioGptConfig (BioGpt model)
- bit β BitConfig (BiT model)
- blenderbot β BlenderbotConfig (Blenderbot model)
- blenderbot-small β BlenderbotSmallConfig (BlenderbotSmall model)
- blip β BlipConfig (BLIP model)
- blip-2 β Blip2Config (BLIP-2 model)
- bloom β BloomConfig (BLOOM model)
- bridgetower β BridgeTowerConfig (BridgeTower model)
- bros β BrosConfig (BROS model)
- camembert β CamembertConfig (CamemBERT model)
- canine β CanineConfig (CANINE model)
- chameleon β ChameleonConfig (Chameleon model)
- chinese_clip β ChineseCLIPConfig (Chinese-CLIP model)
- chinese_clip_vision_model β ChineseCLIPVisionConfig (ChineseCLIPVisionModel model)
- clap β ClapConfig (CLAP model)
- clip β CLIPConfig (CLIP model)
- clip_text_model β CLIPTextConfig (CLIPTextModel model)
- clip_vision_model β CLIPVisionConfig (CLIPVisionModel model)
- clipseg β CLIPSegConfig (CLIPSeg model)
- clvp β ClvpConfig (CLVP model)
- code_llama β LlamaConfig (CodeLlama model)
- codegen β CodeGenConfig (CodeGen model)
- cohere β CohereConfig (Cohere model)
- cohere2 β Cohere2Config (Cohere2 model)
- colpali β ColPaliConfig (ColPali model)
- conditional_detr β ConditionalDetrConfig (Conditional DETR model)
- convbert β ConvBertConfig (ConvBERT model)
- convnext β ConvNextConfig (ConvNeXT model)
- convnextv2 β ConvNextV2Config (ConvNeXTV2 model)
- cpmant β CpmAntConfig (CPM-Ant model)
- ctrl β CTRLConfig (CTRL model)
- cvt β CvtConfig (CvT model)
- dac β DacConfig (DAC model)
- data2vec-audio β Data2VecAudioConfig (Data2VecAudio model)
- data2vec-text β Data2VecTextConfig (Data2VecText model)
- data2vec-vision β Data2VecVisionConfig (Data2VecVision model)
- dbrx β DbrxConfig (DBRX model)
- deberta β DebertaConfig (DeBERTa model)
- deberta-v2 β DebertaV2Config (DeBERTa-v2 model)
- decision_transformer β DecisionTransformerConfig (Decision Transformer model)
- deformable_detr β DeformableDetrConfig (Deformable DETR model)
- deit β DeiTConfig (DeiT model)
- depth_anything β DepthAnythingConfig (Depth Anything model)
- deta β DetaConfig (DETA model)
- detr β DetrConfig (DETR model)
- dinat β DinatConfig (DiNAT model)
- dinov2 β Dinov2Config (DINOv2 model)
- distilbert β DistilBertConfig (DistilBERT model)
- donut-swin β DonutSwinConfig (DonutSwin model)
- dpr β DPRConfig (DPR model)
- dpt β DPTConfig (DPT model)
- efficientformer β EfficientFormerConfig (EfficientFormer model)
- efficientnet β EfficientNetConfig (EfficientNet model)
- electra β ElectraConfig (ELECTRA model)
- encodec β EncodecConfig (EnCodec model)
- encoder-decoder β EncoderDecoderConfig (Encoder decoder model)
- ernie β ErnieConfig (ERNIE model)
- ernie_m β ErnieMConfig (ErnieM model)
- esm β EsmConfig (ESM model)
- falcon β FalconConfig (Falcon model)
- falcon_mamba β FalconMambaConfig (FalconMamba model)
- fastspeech2_conformer β FastSpeech2ConformerConfig (FastSpeech2Conformer model)
- flaubert β FlaubertConfig (FlauBERT model)
- flava β FlavaConfig (FLAVA model)
- fnet β FNetConfig (FNet model)
- focalnet β FocalNetConfig (FocalNet model)
- fsmt β FSMTConfig (FairSeq Machine-Translation model)
- funnel β FunnelConfig (Funnel Transformer model)
- fuyu β FuyuConfig (Fuyu model)
- gemma β GemmaConfig (Gemma model)
- gemma2 β Gemma2Config (Gemma2 model)
- git β GitConfig (GIT model)
- glm β GlmConfig (GLM model)
- glpn β GLPNConfig (GLPN model)
- gpt-sw3 β GPT2Config (GPT-Sw3 model)
- gpt2 β GPT2Config (OpenAI GPT-2 model)
- gpt_bigcode β GPTBigCodeConfig (GPTBigCode model)
- gpt_neo β GPTNeoConfig (GPT Neo model)
- gpt_neox β GPTNeoXConfig (GPT NeoX model)
- gpt_neox_japanese β GPTNeoXJapaneseConfig (GPT NeoX Japanese model)
- gptj β GPTJConfig (GPT-J model)
- gptsan-japanese β GPTSanJapaneseConfig (GPTSAN-japanese model)
- granite β GraniteConfig (Granite model)
- granitemoe β GraniteMoeConfig (GraniteMoeMoe model)
- graphormer β GraphormerConfig (Graphormer model)
- grounding-dino β GroundingDinoConfig (Grounding DINO model)
- groupvit β GroupViTConfig (GroupViT model)
- hiera β HieraConfig (Hiera model)
- hubert β HubertConfig (Hubert model)
- ibert β IBertConfig (I-BERT model)
- idefics β IdeficsConfig (IDEFICS model)
- idefics2 β Idefics2Config (Idefics2 model)
- idefics3 β Idefics3Config (Idefics3 model)
- idefics3_vision β Idefics3VisionConfig (Idefics3VisionTransformer model)
- ijepa β IJepaConfig (I-JEPA model)
- imagegpt β ImageGPTConfig (ImageGPT model)
- informer β InformerConfig (Informer model)
- instructblip β InstructBlipConfig (InstructBLIP model)
- instructblipvideo β InstructBlipVideoConfig (InstructBlipVideo model)
- jamba β JambaConfig (Jamba model)
- jetmoe β JetMoeConfig (JetMoe model)
- jukebox β JukeboxConfig (Jukebox model)
- kosmos-2 β Kosmos2Config (KOSMOS-2 model)
- layoutlm β LayoutLMConfig (LayoutLM model)
- layoutlmv2 β LayoutLMv2Config (LayoutLMv2 model)
- layoutlmv3 β LayoutLMv3Config (LayoutLMv3 model)
- led β LEDConfig (LED model)
- levit β LevitConfig (LeViT model)
- lilt β LiltConfig (LiLT model)
- llama β LlamaConfig (LLaMA model)
- llava β LlavaConfig (LLaVa model)
- llava_next β LlavaNextConfig (LLaVA-NeXT model)
- llava_next_video β LlavaNextVideoConfig (LLaVa-NeXT-Video model)
- llava_onevision β LlavaOnevisionConfig (LLaVA-Onevision model)
- longformer β LongformerConfig (Longformer model)
- longt5 β LongT5Config (LongT5 model)
- luke β LukeConfig (LUKE model)
- lxmert β LxmertConfig (LXMERT model)
- m2m_100 β M2M100Config (M2M100 model)
- mamba β MambaConfig (Mamba model)
- mamba2 β Mamba2Config (mamba2 model)
- marian β MarianConfig (Marian model)
- markuplm β MarkupLMConfig (MarkupLM model)
- mask2former β Mask2FormerConfig (Mask2Former model)
- maskformer β MaskFormerConfig (MaskFormer model)
- maskformer-swin β
MaskFormerSwinConfig
(MaskFormerSwin model) - mbart β MBartConfig (mBART model)
- mctct β MCTCTConfig (M-CTC-T model)
- mega β MegaConfig (MEGA model)
- megatron-bert β MegatronBertConfig (Megatron-BERT model)
- mgp-str β MgpstrConfig (MGP-STR model)
- mimi β MimiConfig (Mimi model)
- mistral β MistralConfig (Mistral model)
- mixtral β MixtralConfig (Mixtral model)
- mllama β MllamaConfig (Mllama model)
- mobilebert β MobileBertConfig (MobileBERT model)
- mobilenet_v1 β MobileNetV1Config (MobileNetV1 model)
- mobilenet_v2 β MobileNetV2Config (MobileNetV2 model)
- mobilevit β MobileViTConfig (MobileViT model)
- mobilevitv2 β MobileViTV2Config (MobileViTV2 model)
- modernbert β ModernBertConfig (ModernBERT model)
- moshi β MoshiConfig (Moshi model)
- mpnet β MPNetConfig (MPNet model)
- mpt β MptConfig (MPT model)
- mra β MraConfig (MRA model)
- mt5 β MT5Config (MT5 model)
- musicgen β MusicgenConfig (MusicGen model)
- musicgen_melody β MusicgenMelodyConfig (MusicGen Melody model)
- mvp β MvpConfig (MVP model)
- nat β NatConfig (NAT model)
- nemotron β NemotronConfig (Nemotron model)
- nezha β NezhaConfig (Nezha model)
- nllb-moe β NllbMoeConfig (NLLB-MOE model)
- nougat β VisionEncoderDecoderConfig (Nougat model)
- nystromformer β NystromformerConfig (NystrΓΆmformer model)
- olmo β OlmoConfig (OLMo model)
- olmo2 β Olmo2Config (OLMo2 model)
- olmoe β OlmoeConfig (OLMoE model)
- omdet-turbo β OmDetTurboConfig (OmDet-Turbo model)
- oneformer β OneFormerConfig (OneFormer model)
- open-llama β OpenLlamaConfig (OpenLlama model)
- openai-gpt β OpenAIGPTConfig (OpenAI GPT model)
- opt β OPTConfig (OPT model)
- owlv2 β Owlv2Config (OWLv2 model)
- owlvit β OwlViTConfig (OWL-ViT model)
- paligemma β PaliGemmaConfig (PaliGemma model)
- patchtsmixer β PatchTSMixerConfig (PatchTSMixer model)
- patchtst β PatchTSTConfig (PatchTST model)
- pegasus β PegasusConfig (Pegasus model)
- pegasus_x β PegasusXConfig (PEGASUS-X model)
- perceiver β PerceiverConfig (Perceiver model)
- persimmon β PersimmonConfig (Persimmon model)
- phi β PhiConfig (Phi model)
- phi3 β Phi3Config (Phi3 model)
- phimoe β PhimoeConfig (Phimoe model)
- pix2struct β Pix2StructConfig (Pix2Struct model)
- pixtral β PixtralVisionConfig (Pixtral model)
- plbart β PLBartConfig (PLBart model)
- poolformer β PoolFormerConfig (PoolFormer model)
- pop2piano β Pop2PianoConfig (Pop2Piano model)
- prophetnet β ProphetNetConfig (ProphetNet model)
- pvt β PvtConfig (PVT model)
- pvt_v2 β PvtV2Config (PVTv2 model)
- qdqbert β QDQBertConfig (QDQBert model)
- qwen2 β Qwen2Config (Qwen2 model)
- qwen2_audio β Qwen2AudioConfig (Qwen2Audio model)
- qwen2_audio_encoder β Qwen2AudioEncoderConfig (Qwen2AudioEncoder model)
- qwen2_moe β Qwen2MoeConfig (Qwen2MoE model)
- qwen2_vl β Qwen2VLConfig (Qwen2VL model)
- rag β RagConfig (RAG model)
- realm β RealmConfig (REALM model)
- recurrent_gemma β RecurrentGemmaConfig (RecurrentGemma model)
- reformer β ReformerConfig (Reformer model)
- regnet β RegNetConfig (RegNet model)
- rembert β RemBertConfig (RemBERT model)
- resnet β ResNetConfig (ResNet model)
- retribert β RetriBertConfig (RetriBERT model)
- roberta β RobertaConfig (RoBERTa model)
- roberta-prelayernorm β RobertaPreLayerNormConfig (RoBERTa-PreLayerNorm model)
- roc_bert β RoCBertConfig (RoCBert model)
- roformer β RoFormerConfig (RoFormer model)
- rt_detr β RTDetrConfig (RT-DETR model)
- rt_detr_resnet β RTDetrResNetConfig (RT-DETR-ResNet model)
- rwkv β RwkvConfig (RWKV model)
- sam β SamConfig (SAM model)
- seamless_m4t β SeamlessM4TConfig (SeamlessM4T model)
- seamless_m4t_v2 β SeamlessM4Tv2Config (SeamlessM4Tv2 model)
- segformer β SegformerConfig (SegFormer model)
- seggpt β SegGptConfig (SegGPT model)
- sew β SEWConfig (SEW model)
- sew-d β SEWDConfig (SEW-D model)
- siglip β SiglipConfig (SigLIP model)
- siglip_vision_model β SiglipVisionConfig (SiglipVisionModel model)
- speech-encoder-decoder β SpeechEncoderDecoderConfig (Speech Encoder decoder model)
- speech_to_text β Speech2TextConfig (Speech2Text model)
- speech_to_text_2 β Speech2Text2Config (Speech2Text2 model)
- speecht5 β SpeechT5Config (SpeechT5 model)
- splinter β SplinterConfig (Splinter model)
- squeezebert β SqueezeBertConfig (SqueezeBERT model)
- stablelm β StableLmConfig (StableLm model)
- starcoder2 β Starcoder2Config (Starcoder2 model)
- superpoint β SuperPointConfig (SuperPoint model)
- swiftformer β SwiftFormerConfig (SwiftFormer model)
- swin β SwinConfig (Swin Transformer model)
- swin2sr β Swin2SRConfig (Swin2SR model)
- swinv2 β Swinv2Config (Swin Transformer V2 model)
- switch_transformers β SwitchTransformersConfig (SwitchTransformers model)
- t5 β T5Config (T5 model)
- table-transformer β TableTransformerConfig (Table Transformer model)
- tapas β TapasConfig (TAPAS model)
- time_series_transformer β TimeSeriesTransformerConfig (Time Series Transformer model)
- timesformer β TimesformerConfig (TimeSformer model)
- timm_backbone β TimmBackboneConfig (TimmBackbone model)
- timm_wrapper β TimmWrapperConfig (TimmWrapperModel model)
- trajectory_transformer β TrajectoryTransformerConfig (Trajectory Transformer model)
- transfo-xl β TransfoXLConfig (Transformer-XL model)
- trocr β TrOCRConfig (TrOCR model)
- tvlt β TvltConfig (TVLT model)
- tvp β TvpConfig (TVP model)
- udop β UdopConfig (UDOP model)
- umt5 β UMT5Config (UMT5 model)
- unispeech β UniSpeechConfig (UniSpeech model)
- unispeech-sat β UniSpeechSatConfig (UniSpeechSat model)
- univnet β UnivNetConfig (UnivNet model)
- upernet β UperNetConfig (UPerNet model)
- van β VanConfig (VAN model)
- video_llava β VideoLlavaConfig (VideoLlava model)
- videomae β VideoMAEConfig (VideoMAE model)
- vilt β ViltConfig (ViLT model)
- vipllava β VipLlavaConfig (VipLlava model)
- vision-encoder-decoder β VisionEncoderDecoderConfig (Vision Encoder decoder model)
- vision-text-dual-encoder β VisionTextDualEncoderConfig (VisionTextDualEncoder model)
- visual_bert β VisualBertConfig (VisualBERT model)
- vit β ViTConfig (ViT model)
- vit_hybrid β ViTHybridConfig (ViT Hybrid model)
- vit_mae β ViTMAEConfig (ViTMAE model)
- vit_msn β ViTMSNConfig (ViTMSN model)
- vitdet β VitDetConfig (VitDet model)
- vitmatte β VitMatteConfig (ViTMatte model)
- vits β VitsConfig (VITS model)
- vivit β VivitConfig (ViViT model)
- wav2vec2 β Wav2Vec2Config (Wav2Vec2 model)
- wav2vec2-bert β Wav2Vec2BertConfig (Wav2Vec2-BERT model)
- wav2vec2-conformer β Wav2Vec2ConformerConfig (Wav2Vec2-Conformer model)
- wavlm β WavLMConfig (WavLM model)
- whisper β WhisperConfig (Whisper model)
- xclip β XCLIPConfig (X-CLIP model)
- xglm β XGLMConfig (XGLM model)
- xlm β XLMConfig (XLM model)
- xlm-prophetnet β XLMProphetNetConfig (XLM-ProphetNet model)
- xlm-roberta β XLMRobertaConfig (XLM-RoBERTa model)
- xlm-roberta-xl β XLMRobertaXLConfig (XLM-RoBERTa-XL model)
- xlnet β XLNetConfig (XLNet model)
- xmod β XmodConfig (X-MOD model)
- yolos β YolosConfig (YOLOS model)
- yoso β YosoConfig (YOSO model)
- zamba β ZambaConfig (Zamba model)
- zoedepth β ZoeDepthConfig (ZoeDepth model)
Examples:
>>> from transformers import AutoConfig
>>> # Download configuration from huggingface.co and cache.
>>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased")
>>> # Download configuration from huggingface.co (user-uploaded) and cache.
>>> config = AutoConfig.from_pretrained("dbmdz/bert-base-german-cased")
>>> # If configuration file is in a directory (e.g., was saved using *save_pretrained('./test/saved_model/')*).
>>> config = AutoConfig.from_pretrained("./test/bert_saved_model/")
>>> # Load a specific configuration file.
>>> config = AutoConfig.from_pretrained("./test/bert_saved_model/my_configuration.json")
>>> # Change some config attributes when loading a pretrained config.
>>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False)
>>> config.output_attentions
True
>>> config, unused_kwargs = AutoConfig.from_pretrained(
... "google-bert/bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True
... )
>>> config.output_attentions
True
>>> unused_kwargs
{'foo': False}
register
< source >( model_type config exist_ok = False )
Parameters
- model_type (
str
) — The model type like “bert” or “gpt”. - config (PretrainedConfig) — The config to register.
Register a new configuration for this class.
AutoTokenizer
This is a generic tokenizer class that will be instantiated as one of the tokenizer classes of the library when created with the AutoTokenizer.from_pretrained() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_pretrained
< source >( pretrained_model_name_or_path *inputs **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- 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 save_pretrained() method, e.g.,
./my_model_directory/
. - A path or url to a single saved vocabulary file if and only if the tokenizer only requires a
single vocabulary file (like Bert or XLNet), e.g.:
./my_model_directory/vocab.txt
. (Not applicable to all derived classes)
- inputs (additional positional arguments, optional) —
Will be passed along to the Tokenizer
__init__()
method. - config (PretrainedConfig, optional) — The configuration object used to determine the tokenizer class to instantiate.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download the model weights and configuration files and override the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - subfolder (
str
, optional) — In case the relevant files are located inside a subfolder of the model repo on huggingface.co (e.g. for facebook/rag-token-base), specify it here. - use_fast (
bool
, optional, defaults toTrue
) — Use a fast Rust-based tokenizer if it is supported for a given model. If a fast tokenizer is not available for a given model, a normal Python-based tokenizer is returned instead. - tokenizer_type (
str
, optional) — Tokenizer type to be loaded. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - kwargs (additional keyword arguments, optional) —
Will be passed to the Tokenizer
__init__()
method. Can be used to set special tokens likebos_token
,eos_token
,unk_token
,sep_token
,pad_token
,cls_token
,mask_token
,additional_special_tokens
. See parameters in the__init__()
for more details.
Instantiate one of the tokenizer classes of the library from a pretrained model vocabulary.
The tokenizer class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β AlbertTokenizer or AlbertTokenizerFast (ALBERT model)
- align β BertTokenizer or BertTokenizerFast (ALIGN model)
- aria β LlamaTokenizer or LlamaTokenizerFast (Aria model)
- bark β BertTokenizer or BertTokenizerFast (Bark model)
- bart β BartTokenizer or BartTokenizerFast (BART model)
- barthez β BarthezTokenizer or BarthezTokenizerFast (BARThez model)
- bartpho β BartphoTokenizer (BARTpho model)
- bert β BertTokenizer or BertTokenizerFast (BERT model)
- bert-generation β BertGenerationTokenizer (Bert Generation model)
- bert-japanese β BertJapaneseTokenizer (BertJapanese model)
- bertweet β BertweetTokenizer (BERTweet model)
- big_bird β BigBirdTokenizer or BigBirdTokenizerFast (BigBird model)
- bigbird_pegasus β PegasusTokenizer or PegasusTokenizerFast (BigBird-Pegasus model)
- biogpt β BioGptTokenizer (BioGpt model)
- blenderbot β BlenderbotTokenizer or BlenderbotTokenizerFast (Blenderbot model)
- blenderbot-small β BlenderbotSmallTokenizer (BlenderbotSmall model)
- blip β BertTokenizer or BertTokenizerFast (BLIP model)
- blip-2 β GPT2Tokenizer or GPT2TokenizerFast (BLIP-2 model)
- bloom β BloomTokenizerFast (BLOOM model)
- bridgetower β RobertaTokenizer or RobertaTokenizerFast (BridgeTower model)
- bros β BertTokenizer or BertTokenizerFast (BROS model)
- byt5 β ByT5Tokenizer (ByT5 model)
- camembert β CamembertTokenizer or CamembertTokenizerFast (CamemBERT model)
- canine β CanineTokenizer (CANINE model)
- chameleon β LlamaTokenizer or LlamaTokenizerFast (Chameleon model)
- chinese_clip β BertTokenizer or BertTokenizerFast (Chinese-CLIP model)
- clap β RobertaTokenizer or RobertaTokenizerFast (CLAP model)
- clip β CLIPTokenizer or CLIPTokenizerFast (CLIP model)
- clipseg β CLIPTokenizer or CLIPTokenizerFast (CLIPSeg model)
- clvp β ClvpTokenizer (CLVP model)
- code_llama β CodeLlamaTokenizer or CodeLlamaTokenizerFast (CodeLlama model)
- codegen β CodeGenTokenizer or CodeGenTokenizerFast (CodeGen model)
- cohere β CohereTokenizerFast (Cohere model)
- cohere2 β CohereTokenizerFast (Cohere2 model)
- colpali β LlamaTokenizer or LlamaTokenizerFast (ColPali model)
- convbert β ConvBertTokenizer or ConvBertTokenizerFast (ConvBERT model)
- cpm β CpmTokenizer or CpmTokenizerFast (CPM model)
- cpmant β CpmAntTokenizer (CPM-Ant model)
- ctrl β CTRLTokenizer (CTRL model)
- data2vec-audio β Wav2Vec2CTCTokenizer (Data2VecAudio model)
- data2vec-text β RobertaTokenizer or RobertaTokenizerFast (Data2VecText model)
- dbrx β GPT2Tokenizer or GPT2TokenizerFast (DBRX model)
- deberta β DebertaTokenizer or DebertaTokenizerFast (DeBERTa model)
- deberta-v2 β DebertaV2Tokenizer or DebertaV2TokenizerFast (DeBERTa-v2 model)
- distilbert β DistilBertTokenizer or DistilBertTokenizerFast (DistilBERT model)
- dpr β DPRQuestionEncoderTokenizer or DPRQuestionEncoderTokenizerFast (DPR model)
- electra β ElectraTokenizer or ElectraTokenizerFast (ELECTRA model)
- ernie β BertTokenizer or BertTokenizerFast (ERNIE model)
- ernie_m β ErnieMTokenizer (ErnieM model)
- esm β EsmTokenizer (ESM model)
- falcon β PreTrainedTokenizerFast (Falcon model)
- falcon_mamba β GPTNeoXTokenizerFast (FalconMamba model)
- fastspeech2_conformer β (FastSpeech2Conformer model)
- flaubert β FlaubertTokenizer (FlauBERT model)
- fnet β FNetTokenizer or FNetTokenizerFast (FNet model)
- fsmt β FSMTTokenizer (FairSeq Machine-Translation model)
- funnel β FunnelTokenizer or FunnelTokenizerFast (Funnel Transformer model)
- gemma β GemmaTokenizer or GemmaTokenizerFast (Gemma model)
- gemma2 β GemmaTokenizer or GemmaTokenizerFast (Gemma2 model)
- git β BertTokenizer or BertTokenizerFast (GIT model)
- glm β PreTrainedTokenizerFast (GLM model)
- gpt-sw3 β GPTSw3Tokenizer (GPT-Sw3 model)
- gpt2 β GPT2Tokenizer or GPT2TokenizerFast (OpenAI GPT-2 model)
- gpt_bigcode β GPT2Tokenizer or GPT2TokenizerFast (GPTBigCode model)
- gpt_neo β GPT2Tokenizer or GPT2TokenizerFast (GPT Neo model)
- gpt_neox β GPTNeoXTokenizerFast (GPT NeoX model)
- gpt_neox_japanese β GPTNeoXJapaneseTokenizer (GPT NeoX Japanese model)
- gptj β GPT2Tokenizer or GPT2TokenizerFast (GPT-J model)
- gptsan-japanese β GPTSanJapaneseTokenizer (GPTSAN-japanese model)
- grounding-dino β BertTokenizer or BertTokenizerFast (Grounding DINO model)
- groupvit β CLIPTokenizer or CLIPTokenizerFast (GroupViT model)
- herbert β HerbertTokenizer or HerbertTokenizerFast (HerBERT model)
- hubert β Wav2Vec2CTCTokenizer (Hubert model)
- ibert β RobertaTokenizer or RobertaTokenizerFast (I-BERT model)
- idefics β LlamaTokenizerFast (IDEFICS model)
- idefics2 β LlamaTokenizer or LlamaTokenizerFast (Idefics2 model)
- idefics3 β LlamaTokenizer or LlamaTokenizerFast (Idefics3 model)
- instructblip β GPT2Tokenizer or GPT2TokenizerFast (InstructBLIP model)
- instructblipvideo β GPT2Tokenizer or GPT2TokenizerFast (InstructBlipVideo model)
- jamba β LlamaTokenizer or LlamaTokenizerFast (Jamba model)
- jetmoe β LlamaTokenizer or LlamaTokenizerFast (JetMoe model)
- jukebox β JukeboxTokenizer (Jukebox model)
- kosmos-2 β XLMRobertaTokenizer or XLMRobertaTokenizerFast (KOSMOS-2 model)
- layoutlm β LayoutLMTokenizer or LayoutLMTokenizerFast (LayoutLM model)
- layoutlmv2 β LayoutLMv2Tokenizer or LayoutLMv2TokenizerFast (LayoutLMv2 model)
- layoutlmv3 β LayoutLMv3Tokenizer or LayoutLMv3TokenizerFast (LayoutLMv3 model)
- layoutxlm β LayoutXLMTokenizer or LayoutXLMTokenizerFast (LayoutXLM model)
- led β LEDTokenizer or LEDTokenizerFast (LED model)
- lilt β LayoutLMv3Tokenizer or LayoutLMv3TokenizerFast (LiLT model)
- llama β LlamaTokenizer or LlamaTokenizerFast (LLaMA model)
- llava β LlamaTokenizer or LlamaTokenizerFast (LLaVa model)
- llava_next β LlamaTokenizer or LlamaTokenizerFast (LLaVA-NeXT model)
- llava_next_video β LlamaTokenizer or LlamaTokenizerFast (LLaVa-NeXT-Video model)
- llava_onevision β LlamaTokenizer or LlamaTokenizerFast (LLaVA-Onevision model)
- longformer β LongformerTokenizer or LongformerTokenizerFast (Longformer model)
- longt5 β T5Tokenizer or T5TokenizerFast (LongT5 model)
- luke β LukeTokenizer (LUKE model)
- lxmert β LxmertTokenizer or LxmertTokenizerFast (LXMERT model)
- m2m_100 β M2M100Tokenizer (M2M100 model)
- mamba β GPTNeoXTokenizerFast (Mamba model)
- mamba2 β GPTNeoXTokenizerFast (mamba2 model)
- marian β MarianTokenizer (Marian model)
- mbart β MBartTokenizer or MBartTokenizerFast (mBART model)
- mbart50 β MBart50Tokenizer or MBart50TokenizerFast (mBART-50 model)
- mega β RobertaTokenizer or RobertaTokenizerFast (MEGA model)
- megatron-bert β BertTokenizer or BertTokenizerFast (Megatron-BERT model)
- mgp-str β MgpstrTokenizer (MGP-STR model)
- mistral β LlamaTokenizer or LlamaTokenizerFast (Mistral model)
- mixtral β LlamaTokenizer or LlamaTokenizerFast (Mixtral model)
- mllama β LlamaTokenizer or LlamaTokenizerFast (Mllama model)
- mluke β MLukeTokenizer (mLUKE model)
- mobilebert β MobileBertTokenizer or MobileBertTokenizerFast (MobileBERT model)
- modernbert β PreTrainedTokenizerFast (ModernBERT model)
- moshi β PreTrainedTokenizerFast (Moshi model)
- mpnet β MPNetTokenizer or MPNetTokenizerFast (MPNet model)
- mpt β GPTNeoXTokenizerFast (MPT model)
- mra β RobertaTokenizer or RobertaTokenizerFast (MRA model)
- mt5 β MT5Tokenizer or MT5TokenizerFast (MT5 model)
- musicgen β T5Tokenizer or T5TokenizerFast (MusicGen model)
- musicgen_melody β T5Tokenizer or T5TokenizerFast (MusicGen Melody model)
- mvp β MvpTokenizer or MvpTokenizerFast (MVP model)
- myt5 β MyT5Tokenizer (myt5 model)
- nezha β BertTokenizer or BertTokenizerFast (Nezha model)
- nllb β NllbTokenizer or NllbTokenizerFast (NLLB model)
- nllb-moe β NllbTokenizer or NllbTokenizerFast (NLLB-MOE model)
- nystromformer β AlbertTokenizer or AlbertTokenizerFast (NystrΓΆmformer model)
- olmo β GPTNeoXTokenizerFast (OLMo model)
- olmo2 β GPTNeoXTokenizerFast (OLMo2 model)
- olmoe β GPTNeoXTokenizerFast (OLMoE model)
- omdet-turbo β CLIPTokenizer or CLIPTokenizerFast (OmDet-Turbo model)
- oneformer β CLIPTokenizer or CLIPTokenizerFast (OneFormer model)
- openai-gpt β OpenAIGPTTokenizer or OpenAIGPTTokenizerFast (OpenAI GPT model)
- opt β GPT2Tokenizer or GPT2TokenizerFast (OPT model)
- owlv2 β CLIPTokenizer or CLIPTokenizerFast (OWLv2 model)
- owlvit β CLIPTokenizer or CLIPTokenizerFast (OWL-ViT model)
- paligemma β LlamaTokenizer or LlamaTokenizerFast (PaliGemma model)
- pegasus β PegasusTokenizer or PegasusTokenizerFast (Pegasus model)
- pegasus_x β PegasusTokenizer or PegasusTokenizerFast (PEGASUS-X model)
- perceiver β PerceiverTokenizer (Perceiver model)
- persimmon β LlamaTokenizer or LlamaTokenizerFast (Persimmon model)
- phi β CodeGenTokenizer or CodeGenTokenizerFast (Phi model)
- phi3 β LlamaTokenizer or LlamaTokenizerFast (Phi3 model)
- phimoe β LlamaTokenizer or LlamaTokenizerFast (Phimoe model)
- phobert β PhobertTokenizer (PhoBERT model)
- pix2struct β T5Tokenizer or T5TokenizerFast (Pix2Struct model)
- pixtral β PreTrainedTokenizerFast (Pixtral model)
- plbart β PLBartTokenizer (PLBart model)
- prophetnet β ProphetNetTokenizer (ProphetNet model)
- qdqbert β BertTokenizer or BertTokenizerFast (QDQBert model)
- qwen2 β Qwen2Tokenizer or Qwen2TokenizerFast (Qwen2 model)
- qwen2_audio β Qwen2Tokenizer or Qwen2TokenizerFast (Qwen2Audio model)
- qwen2_moe β Qwen2Tokenizer or Qwen2TokenizerFast (Qwen2MoE model)
- qwen2_vl β Qwen2Tokenizer or Qwen2TokenizerFast (Qwen2VL model)
- rag β RagTokenizer (RAG model)
- realm β RealmTokenizer or RealmTokenizerFast (REALM model)
- recurrent_gemma β GemmaTokenizer or GemmaTokenizerFast (RecurrentGemma model)
- reformer β ReformerTokenizer or ReformerTokenizerFast (Reformer model)
- rembert β RemBertTokenizer or RemBertTokenizerFast (RemBERT model)
- retribert β RetriBertTokenizer or RetriBertTokenizerFast (RetriBERT model)
- roberta β RobertaTokenizer or RobertaTokenizerFast (RoBERTa model)
- roberta-prelayernorm β RobertaTokenizer or RobertaTokenizerFast (RoBERTa-PreLayerNorm model)
- roc_bert β RoCBertTokenizer (RoCBert model)
- roformer β RoFormerTokenizer or RoFormerTokenizerFast (RoFormer model)
- rwkv β GPTNeoXTokenizerFast (RWKV model)
- seamless_m4t β SeamlessM4TTokenizer or SeamlessM4TTokenizerFast (SeamlessM4T model)
- seamless_m4t_v2 β SeamlessM4TTokenizer or SeamlessM4TTokenizerFast (SeamlessM4Tv2 model)
- siglip β SiglipTokenizer (SigLIP model)
- speech_to_text β Speech2TextTokenizer (Speech2Text model)
- speech_to_text_2 β Speech2Text2Tokenizer (Speech2Text2 model)
- speecht5 β SpeechT5Tokenizer (SpeechT5 model)
- splinter β SplinterTokenizer or SplinterTokenizerFast (Splinter model)
- squeezebert β SqueezeBertTokenizer or SqueezeBertTokenizerFast (SqueezeBERT model)
- stablelm β GPTNeoXTokenizerFast (StableLm model)
- starcoder2 β GPT2Tokenizer or GPT2TokenizerFast (Starcoder2 model)
- switch_transformers β T5Tokenizer or T5TokenizerFast (SwitchTransformers model)
- t5 β T5Tokenizer or T5TokenizerFast (T5 model)
- tapas β TapasTokenizer (TAPAS model)
- tapex β TapexTokenizer (TAPEX model)
- transfo-xl β TransfoXLTokenizer (Transformer-XL model)
- tvp β BertTokenizer or BertTokenizerFast (TVP model)
- udop β UdopTokenizer or UdopTokenizerFast (UDOP model)
- umt5 β T5Tokenizer or T5TokenizerFast (UMT5 model)
- video_llava β LlamaTokenizer or LlamaTokenizerFast (VideoLlava model)
- vilt β BertTokenizer or BertTokenizerFast (ViLT model)
- vipllava β LlamaTokenizer or LlamaTokenizerFast (VipLlava model)
- visual_bert β BertTokenizer or BertTokenizerFast (VisualBERT model)
- vits β VitsTokenizer (VITS model)
- wav2vec2 β Wav2Vec2CTCTokenizer (Wav2Vec2 model)
- wav2vec2-bert β Wav2Vec2CTCTokenizer (Wav2Vec2-BERT model)
- wav2vec2-conformer β Wav2Vec2CTCTokenizer (Wav2Vec2-Conformer model)
- wav2vec2_phoneme β Wav2Vec2PhonemeCTCTokenizer (Wav2Vec2Phoneme model)
- whisper β WhisperTokenizer or WhisperTokenizerFast (Whisper model)
- xclip β CLIPTokenizer or CLIPTokenizerFast (X-CLIP model)
- xglm β XGLMTokenizer or XGLMTokenizerFast (XGLM model)
- xlm β XLMTokenizer (XLM model)
- xlm-prophetnet β XLMProphetNetTokenizer (XLM-ProphetNet model)
- xlm-roberta β XLMRobertaTokenizer or XLMRobertaTokenizerFast (XLM-RoBERTa model)
- xlm-roberta-xl β XLMRobertaTokenizer or XLMRobertaTokenizerFast (XLM-RoBERTa-XL model)
- xlnet β XLNetTokenizer or XLNetTokenizerFast (XLNet model)
- xmod β XLMRobertaTokenizer or XLMRobertaTokenizerFast (X-MOD model)
- yoso β AlbertTokenizer or AlbertTokenizerFast (YOSO model)
- zamba β LlamaTokenizer or LlamaTokenizerFast (Zamba model)
Examples:
>>> from transformers import AutoTokenizer
>>> # Download vocabulary from huggingface.co and cache.
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
>>> # Download vocabulary from huggingface.co (user-uploaded) and cache.
>>> tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-base-german-cased")
>>> # If vocabulary files are in a directory (e.g. tokenizer was saved using *save_pretrained('./test/saved_model/')*)
>>> # tokenizer = AutoTokenizer.from_pretrained("./test/bert_saved_model/")
>>> # Download vocabulary from huggingface.co and define model-specific arguments
>>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base", add_prefix_space=True)
register
< source >( config_class slow_tokenizer_class = None fast_tokenizer_class = None exist_ok = False )
Parameters
- config_class (PretrainedConfig) — The configuration corresponding to the model to register.
- slow_tokenizer_class (
PretrainedTokenizer
, optional) — The slow tokenizer to register. - fast_tokenizer_class (
PretrainedTokenizerFast
, optional) — The fast tokenizer to register.
Register a new tokenizer in this mapping.
AutoFeatureExtractor
This is a generic feature extractor class that will be instantiated as one of the feature extractor classes of the library when created with the AutoFeatureExtractor.from_pretrained() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_pretrained
< source >( pretrained_model_name_or_path **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — This can be either:- a string, the model id of a pretrained feature_extractor hosted inside a model repo on huggingface.co.
- a path to a directory containing a feature extractor file saved using the
save_pretrained() method, e.g.,
./my_model_directory/
. - a path or url to a saved feature extractor JSON file, e.g.,
./my_model_directory/preprocessor_config.json
.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model feature extractor should be cached if the standard cache should not be used. - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force to (re-)download the feature extractor files and override the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.
The proxies are used on each request. - token (
str
or bool, optional) — The token to use as HTTP bearer authorization for remote files. IfTrue
, will use the token generated when runninghuggingface-cli login
(stored in~/.huggingface
). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - return_unused_kwargs (
bool
, optional, defaults toFalse
) — IfFalse
, then this function returns just the final feature extractor object. IfTrue
, then this functions returns aTuple(feature_extractor, unused_kwargs)
where unused_kwargs is a dictionary consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part ofkwargs
which has not been used to updatefeature_extractor
and is otherwise ignored. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - kwargs (
Dict[str, Any]
, optional) — The values in kwargs of any keys which are feature extractor attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are not feature extractor attributes is controlled by thereturn_unused_kwargs
keyword parameter.
Instantiate one of the feature extractor classes of the library from a pretrained model vocabulary.
The feature extractor class to instantiate is selected based on the model_type
property of the config object
(either passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs
missing, by falling back to using pattern matching on pretrained_model_name_or_path
:
- audio-spectrogram-transformer β ASTFeatureExtractor (Audio Spectrogram Transformer model)
- beit β BeitFeatureExtractor (BEiT model)
- chinese_clip β ChineseCLIPFeatureExtractor (Chinese-CLIP model)
- clap β ClapFeatureExtractor (CLAP model)
- clip β CLIPFeatureExtractor (CLIP model)
- clipseg β ViTFeatureExtractor (CLIPSeg model)
- clvp β ClvpFeatureExtractor (CLVP model)
- conditional_detr β ConditionalDetrFeatureExtractor (Conditional DETR model)
- convnext β ConvNextFeatureExtractor (ConvNeXT model)
- cvt β ConvNextFeatureExtractor (CvT model)
- dac β DacFeatureExtractor (DAC model)
- data2vec-audio β Wav2Vec2FeatureExtractor (Data2VecAudio model)
- data2vec-vision β BeitFeatureExtractor (Data2VecVision model)
- deformable_detr β DeformableDetrFeatureExtractor (Deformable DETR model)
- deit β DeiTFeatureExtractor (DeiT model)
- detr β DetrFeatureExtractor (DETR model)
- dinat β ViTFeatureExtractor (DiNAT model)
- donut-swin β DonutFeatureExtractor (DonutSwin model)
- dpt β DPTFeatureExtractor (DPT model)
- encodec β EncodecFeatureExtractor (EnCodec model)
- flava β FlavaFeatureExtractor (FLAVA model)
- glpn β GLPNFeatureExtractor (GLPN model)
- groupvit β CLIPFeatureExtractor (GroupViT model)
- hubert β Wav2Vec2FeatureExtractor (Hubert model)
- imagegpt β ImageGPTFeatureExtractor (ImageGPT model)
- layoutlmv2 β LayoutLMv2FeatureExtractor (LayoutLMv2 model)
- layoutlmv3 β LayoutLMv3FeatureExtractor (LayoutLMv3 model)
- levit β LevitFeatureExtractor (LeViT model)
- maskformer β MaskFormerFeatureExtractor (MaskFormer model)
- mctct β MCTCTFeatureExtractor (M-CTC-T model)
- mimi β EncodecFeatureExtractor (Mimi model)
- mobilenet_v1 β MobileNetV1FeatureExtractor (MobileNetV1 model)
- mobilenet_v2 β MobileNetV2FeatureExtractor (MobileNetV2 model)
- mobilevit β MobileViTFeatureExtractor (MobileViT model)
- moshi β EncodecFeatureExtractor (Moshi model)
- nat β ViTFeatureExtractor (NAT model)
- owlvit β OwlViTFeatureExtractor (OWL-ViT model)
- perceiver β PerceiverFeatureExtractor (Perceiver model)
- poolformer β PoolFormerFeatureExtractor (PoolFormer model)
- pop2piano β Pop2PianoFeatureExtractor (Pop2Piano model)
- regnet β ConvNextFeatureExtractor (RegNet model)
- resnet β ConvNextFeatureExtractor (ResNet model)
- seamless_m4t β SeamlessM4TFeatureExtractor (SeamlessM4T model)
- seamless_m4t_v2 β SeamlessM4TFeatureExtractor (SeamlessM4Tv2 model)
- segformer β SegformerFeatureExtractor (SegFormer model)
- sew β Wav2Vec2FeatureExtractor (SEW model)
- sew-d β Wav2Vec2FeatureExtractor (SEW-D model)
- speech_to_text β Speech2TextFeatureExtractor (Speech2Text model)
- speecht5 β SpeechT5FeatureExtractor (SpeechT5 model)
- swiftformer β ViTFeatureExtractor (SwiftFormer model)
- swin β ViTFeatureExtractor (Swin Transformer model)
- swinv2 β ViTFeatureExtractor (Swin Transformer V2 model)
- table-transformer β DetrFeatureExtractor (Table Transformer model)
- timesformer β VideoMAEFeatureExtractor (TimeSformer model)
- tvlt β TvltFeatureExtractor (TVLT model)
- unispeech β Wav2Vec2FeatureExtractor (UniSpeech model)
- unispeech-sat β Wav2Vec2FeatureExtractor (UniSpeechSat model)
- univnet β UnivNetFeatureExtractor (UnivNet model)
- van β ConvNextFeatureExtractor (VAN model)
- videomae β VideoMAEFeatureExtractor (VideoMAE model)
- vilt β ViltFeatureExtractor (ViLT model)
- vit β ViTFeatureExtractor (ViT model)
- vit_mae β ViTFeatureExtractor (ViTMAE model)
- vit_msn β ViTFeatureExtractor (ViTMSN model)
- wav2vec2 β Wav2Vec2FeatureExtractor (Wav2Vec2 model)
- wav2vec2-bert β Wav2Vec2FeatureExtractor (Wav2Vec2-BERT model)
- wav2vec2-conformer β Wav2Vec2FeatureExtractor (Wav2Vec2-Conformer model)
- wavlm β Wav2Vec2FeatureExtractor (WavLM model)
- whisper β WhisperFeatureExtractor (Whisper model)
- xclip β CLIPFeatureExtractor (X-CLIP model)
- yolos β YolosFeatureExtractor (YOLOS model)
Passing token=True
is required when you want to use a private model.
Examples:
>>> from transformers import AutoFeatureExtractor
>>> # Download feature extractor from huggingface.co and cache.
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
>>> # If feature extractor files are in a directory (e.g. feature extractor was saved using *save_pretrained('./test/saved_model/')*)
>>> # feature_extractor = AutoFeatureExtractor.from_pretrained("./test/saved_model/")
register
< source >( config_class feature_extractor_class exist_ok = False )
Parameters
- config_class (PretrainedConfig) — The configuration corresponding to the model to register.
- feature_extractor_class (
FeatureExtractorMixin
) — The feature extractor to register.
Register a new feature extractor for this class.
AutoImageProcessor
This is a generic image processor class that will be instantiated as one of the image processor classes of the library when created with the AutoImageProcessor.from_pretrained() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_pretrained
< source >( pretrained_model_name_or_path *inputs **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — This can be either:- a string, the model id of a pretrained image_processor hosted inside a model repo on huggingface.co.
- a path to a directory containing a image processor file saved using the
save_pretrained() method, e.g.,
./my_model_directory/
. - a path or url to a saved image processor JSON file, e.g.,
./my_model_directory/preprocessor_config.json
.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model image processor should be cached if the standard cache should not be used. - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force to (re-)download the image processor files and override the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.
The proxies are used on each request. - token (
str
or bool, optional) — The token to use as HTTP bearer authorization for remote files. IfTrue
, will use the token generated when runninghuggingface-cli login
(stored in~/.huggingface
). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - use_fast (
bool
, optional, defaults toFalse
) — Use a fast torchvision-base image processor if it is supported for a given model. If a fast image processor is not available for a given model, a normal numpy-based image processor is returned instead. - return_unused_kwargs (
bool
, optional, defaults toFalse
) — IfFalse
, then this function returns just the final image processor object. IfTrue
, then this functions returns aTuple(image_processor, unused_kwargs)
where unused_kwargs is a dictionary consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part ofkwargs
which has not been used to updateimage_processor
and is otherwise ignored. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - image_processor_filename (
str
, optional, defaults to"config.json"
) — The name of the file in the model directory to use for the image processor config. - kwargs (
Dict[str, Any]
, optional) — The values in kwargs of any keys which are image processor attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are not image processor attributes is controlled by thereturn_unused_kwargs
keyword parameter.
Instantiate one of the image processor classes of the library from a pretrained model vocabulary.
The image processor class to instantiate is selected based on the model_type
property of the config object
(either passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs
missing, by falling back to using pattern matching on pretrained_model_name_or_path
:
- align β EfficientNetImageProcessor (ALIGN model)
- aria β
A
orr
(Aria model) - beit β BeitImageProcessor (BEiT model)
- bit β BitImageProcessor (BiT model)
- blip β BlipImageProcessor (BLIP model)
- blip-2 β BlipImageProcessor (BLIP-2 model)
- bridgetower β BridgeTowerImageProcessor (BridgeTower model)
- chameleon β ChameleonImageProcessor (Chameleon model)
- chinese_clip β ChineseCLIPImageProcessor (Chinese-CLIP model)
- clip β CLIPImageProcessor (CLIP model)
- clipseg β ViTImageProcessor or ViTImageProcessorFast (CLIPSeg model)
- conditional_detr β ConditionalDetrImageProcessor (Conditional DETR model)
- convnext β ConvNextImageProcessor (ConvNeXT model)
- convnextv2 β ConvNextImageProcessor (ConvNeXTV2 model)
- cvt β ConvNextImageProcessor (CvT model)
- data2vec-vision β BeitImageProcessor (Data2VecVision model)
- deformable_detr β DeformableDetrImageProcessor or DeformableDetrImageProcessorFast (Deformable DETR model)
- deit β DeiTImageProcessor (DeiT model)
- depth_anything β DPTImageProcessor (Depth Anything model)
- deta β DetaImageProcessor (DETA model)
- detr β DetrImageProcessor or DetrImageProcessorFast (DETR model)
- dinat β ViTImageProcessor or ViTImageProcessorFast (DiNAT model)
- dinov2 β BitImageProcessor (DINOv2 model)
- donut-swin β DonutImageProcessor (DonutSwin model)
- dpt β DPTImageProcessor (DPT model)
- efficientformer β EfficientFormerImageProcessor (EfficientFormer model)
- efficientnet β EfficientNetImageProcessor (EfficientNet model)
- flava β FlavaImageProcessor (FLAVA model)
- focalnet β BitImageProcessor (FocalNet model)
- fuyu β FuyuImageProcessor (Fuyu model)
- git β CLIPImageProcessor (GIT model)
- glpn β GLPNImageProcessor (GLPN model)
- grounding-dino β GroundingDinoImageProcessor (Grounding DINO model)
- groupvit β CLIPImageProcessor (GroupViT model)
- hiera β BitImageProcessor (Hiera model)
- idefics β IdeficsImageProcessor (IDEFICS model)
- idefics2 β Idefics2ImageProcessor (Idefics2 model)
- idefics3 β Idefics3ImageProcessor (Idefics3 model)
- ijepa β ViTImageProcessor or ViTImageProcessorFast (I-JEPA model)
- imagegpt β ImageGPTImageProcessor (ImageGPT model)
- instructblip β BlipImageProcessor (InstructBLIP model)
- instructblipvideo β InstructBlipVideoImageProcessor (InstructBlipVideo model)
- kosmos-2 β CLIPImageProcessor (KOSMOS-2 model)
- layoutlmv2 β LayoutLMv2ImageProcessor (LayoutLMv2 model)
- layoutlmv3 β LayoutLMv3ImageProcessor (LayoutLMv3 model)
- levit β LevitImageProcessor (LeViT model)
- llava β CLIPImageProcessor (LLaVa model)
- llava_next β LlavaNextImageProcessor (LLaVA-NeXT model)
- llava_next_video β LlavaNextVideoImageProcessor (LLaVa-NeXT-Video model)
- llava_onevision β LlavaOnevisionImageProcessor (LLaVA-Onevision model)
- mask2former β Mask2FormerImageProcessor (Mask2Former model)
- maskformer β MaskFormerImageProcessor (MaskFormer model)
- mgp-str β ViTImageProcessor or ViTImageProcessorFast (MGP-STR model)
- mllama β MllamaImageProcessor (Mllama model)
- mobilenet_v1 β MobileNetV1ImageProcessor (MobileNetV1 model)
- mobilenet_v2 β MobileNetV2ImageProcessor (MobileNetV2 model)
- mobilevit β MobileViTImageProcessor (MobileViT model)
- mobilevitv2 β MobileViTImageProcessor (MobileViTV2 model)
- nat β ViTImageProcessor or ViTImageProcessorFast (NAT model)
- nougat β NougatImageProcessor (Nougat model)
- oneformer β OneFormerImageProcessor (OneFormer model)
- owlv2 β Owlv2ImageProcessor (OWLv2 model)
- owlvit β OwlViTImageProcessor (OWL-ViT model)
- paligemma β SiglipImageProcessor (PaliGemma model)
- perceiver β PerceiverImageProcessor (Perceiver model)
- pix2struct β Pix2StructImageProcessor (Pix2Struct model)
- pixtral β PixtralImageProcessor or PixtralImageProcessorFast (Pixtral model)
- poolformer β PoolFormerImageProcessor (PoolFormer model)
- pvt β PvtImageProcessor (PVT model)
- pvt_v2 β PvtImageProcessor (PVTv2 model)
- qwen2_vl β Qwen2VLImageProcessor (Qwen2VL model)
- regnet β ConvNextImageProcessor (RegNet model)
- resnet β ConvNextImageProcessor (ResNet model)
- rt_detr β RTDetrImageProcessor or RTDetrImageProcessorFast (RT-DETR model)
- sam β SamImageProcessor (SAM model)
- segformer β SegformerImageProcessor (SegFormer model)
- seggpt β SegGptImageProcessor (SegGPT model)
- siglip β SiglipImageProcessor (SigLIP model)
- swiftformer β ViTImageProcessor or ViTImageProcessorFast (SwiftFormer model)
- swin β ViTImageProcessor or ViTImageProcessorFast (Swin Transformer model)
- swin2sr β Swin2SRImageProcessor (Swin2SR model)
- swinv2 β ViTImageProcessor or ViTImageProcessorFast (Swin Transformer V2 model)
- table-transformer β DetrImageProcessor (Table Transformer model)
- timesformer β VideoMAEImageProcessor (TimeSformer model)
- timm_wrapper β TimmWrapperImageProcessor (TimmWrapperModel model)
- tvlt β TvltImageProcessor (TVLT model)
- tvp β TvpImageProcessor (TVP model)
- udop β LayoutLMv3ImageProcessor (UDOP model)
- upernet β SegformerImageProcessor (UPerNet model)
- van β ConvNextImageProcessor (VAN model)
- videomae β VideoMAEImageProcessor (VideoMAE model)
- vilt β ViltImageProcessor (ViLT model)
- vipllava β CLIPImageProcessor (VipLlava model)
- vit β ViTImageProcessor or ViTImageProcessorFast (ViT model)
- vit_hybrid β ViTHybridImageProcessor (ViT Hybrid model)
- vit_mae β ViTImageProcessor or ViTImageProcessorFast (ViTMAE model)
- vit_msn β ViTImageProcessor or ViTImageProcessorFast (ViTMSN model)
- vitmatte β VitMatteImageProcessor (ViTMatte model)
- xclip β CLIPImageProcessor (X-CLIP model)
- yolos β YolosImageProcessor (YOLOS model)
- zoedepth β ZoeDepthImageProcessor (ZoeDepth model)
Passing token=True
is required when you want to use a private model.
Examples:
>>> from transformers import AutoImageProcessor
>>> # Download image processor from huggingface.co and cache.
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
>>> # If image processor files are in a directory (e.g. image processor was saved using *save_pretrained('./test/saved_model/')*)
>>> # image_processor = AutoImageProcessor.from_pretrained("./test/saved_model/")
register
< source >( config_class image_processor_class = None slow_image_processor_class = None fast_image_processor_class = None exist_ok = False )
Parameters
- config_class (PretrainedConfig) — The configuration corresponding to the model to register.
- image_processor_class (ImageProcessingMixin) — The image processor to register.
Register a new image processor for this class.
AutoProcessor
This is a generic processor class that will be instantiated as one of the processor classes of the library when created with the AutoProcessor.from_pretrained() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_pretrained
< source >( pretrained_model_name_or_path **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — This can be either:- a string, the model id of a pretrained feature_extractor hosted inside a model repo on huggingface.co.
- a path to a directory containing a processor files saved using the
save_pretrained()
method, e.g.,./my_model_directory/
.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model feature extractor should be cached if the standard cache should not be used. - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force to (re-)download the feature extractor files and override the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.
The proxies are used on each request. - token (
str
or bool, optional) — The token to use as HTTP bearer authorization for remote files. IfTrue
, will use the token generated when runninghuggingface-cli login
(stored in~/.huggingface
). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - return_unused_kwargs (
bool
, optional, defaults toFalse
) — IfFalse
, then this function returns just the final feature extractor object. IfTrue
, then this functions returns aTuple(feature_extractor, unused_kwargs)
where unused_kwargs is a dictionary consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part ofkwargs
which has not been used to updatefeature_extractor
and is otherwise ignored. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - kwargs (
Dict[str, Any]
, optional) — The values in kwargs of any keys which are feature extractor attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are not feature extractor attributes is controlled by thereturn_unused_kwargs
keyword parameter.
Instantiate one of the processor classes of the library from a pretrained model vocabulary.
The processor class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible):
- align β AlignProcessor (ALIGN model)
- altclip β AltCLIPProcessor (AltCLIP model)
- aria β AriaProcessor (Aria model)
- bark β BarkProcessor (Bark model)
- blip β BlipProcessor (BLIP model)
- blip-2 β Blip2Processor (BLIP-2 model)
- bridgetower β BridgeTowerProcessor (BridgeTower model)
- chameleon β ChameleonProcessor (Chameleon model)
- chinese_clip β ChineseCLIPProcessor (Chinese-CLIP model)
- clap β ClapProcessor (CLAP model)
- clip β CLIPProcessor (CLIP model)
- clipseg β CLIPSegProcessor (CLIPSeg model)
- clvp β ClvpProcessor (CLVP model)
- colpali β ColPaliProcessor (ColPali model)
- flava β FlavaProcessor (FLAVA model)
- fuyu β FuyuProcessor (Fuyu model)
- git β GitProcessor (GIT model)
- grounding-dino β GroundingDinoProcessor (Grounding DINO model)
- groupvit β CLIPProcessor (GroupViT model)
- hubert β Wav2Vec2Processor (Hubert model)
- idefics β IdeficsProcessor (IDEFICS model)
- idefics2 β Idefics2Processor (Idefics2 model)
- idefics3 β Idefics3Processor (Idefics3 model)
- instructblip β InstructBlipProcessor (InstructBLIP model)
- instructblipvideo β InstructBlipVideoProcessor (InstructBlipVideo model)
- kosmos-2 β Kosmos2Processor (KOSMOS-2 model)
- layoutlmv2 β LayoutLMv2Processor (LayoutLMv2 model)
- layoutlmv3 β LayoutLMv3Processor (LayoutLMv3 model)
- llava β LlavaProcessor (LLaVa model)
- llava_next β LlavaNextProcessor (LLaVA-NeXT model)
- llava_next_video β LlavaNextVideoProcessor (LLaVa-NeXT-Video model)
- llava_onevision β LlavaOnevisionProcessor (LLaVA-Onevision model)
- markuplm β MarkupLMProcessor (MarkupLM model)
- mctct β MCTCTProcessor (M-CTC-T model)
- mgp-str β MgpstrProcessor (MGP-STR model)
- mllama β MllamaProcessor (Mllama model)
- oneformer β OneFormerProcessor (OneFormer model)
- owlv2 β Owlv2Processor (OWLv2 model)
- owlvit β OwlViTProcessor (OWL-ViT model)
- paligemma β PaliGemmaProcessor (PaliGemma model)
- pix2struct β Pix2StructProcessor (Pix2Struct model)
- pixtral β PixtralProcessor (Pixtral model)
- pop2piano β Pop2PianoProcessor (Pop2Piano model)
- qwen2_audio β Qwen2AudioProcessor (Qwen2Audio model)
- qwen2_vl β Qwen2VLProcessor (Qwen2VL model)
- sam β SamProcessor (SAM model)
- seamless_m4t β SeamlessM4TProcessor (SeamlessM4T model)
- sew β Wav2Vec2Processor (SEW model)
- sew-d β Wav2Vec2Processor (SEW-D model)
- siglip β SiglipProcessor (SigLIP model)
- speech_to_text β Speech2TextProcessor (Speech2Text model)
- speech_to_text_2 β Speech2Text2Processor (Speech2Text2 model)
- speecht5 β SpeechT5Processor (SpeechT5 model)
- trocr β TrOCRProcessor (TrOCR model)
- tvlt β TvltProcessor (TVLT model)
- tvp β TvpProcessor (TVP model)
- udop β UdopProcessor (UDOP model)
- unispeech β Wav2Vec2Processor (UniSpeech model)
- unispeech-sat β Wav2Vec2Processor (UniSpeechSat model)
- video_llava β VideoLlavaProcessor (VideoLlava model)
- vilt β ViltProcessor (ViLT model)
- vipllava β LlavaProcessor (VipLlava model)
- vision-text-dual-encoder β VisionTextDualEncoderProcessor (VisionTextDualEncoder model)
- wav2vec2 β Wav2Vec2Processor (Wav2Vec2 model)
- wav2vec2-bert β Wav2Vec2Processor (Wav2Vec2-BERT model)
- wav2vec2-conformer β Wav2Vec2Processor (Wav2Vec2-Conformer model)
- wavlm β Wav2Vec2Processor (WavLM model)
- whisper β WhisperProcessor (Whisper model)
- xclip β XCLIPProcessor (X-CLIP model)
Passing token=True
is required when you want to use a private model.
Examples:
>>> from transformers import AutoProcessor
>>> # Download processor from huggingface.co and cache.
>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
>>> # If processor files are in a directory (e.g. processor was saved using *save_pretrained('./test/saved_model/')*)
>>> # processor = AutoProcessor.from_pretrained("./test/saved_model/")
register
< source >( config_class processor_class exist_ok = False )
Parameters
- config_class (PretrainedConfig) — The configuration corresponding to the model to register.
- processor_class (
FeatureExtractorMixin
) — The processor to register.
Register a new processor for this class.
Generic model classes
The following auto classes are available for instantiating a base model class without a specific head.
AutoModel
This is a generic model class that will be instantiated as one of the base model classes of the library when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- ASTConfig configuration class: ASTModel (Audio Spectrogram Transformer model)
- AlbertConfig configuration class: AlbertModel (ALBERT model)
- AlignConfig configuration class: AlignModel (ALIGN model)
- AltCLIPConfig configuration class: AltCLIPModel (AltCLIP model)
- AriaConfig configuration class: AriaForConditionalGeneration (Aria model)
- AriaTextConfig configuration class: AriaTextModel (AriaText model)
- AutoformerConfig configuration class: AutoformerModel (Autoformer model)
- BambaConfig configuration class: BambaModel (Bamba model)
- BarkConfig configuration class: BarkModel (Bark model)
- BartConfig configuration class: BartModel (BART model)
- BeitConfig configuration class: BeitModel (BEiT model)
- BertConfig configuration class: BertModel (BERT model)
- BertGenerationConfig configuration class: BertGenerationEncoder (Bert Generation model)
- BigBirdConfig configuration class: BigBirdModel (BigBird model)
- BigBirdPegasusConfig configuration class: BigBirdPegasusModel (BigBird-Pegasus model)
- BioGptConfig configuration class: BioGptModel (BioGpt model)
- BitConfig configuration class: BitModel (BiT model)
- BlenderbotConfig configuration class: BlenderbotModel (Blenderbot model)
- BlenderbotSmallConfig configuration class: BlenderbotSmallModel (BlenderbotSmall model)
- Blip2Config configuration class: Blip2Model (BLIP-2 model)
- BlipConfig configuration class: BlipModel (BLIP model)
- BloomConfig configuration class: BloomModel (BLOOM model)
- BridgeTowerConfig configuration class: BridgeTowerModel (BridgeTower model)
- BrosConfig configuration class: BrosModel (BROS model)
- CLIPConfig configuration class: CLIPModel (CLIP model)
- CLIPSegConfig configuration class: CLIPSegModel (CLIPSeg model)
- CLIPTextConfig configuration class: CLIPTextModel (CLIPTextModel model)
- CLIPVisionConfig configuration class: CLIPVisionModel (CLIPVisionModel model)
- CTRLConfig configuration class: CTRLModel (CTRL model)
- CamembertConfig configuration class: CamembertModel (CamemBERT model)
- CanineConfig configuration class: CanineModel (CANINE model)
- ChameleonConfig configuration class: ChameleonModel (Chameleon model)
- ChineseCLIPConfig configuration class: ChineseCLIPModel (Chinese-CLIP model)
- ChineseCLIPVisionConfig configuration class: ChineseCLIPVisionModel (ChineseCLIPVisionModel model)
- ClapConfig configuration class: ClapModel (CLAP model)
- ClvpConfig configuration class: ClvpModelForConditionalGeneration (CLVP model)
- CodeGenConfig configuration class: CodeGenModel (CodeGen model)
- Cohere2Config configuration class: Cohere2Model (Cohere2 model)
- CohereConfig configuration class: CohereModel (Cohere model)
- ConditionalDetrConfig configuration class: ConditionalDetrModel (Conditional DETR model)
- ConvBertConfig configuration class: ConvBertModel (ConvBERT model)
- ConvNextConfig configuration class: ConvNextModel (ConvNeXT model)
- ConvNextV2Config configuration class: ConvNextV2Model (ConvNeXTV2 model)
- CpmAntConfig configuration class: CpmAntModel (CPM-Ant model)
- CvtConfig configuration class: CvtModel (CvT model)
- DPRConfig configuration class: DPRQuestionEncoder (DPR model)
- DPTConfig configuration class: DPTModel (DPT model)
- DacConfig configuration class: DacModel (DAC model)
- Data2VecAudioConfig configuration class: Data2VecAudioModel (Data2VecAudio model)
- Data2VecTextConfig configuration class: Data2VecTextModel (Data2VecText model)
- Data2VecVisionConfig configuration class: Data2VecVisionModel (Data2VecVision model)
- DbrxConfig configuration class: DbrxModel (DBRX model)
- DebertaConfig configuration class: DebertaModel (DeBERTa model)
- DebertaV2Config configuration class: DebertaV2Model (DeBERTa-v2 model)
- DecisionTransformerConfig configuration class: DecisionTransformerModel (Decision Transformer model)
- DeformableDetrConfig configuration class: DeformableDetrModel (Deformable DETR model)
- DeiTConfig configuration class: DeiTModel (DeiT model)
- DetaConfig configuration class: DetaModel (DETA model)
- DetrConfig configuration class: DetrModel (DETR model)
- DinatConfig configuration class: DinatModel (DiNAT model)
- Dinov2Config configuration class: Dinov2Model (DINOv2 model)
- DistilBertConfig configuration class: DistilBertModel (DistilBERT model)
- DonutSwinConfig configuration class: DonutSwinModel (DonutSwin model)
- EfficientFormerConfig configuration class: EfficientFormerModel (EfficientFormer model)
- EfficientNetConfig configuration class: EfficientNetModel (EfficientNet model)
- ElectraConfig configuration class: ElectraModel (ELECTRA model)
- EncodecConfig configuration class: EncodecModel (EnCodec model)
- ErnieConfig configuration class: ErnieModel (ERNIE model)
- ErnieMConfig configuration class: ErnieMModel (ErnieM model)
- EsmConfig configuration class: EsmModel (ESM model)
- FNetConfig configuration class: FNetModel (FNet model)
- FSMTConfig configuration class: FSMTModel (FairSeq Machine-Translation model)
- FalconConfig configuration class: FalconModel (Falcon model)
- FalconMambaConfig configuration class: FalconMambaModel (FalconMamba model)
- FastSpeech2ConformerConfig configuration class: FastSpeech2ConformerModel (FastSpeech2Conformer model)
- FlaubertConfig configuration class: FlaubertModel (FlauBERT model)
- FlavaConfig configuration class: FlavaModel (FLAVA model)
- FocalNetConfig configuration class: FocalNetModel (FocalNet model)
- FunnelConfig configuration class: FunnelModel or FunnelBaseModel (Funnel Transformer model)
- GLPNConfig configuration class: GLPNModel (GLPN model)
- GPT2Config configuration class: GPT2Model (OpenAI GPT-2 model)
- GPTBigCodeConfig configuration class: GPTBigCodeModel (GPTBigCode model)
- GPTJConfig configuration class: GPTJModel (GPT-J model)
- GPTNeoConfig configuration class: GPTNeoModel (GPT Neo model)
- GPTNeoXConfig configuration class: GPTNeoXModel (GPT NeoX model)
- GPTNeoXJapaneseConfig configuration class: GPTNeoXJapaneseModel (GPT NeoX Japanese model)
- GPTSanJapaneseConfig configuration class: GPTSanJapaneseForConditionalGeneration (GPTSAN-japanese model)
- Gemma2Config configuration class: Gemma2Model (Gemma2 model)
- GemmaConfig configuration class: GemmaModel (Gemma model)
- GitConfig configuration class: GitModel (GIT model)
- GlmConfig configuration class: GlmModel (GLM model)
- GraniteConfig configuration class: GraniteModel (Granite model)
- GraniteMoeConfig configuration class: GraniteMoeModel (GraniteMoeMoe model)
- GraphormerConfig configuration class: GraphormerModel (Graphormer model)
- GroundingDinoConfig configuration class: GroundingDinoModel (Grounding DINO model)
- GroupViTConfig configuration class: GroupViTModel (GroupViT model)
- HieraConfig configuration class: HieraModel (Hiera model)
- HubertConfig configuration class: HubertModel (Hubert model)
- IBertConfig configuration class: IBertModel (I-BERT model)
- IJepaConfig configuration class: IJepaModel (I-JEPA model)
- Idefics2Config configuration class: Idefics2Model (Idefics2 model)
- Idefics3Config configuration class: Idefics3Model (Idefics3 model)
- Idefics3VisionConfig configuration class: Idefics3VisionTransformer (Idefics3VisionTransformer model)
- IdeficsConfig configuration class: IdeficsModel (IDEFICS model)
- ImageGPTConfig configuration class: ImageGPTModel (ImageGPT model)
- InformerConfig configuration class: InformerModel (Informer model)
- JambaConfig configuration class: JambaModel (Jamba model)
- JetMoeConfig configuration class: JetMoeModel (JetMoe model)
- JukeboxConfig configuration class: JukeboxModel (Jukebox model)
- Kosmos2Config configuration class: Kosmos2Model (KOSMOS-2 model)
- LEDConfig configuration class: LEDModel (LED model)
- LayoutLMConfig configuration class: LayoutLMModel (LayoutLM model)
- LayoutLMv2Config configuration class: LayoutLMv2Model (LayoutLMv2 model)
- LayoutLMv3Config configuration class: LayoutLMv3Model (LayoutLMv3 model)
- LevitConfig configuration class: LevitModel (LeViT model)
- LiltConfig configuration class: LiltModel (LiLT model)
- LlamaConfig configuration class: LlamaModel (LLaMA model)
- LongT5Config configuration class: LongT5Model (LongT5 model)
- LongformerConfig configuration class: LongformerModel (Longformer model)
- LukeConfig configuration class: LukeModel (LUKE model)
- LxmertConfig configuration class: LxmertModel (LXMERT model)
- M2M100Config configuration class: M2M100Model (M2M100 model)
- MBartConfig configuration class: MBartModel (mBART model)
- MCTCTConfig configuration class: MCTCTModel (M-CTC-T model)
- MPNetConfig configuration class: MPNetModel (MPNet model)
- MT5Config configuration class: MT5Model (MT5 model)
- Mamba2Config configuration class: Mamba2Model (mamba2 model)
- MambaConfig configuration class: MambaModel (Mamba model)
- MarianConfig configuration class: MarianModel (Marian model)
- MarkupLMConfig configuration class: MarkupLMModel (MarkupLM model)
- Mask2FormerConfig configuration class: Mask2FormerModel (Mask2Former model)
- MaskFormerConfig configuration class: MaskFormerModel (MaskFormer model)
MaskFormerSwinConfig
configuration class:MaskFormerSwinModel
(MaskFormerSwin model)- MegaConfig configuration class: MegaModel (MEGA model)
- MegatronBertConfig configuration class: MegatronBertModel (Megatron-BERT model)
- MgpstrConfig configuration class: MgpstrForSceneTextRecognition (MGP-STR model)
- MimiConfig configuration class: MimiModel (Mimi model)
- MistralConfig configuration class: MistralModel (Mistral model)
- MixtralConfig configuration class: MixtralModel (Mixtral model)
- MobileBertConfig configuration class: MobileBertModel (MobileBERT model)
- MobileNetV1Config configuration class: MobileNetV1Model (MobileNetV1 model)
- MobileNetV2Config configuration class: MobileNetV2Model (MobileNetV2 model)
- MobileViTConfig configuration class: MobileViTModel (MobileViT model)
- MobileViTV2Config configuration class: MobileViTV2Model (MobileViTV2 model)
- ModernBertConfig configuration class: ModernBertModel (ModernBERT model)
- MoshiConfig configuration class: MoshiModel (Moshi model)
- MptConfig configuration class: MptModel (MPT model)
- MraConfig configuration class: MraModel (MRA model)
- MusicgenConfig configuration class: MusicgenModel (MusicGen model)
- MusicgenMelodyConfig configuration class: MusicgenMelodyModel (MusicGen Melody model)
- MvpConfig configuration class: MvpModel (MVP model)
- NatConfig configuration class: NatModel (NAT model)
- NemotronConfig configuration class: NemotronModel (Nemotron model)
- NezhaConfig configuration class: NezhaModel (Nezha model)
- NllbMoeConfig configuration class: NllbMoeModel (NLLB-MOE model)
- NystromformerConfig configuration class: NystromformerModel (Nyströmformer model)
- OPTConfig configuration class: OPTModel (OPT model)
- Olmo2Config configuration class: Olmo2Model (OLMo2 model)
- OlmoConfig configuration class: OlmoModel (OLMo model)
- OlmoeConfig configuration class: OlmoeModel (OLMoE model)
- OmDetTurboConfig configuration class: OmDetTurboForObjectDetection (OmDet-Turbo model)
- OneFormerConfig configuration class: OneFormerModel (OneFormer model)
- OpenAIGPTConfig configuration class: OpenAIGPTModel (OpenAI GPT model)
- OpenLlamaConfig configuration class: OpenLlamaModel (OpenLlama model)
- OwlViTConfig configuration class: OwlViTModel (OWL-ViT model)
- Owlv2Config configuration class: Owlv2Model (OWLv2 model)
- PLBartConfig configuration class: PLBartModel (PLBart model)
- PatchTSMixerConfig configuration class: PatchTSMixerModel (PatchTSMixer model)
- PatchTSTConfig configuration class: PatchTSTModel (PatchTST model)
- PegasusConfig configuration class: PegasusModel (Pegasus model)
- PegasusXConfig configuration class: PegasusXModel (PEGASUS-X model)
- PerceiverConfig configuration class: PerceiverModel (Perceiver model)
- PersimmonConfig configuration class: PersimmonModel (Persimmon model)
- Phi3Config configuration class: Phi3Model (Phi3 model)
- PhiConfig configuration class: PhiModel (Phi model)
- PhimoeConfig configuration class: PhimoeModel (Phimoe model)
- PixtralVisionConfig configuration class: PixtralVisionModel (Pixtral model)
- PoolFormerConfig configuration class: PoolFormerModel (PoolFormer model)
- ProphetNetConfig configuration class: ProphetNetModel (ProphetNet model)
- PvtConfig configuration class: PvtModel (PVT model)
- PvtV2Config configuration class: PvtV2Model (PVTv2 model)
- QDQBertConfig configuration class: QDQBertModel (QDQBert model)
- Qwen2AudioEncoderConfig configuration class:
Qwen2AudioEncoder
(Qwen2AudioEncoder model) - Qwen2Config configuration class: Qwen2Model (Qwen2 model)
- Qwen2MoeConfig configuration class: Qwen2MoeModel (Qwen2MoE model)
- Qwen2VLConfig configuration class: Qwen2VLModel (Qwen2VL model)
- RTDetrConfig configuration class: RTDetrModel (RT-DETR model)
- RecurrentGemmaConfig configuration class: RecurrentGemmaModel (RecurrentGemma model)
- ReformerConfig configuration class: ReformerModel (Reformer model)
- RegNetConfig configuration class: RegNetModel (RegNet model)
- RemBertConfig configuration class: RemBertModel (RemBERT model)
- ResNetConfig configuration class: ResNetModel (ResNet model)
- RetriBertConfig configuration class: RetriBertModel (RetriBERT model)
- RoCBertConfig configuration class: RoCBertModel (RoCBert model)
- RoFormerConfig configuration class: RoFormerModel (RoFormer model)
- RobertaConfig configuration class: RobertaModel (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: RobertaPreLayerNormModel (RoBERTa-PreLayerNorm model)
- RwkvConfig configuration class: RwkvModel (RWKV model)
- SEWConfig configuration class: SEWModel (SEW model)
- SEWDConfig configuration class: SEWDModel (SEW-D model)
- SamConfig configuration class: SamModel (SAM model)
- SeamlessM4TConfig configuration class: SeamlessM4TModel (SeamlessM4T model)
- SeamlessM4Tv2Config configuration class: SeamlessM4Tv2Model (SeamlessM4Tv2 model)
- SegGptConfig configuration class: SegGptModel (SegGPT model)
- SegformerConfig configuration class: SegformerModel (SegFormer model)
- SiglipConfig configuration class: SiglipModel (SigLIP model)
- SiglipVisionConfig configuration class: SiglipVisionModel (SiglipVisionModel model)
- Speech2TextConfig configuration class: Speech2TextModel (Speech2Text model)
- SpeechT5Config configuration class: SpeechT5Model (SpeechT5 model)
- SplinterConfig configuration class: SplinterModel (Splinter model)
- SqueezeBertConfig configuration class: SqueezeBertModel (SqueezeBERT model)
- StableLmConfig configuration class: StableLmModel (StableLm model)
- Starcoder2Config configuration class: Starcoder2Model (Starcoder2 model)
- SwiftFormerConfig configuration class: SwiftFormerModel (SwiftFormer model)
- Swin2SRConfig configuration class: Swin2SRModel (Swin2SR model)
- SwinConfig configuration class: SwinModel (Swin Transformer model)
- Swinv2Config configuration class: Swinv2Model (Swin Transformer V2 model)
- SwitchTransformersConfig configuration class: SwitchTransformersModel (SwitchTransformers model)
- T5Config configuration class: T5Model (T5 model)
- TableTransformerConfig configuration class: TableTransformerModel (Table Transformer model)
- TapasConfig configuration class: TapasModel (TAPAS model)
- TimeSeriesTransformerConfig configuration class: TimeSeriesTransformerModel (Time Series Transformer model)
- TimesformerConfig configuration class: TimesformerModel (TimeSformer model)
- TimmBackboneConfig configuration class: TimmBackbone (TimmBackbone model)
- TimmWrapperConfig configuration class: TimmWrapperModel (TimmWrapperModel model)
- TrajectoryTransformerConfig configuration class: TrajectoryTransformerModel (Trajectory Transformer model)
- TransfoXLConfig configuration class: TransfoXLModel (Transformer-XL model)
- TvltConfig configuration class: TvltModel (TVLT model)
- TvpConfig configuration class: TvpModel (TVP model)
- UMT5Config configuration class: UMT5Model (UMT5 model)
- UdopConfig configuration class: UdopModel (UDOP model)
- UniSpeechConfig configuration class: UniSpeechModel (UniSpeech model)
- UniSpeechSatConfig configuration class: UniSpeechSatModel (UniSpeechSat model)
- UnivNetConfig configuration class: UnivNetModel (UnivNet model)
- VanConfig configuration class: VanModel (VAN model)
- ViTConfig configuration class: ViTModel (ViT model)
- ViTHybridConfig configuration class: ViTHybridModel (ViT Hybrid model)
- ViTMAEConfig configuration class: ViTMAEModel (ViTMAE model)
- ViTMSNConfig configuration class: ViTMSNModel (ViTMSN model)
- VideoMAEConfig configuration class: VideoMAEModel (VideoMAE model)
- ViltConfig configuration class: ViltModel (ViLT model)
- VisionTextDualEncoderConfig configuration class: VisionTextDualEncoderModel (VisionTextDualEncoder model)
- VisualBertConfig configuration class: VisualBertModel (VisualBERT model)
- VitDetConfig configuration class: VitDetModel (VitDet model)
- VitsConfig configuration class: VitsModel (VITS model)
- VivitConfig configuration class: VivitModel (ViViT model)
- Wav2Vec2BertConfig configuration class: Wav2Vec2BertModel (Wav2Vec2-BERT model)
- Wav2Vec2Config configuration class: Wav2Vec2Model (Wav2Vec2 model)
- Wav2Vec2ConformerConfig configuration class: Wav2Vec2ConformerModel (Wav2Vec2-Conformer model)
- WavLMConfig configuration class: WavLMModel (WavLM model)
- WhisperConfig configuration class: WhisperModel (Whisper model)
- XCLIPConfig configuration class: XCLIPModel (X-CLIP model)
- XGLMConfig configuration class: XGLMModel (XGLM model)
- XLMConfig configuration class: XLMModel (XLM model)
- XLMProphetNetConfig configuration class: XLMProphetNetModel (XLM-ProphetNet model)
- XLMRobertaConfig configuration class: XLMRobertaModel (XLM-RoBERTa model)
- XLMRobertaXLConfig configuration class: XLMRobertaXLModel (XLM-RoBERTa-XL model)
- XLNetConfig configuration class: XLNetModel (XLNet model)
- XmodConfig configuration class: XmodModel (X-MOD model)
- YolosConfig configuration class: YolosModel (YOLOS model)
- YosoConfig configuration class: YosoModel (YOSO model)
- ZambaConfig configuration class: ZambaModel (Zamba model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the base model classes of the library from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the base model classes of the library from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β AlbertModel (ALBERT model)
- align β AlignModel (ALIGN model)
- altclip β AltCLIPModel (AltCLIP model)
- aria β AriaForConditionalGeneration (Aria model)
- aria_text β AriaTextModel (AriaText model)
- audio-spectrogram-transformer β ASTModel (Audio Spectrogram Transformer model)
- autoformer β AutoformerModel (Autoformer model)
- bamba β BambaModel (Bamba model)
- bark β BarkModel (Bark model)
- bart β BartModel (BART model)
- beit β BeitModel (BEiT model)
- bert β BertModel (BERT model)
- bert-generation β BertGenerationEncoder (Bert Generation model)
- big_bird β BigBirdModel (BigBird model)
- bigbird_pegasus β BigBirdPegasusModel (BigBird-Pegasus model)
- biogpt β BioGptModel (BioGpt model)
- bit β BitModel (BiT model)
- blenderbot β BlenderbotModel (Blenderbot model)
- blenderbot-small β BlenderbotSmallModel (BlenderbotSmall model)
- blip β BlipModel (BLIP model)
- blip-2 β Blip2Model (BLIP-2 model)
- bloom β BloomModel (BLOOM model)
- bridgetower β BridgeTowerModel (BridgeTower model)
- bros β BrosModel (BROS model)
- camembert β CamembertModel (CamemBERT model)
- canine β CanineModel (CANINE model)
- chameleon β ChameleonModel (Chameleon model)
- chinese_clip β ChineseCLIPModel (Chinese-CLIP model)
- chinese_clip_vision_model β ChineseCLIPVisionModel (ChineseCLIPVisionModel model)
- clap β ClapModel (CLAP model)
- clip β CLIPModel (CLIP model)
- clip_text_model β CLIPTextModel (CLIPTextModel model)
- clip_vision_model β CLIPVisionModel (CLIPVisionModel model)
- clipseg β CLIPSegModel (CLIPSeg model)
- clvp β ClvpModelForConditionalGeneration (CLVP model)
- code_llama β LlamaModel (CodeLlama model)
- codegen β CodeGenModel (CodeGen model)
- cohere β CohereModel (Cohere model)
- cohere2 β Cohere2Model (Cohere2 model)
- conditional_detr β ConditionalDetrModel (Conditional DETR model)
- convbert β ConvBertModel (ConvBERT model)
- convnext β ConvNextModel (ConvNeXT model)
- convnextv2 β ConvNextV2Model (ConvNeXTV2 model)
- cpmant β CpmAntModel (CPM-Ant model)
- ctrl β CTRLModel (CTRL model)
- cvt β CvtModel (CvT model)
- dac β DacModel (DAC model)
- data2vec-audio β Data2VecAudioModel (Data2VecAudio model)
- data2vec-text β Data2VecTextModel (Data2VecText model)
- data2vec-vision β Data2VecVisionModel (Data2VecVision model)
- dbrx β DbrxModel (DBRX model)
- deberta β DebertaModel (DeBERTa model)
- deberta-v2 β DebertaV2Model (DeBERTa-v2 model)
- decision_transformer β DecisionTransformerModel (Decision Transformer model)
- deformable_detr β DeformableDetrModel (Deformable DETR model)
- deit β DeiTModel (DeiT model)
- deta β DetaModel (DETA model)
- detr β DetrModel (DETR model)
- dinat β DinatModel (DiNAT model)
- dinov2 β Dinov2Model (DINOv2 model)
- distilbert β DistilBertModel (DistilBERT model)
- donut-swin β DonutSwinModel (DonutSwin model)
- dpr β DPRQuestionEncoder (DPR model)
- dpt β DPTModel (DPT model)
- efficientformer β EfficientFormerModel (EfficientFormer model)
- efficientnet β EfficientNetModel (EfficientNet model)
- electra β ElectraModel (ELECTRA model)
- encodec β EncodecModel (EnCodec model)
- ernie β ErnieModel (ERNIE model)
- ernie_m β ErnieMModel (ErnieM model)
- esm β EsmModel (ESM model)
- falcon β FalconModel (Falcon model)
- falcon_mamba β FalconMambaModel (FalconMamba model)
- fastspeech2_conformer β FastSpeech2ConformerModel (FastSpeech2Conformer model)
- flaubert β FlaubertModel (FlauBERT model)
- flava β FlavaModel (FLAVA model)
- fnet β FNetModel (FNet model)
- focalnet β FocalNetModel (FocalNet model)
- fsmt β FSMTModel (FairSeq Machine-Translation model)
- funnel β FunnelModel or FunnelBaseModel (Funnel Transformer model)
- gemma β GemmaModel (Gemma model)
- gemma2 β Gemma2Model (Gemma2 model)
- git β GitModel (GIT model)
- glm β GlmModel (GLM model)
- glpn β GLPNModel (GLPN model)
- gpt-sw3 β GPT2Model (GPT-Sw3 model)
- gpt2 β GPT2Model (OpenAI GPT-2 model)
- gpt_bigcode β GPTBigCodeModel (GPTBigCode model)
- gpt_neo β GPTNeoModel (GPT Neo model)
- gpt_neox β GPTNeoXModel (GPT NeoX model)
- gpt_neox_japanese β GPTNeoXJapaneseModel (GPT NeoX Japanese model)
- gptj β GPTJModel (GPT-J model)
- gptsan-japanese β GPTSanJapaneseForConditionalGeneration (GPTSAN-japanese model)
- granite β GraniteModel (Granite model)
- granitemoe β GraniteMoeModel (GraniteMoeMoe model)
- graphormer β GraphormerModel (Graphormer model)
- grounding-dino β GroundingDinoModel (Grounding DINO model)
- groupvit β GroupViTModel (GroupViT model)
- hiera β HieraModel (Hiera model)
- hubert β HubertModel (Hubert model)
- ibert β IBertModel (I-BERT model)
- idefics β IdeficsModel (IDEFICS model)
- idefics2 β Idefics2Model (Idefics2 model)
- idefics3 β Idefics3Model (Idefics3 model)
- idefics3_vision β Idefics3VisionTransformer (Idefics3VisionTransformer model)
- ijepa β IJepaModel (I-JEPA model)
- imagegpt β ImageGPTModel (ImageGPT model)
- informer β InformerModel (Informer model)
- jamba β JambaModel (Jamba model)
- jetmoe β JetMoeModel (JetMoe model)
- jukebox β JukeboxModel (Jukebox model)
- kosmos-2 β Kosmos2Model (KOSMOS-2 model)
- layoutlm β LayoutLMModel (LayoutLM model)
- layoutlmv2 β LayoutLMv2Model (LayoutLMv2 model)
- layoutlmv3 β LayoutLMv3Model (LayoutLMv3 model)
- led β LEDModel (LED model)
- levit β LevitModel (LeViT model)
- lilt β LiltModel (LiLT model)
- llama β LlamaModel (LLaMA model)
- longformer β LongformerModel (Longformer model)
- longt5 β LongT5Model (LongT5 model)
- luke β LukeModel (LUKE model)
- lxmert β LxmertModel (LXMERT model)
- m2m_100 β M2M100Model (M2M100 model)
- mamba β MambaModel (Mamba model)
- mamba2 β Mamba2Model (mamba2 model)
- marian β MarianModel (Marian model)
- markuplm β MarkupLMModel (MarkupLM model)
- mask2former β Mask2FormerModel (Mask2Former model)
- maskformer β MaskFormerModel (MaskFormer model)
- maskformer-swin β
MaskFormerSwinModel
(MaskFormerSwin model) - mbart β MBartModel (mBART model)
- mctct β MCTCTModel (M-CTC-T model)
- mega β MegaModel (MEGA model)
- megatron-bert β MegatronBertModel (Megatron-BERT model)
- mgp-str β MgpstrForSceneTextRecognition (MGP-STR model)
- mimi β MimiModel (Mimi model)
- mistral β MistralModel (Mistral model)
- mixtral β MixtralModel (Mixtral model)
- mobilebert β MobileBertModel (MobileBERT model)
- mobilenet_v1 β MobileNetV1Model (MobileNetV1 model)
- mobilenet_v2 β MobileNetV2Model (MobileNetV2 model)
- mobilevit β MobileViTModel (MobileViT model)
- mobilevitv2 β MobileViTV2Model (MobileViTV2 model)
- modernbert β ModernBertModel (ModernBERT model)
- moshi β MoshiModel (Moshi model)
- mpnet β MPNetModel (MPNet model)
- mpt β MptModel (MPT model)
- mra β MraModel (MRA model)
- mt5 β MT5Model (MT5 model)
- musicgen β MusicgenModel (MusicGen model)
- musicgen_melody β MusicgenMelodyModel (MusicGen Melody model)
- mvp β MvpModel (MVP model)
- nat β NatModel (NAT model)
- nemotron β NemotronModel (Nemotron model)
- nezha β NezhaModel (Nezha model)
- nllb-moe β NllbMoeModel (NLLB-MOE model)
- nystromformer β NystromformerModel (NystrΓΆmformer model)
- olmo β OlmoModel (OLMo model)
- olmo2 β Olmo2Model (OLMo2 model)
- olmoe β OlmoeModel (OLMoE model)
- omdet-turbo β OmDetTurboForObjectDetection (OmDet-Turbo model)
- oneformer β OneFormerModel (OneFormer model)
- open-llama β OpenLlamaModel (OpenLlama model)
- openai-gpt β OpenAIGPTModel (OpenAI GPT model)
- opt β OPTModel (OPT model)
- owlv2 β Owlv2Model (OWLv2 model)
- owlvit β OwlViTModel (OWL-ViT model)
- patchtsmixer β PatchTSMixerModel (PatchTSMixer model)
- patchtst β PatchTSTModel (PatchTST model)
- pegasus β PegasusModel (Pegasus model)
- pegasus_x β PegasusXModel (PEGASUS-X model)
- perceiver β PerceiverModel (Perceiver model)
- persimmon β PersimmonModel (Persimmon model)
- phi β PhiModel (Phi model)
- phi3 β Phi3Model (Phi3 model)
- phimoe β PhimoeModel (Phimoe model)
- pixtral β PixtralVisionModel (Pixtral model)
- plbart β PLBartModel (PLBart model)
- poolformer β PoolFormerModel (PoolFormer model)
- prophetnet β ProphetNetModel (ProphetNet model)
- pvt β PvtModel (PVT model)
- pvt_v2 β PvtV2Model (PVTv2 model)
- qdqbert β QDQBertModel (QDQBert model)
- qwen2 β Qwen2Model (Qwen2 model)
- qwen2_audio_encoder β
Qwen2AudioEncoder
(Qwen2AudioEncoder model) - qwen2_moe β Qwen2MoeModel (Qwen2MoE model)
- qwen2_vl β Qwen2VLModel (Qwen2VL model)
- recurrent_gemma β RecurrentGemmaModel (RecurrentGemma model)
- reformer β ReformerModel (Reformer model)
- regnet β RegNetModel (RegNet model)
- rembert β RemBertModel (RemBERT model)
- resnet β ResNetModel (ResNet model)
- retribert β RetriBertModel (RetriBERT model)
- roberta β RobertaModel (RoBERTa model)
- roberta-prelayernorm β RobertaPreLayerNormModel (RoBERTa-PreLayerNorm model)
- roc_bert β RoCBertModel (RoCBert model)
- roformer β RoFormerModel (RoFormer model)
- rt_detr β RTDetrModel (RT-DETR model)
- rwkv β RwkvModel (RWKV model)
- sam β SamModel (SAM model)
- seamless_m4t β SeamlessM4TModel (SeamlessM4T model)
- seamless_m4t_v2 β SeamlessM4Tv2Model (SeamlessM4Tv2 model)
- segformer β SegformerModel (SegFormer model)
- seggpt β SegGptModel (SegGPT model)
- sew β SEWModel (SEW model)
- sew-d β SEWDModel (SEW-D model)
- siglip β SiglipModel (SigLIP model)
- siglip_vision_model β SiglipVisionModel (SiglipVisionModel model)
- speech_to_text β Speech2TextModel (Speech2Text model)
- speecht5 β SpeechT5Model (SpeechT5 model)
- splinter β SplinterModel (Splinter model)
- squeezebert β SqueezeBertModel (SqueezeBERT model)
- stablelm β StableLmModel (StableLm model)
- starcoder2 β Starcoder2Model (Starcoder2 model)
- swiftformer β SwiftFormerModel (SwiftFormer model)
- swin β SwinModel (Swin Transformer model)
- swin2sr β Swin2SRModel (Swin2SR model)
- swinv2 β Swinv2Model (Swin Transformer V2 model)
- switch_transformers β SwitchTransformersModel (SwitchTransformers model)
- t5 β T5Model (T5 model)
- table-transformer β TableTransformerModel (Table Transformer model)
- tapas β TapasModel (TAPAS model)
- time_series_transformer β TimeSeriesTransformerModel (Time Series Transformer model)
- timesformer β TimesformerModel (TimeSformer model)
- timm_backbone β TimmBackbone (TimmBackbone model)
- timm_wrapper β TimmWrapperModel (TimmWrapperModel model)
- trajectory_transformer β TrajectoryTransformerModel (Trajectory Transformer model)
- transfo-xl β TransfoXLModel (Transformer-XL model)
- tvlt β TvltModel (TVLT model)
- tvp β TvpModel (TVP model)
- udop β UdopModel (UDOP model)
- umt5 β UMT5Model (UMT5 model)
- unispeech β UniSpeechModel (UniSpeech model)
- unispeech-sat β UniSpeechSatModel (UniSpeechSat model)
- univnet β UnivNetModel (UnivNet model)
- van β VanModel (VAN model)
- videomae β VideoMAEModel (VideoMAE model)
- vilt β ViltModel (ViLT model)
- vision-text-dual-encoder β VisionTextDualEncoderModel (VisionTextDualEncoder model)
- visual_bert β VisualBertModel (VisualBERT model)
- vit β ViTModel (ViT model)
- vit_hybrid β ViTHybridModel (ViT Hybrid model)
- vit_mae β ViTMAEModel (ViTMAE model)
- vit_msn β ViTMSNModel (ViTMSN model)
- vitdet β VitDetModel (VitDet model)
- vits β VitsModel (VITS model)
- vivit β VivitModel (ViViT model)
- wav2vec2 β Wav2Vec2Model (Wav2Vec2 model)
- wav2vec2-bert β Wav2Vec2BertModel (Wav2Vec2-BERT model)
- wav2vec2-conformer β Wav2Vec2ConformerModel (Wav2Vec2-Conformer model)
- wavlm β WavLMModel (WavLM model)
- whisper β WhisperModel (Whisper model)
- xclip β XCLIPModel (X-CLIP model)
- xglm β XGLMModel (XGLM model)
- xlm β XLMModel (XLM model)
- xlm-prophetnet β XLMProphetNetModel (XLM-ProphetNet model)
- xlm-roberta β XLMRobertaModel (XLM-RoBERTa model)
- xlm-roberta-xl β XLMRobertaXLModel (XLM-RoBERTa-XL model)
- xlnet β XLNetModel (XLNet model)
- xmod β XmodModel (X-MOD model)
- yolos β YolosModel (YOLOS model)
- yoso β YosoModel (YOSO model)
- zamba β ZambaModel (Zamba model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModel
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModel.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModel.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModel.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModel
This is a generic model class that will be instantiated as one of the base model classes of the library when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: TFAlbertModel (ALBERT model)
- BartConfig configuration class: TFBartModel (BART model)
- BertConfig configuration class: TFBertModel (BERT model)
- BlenderbotConfig configuration class: TFBlenderbotModel (Blenderbot model)
- BlenderbotSmallConfig configuration class: TFBlenderbotSmallModel (BlenderbotSmall model)
- BlipConfig configuration class: TFBlipModel (BLIP model)
- CLIPConfig configuration class: TFCLIPModel (CLIP model)
- CTRLConfig configuration class: TFCTRLModel (CTRL model)
- CamembertConfig configuration class: TFCamembertModel (CamemBERT model)
- ConvBertConfig configuration class: TFConvBertModel (ConvBERT model)
- ConvNextConfig configuration class: TFConvNextModel (ConvNeXT model)
- ConvNextV2Config configuration class: TFConvNextV2Model (ConvNeXTV2 model)
- CvtConfig configuration class: TFCvtModel (CvT model)
- DPRConfig configuration class: TFDPRQuestionEncoder (DPR model)
- Data2VecVisionConfig configuration class: TFData2VecVisionModel (Data2VecVision model)
- DebertaConfig configuration class: TFDebertaModel (DeBERTa model)
- DebertaV2Config configuration class: TFDebertaV2Model (DeBERTa-v2 model)
- DeiTConfig configuration class: TFDeiTModel (DeiT model)
- DistilBertConfig configuration class: TFDistilBertModel (DistilBERT model)
- EfficientFormerConfig configuration class: TFEfficientFormerModel (EfficientFormer model)
- ElectraConfig configuration class: TFElectraModel (ELECTRA model)
- EsmConfig configuration class: TFEsmModel (ESM model)
- FlaubertConfig configuration class: TFFlaubertModel (FlauBERT model)
- FunnelConfig configuration class: TFFunnelModel or TFFunnelBaseModel (Funnel Transformer model)
- GPT2Config configuration class: TFGPT2Model (OpenAI GPT-2 model)
- GPTJConfig configuration class: TFGPTJModel (GPT-J model)
- GroupViTConfig configuration class: TFGroupViTModel (GroupViT model)
- HubertConfig configuration class: TFHubertModel (Hubert model)
- IdeficsConfig configuration class: TFIdeficsModel (IDEFICS model)
- LEDConfig configuration class: TFLEDModel (LED model)
- LayoutLMConfig configuration class: TFLayoutLMModel (LayoutLM model)
- LayoutLMv3Config configuration class: TFLayoutLMv3Model (LayoutLMv3 model)
- LongformerConfig configuration class: TFLongformerModel (Longformer model)
- LxmertConfig configuration class: TFLxmertModel (LXMERT model)
- MBartConfig configuration class: TFMBartModel (mBART model)
- MPNetConfig configuration class: TFMPNetModel (MPNet model)
- MT5Config configuration class: TFMT5Model (MT5 model)
- MarianConfig configuration class: TFMarianModel (Marian model)
- MistralConfig configuration class: TFMistralModel (Mistral model)
- MobileBertConfig configuration class: TFMobileBertModel (MobileBERT model)
- MobileViTConfig configuration class: TFMobileViTModel (MobileViT model)
- OPTConfig configuration class: TFOPTModel (OPT model)
- OpenAIGPTConfig configuration class: TFOpenAIGPTModel (OpenAI GPT model)
- PegasusConfig configuration class: TFPegasusModel (Pegasus model)
- RegNetConfig configuration class: TFRegNetModel (RegNet model)
- RemBertConfig configuration class: TFRemBertModel (RemBERT model)
- ResNetConfig configuration class: TFResNetModel (ResNet model)
- RoFormerConfig configuration class: TFRoFormerModel (RoFormer model)
- RobertaConfig configuration class: TFRobertaModel (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: TFRobertaPreLayerNormModel (RoBERTa-PreLayerNorm model)
- SamConfig configuration class: TFSamModel (SAM model)
- SegformerConfig configuration class: TFSegformerModel (SegFormer model)
- Speech2TextConfig configuration class: TFSpeech2TextModel (Speech2Text model)
- SwiftFormerConfig configuration class: TFSwiftFormerModel (SwiftFormer model)
- SwinConfig configuration class: TFSwinModel (Swin Transformer model)
- T5Config configuration class: TFT5Model (T5 model)
- TapasConfig configuration class: TFTapasModel (TAPAS model)
- TransfoXLConfig configuration class: TFTransfoXLModel (Transformer-XL model)
- ViTConfig configuration class: TFViTModel (ViT model)
- ViTMAEConfig configuration class: TFViTMAEModel (ViTMAE model)
- VisionTextDualEncoderConfig configuration class: TFVisionTextDualEncoderModel (VisionTextDualEncoder model)
- Wav2Vec2Config configuration class: TFWav2Vec2Model (Wav2Vec2 model)
- WhisperConfig configuration class: TFWhisperModel (Whisper model)
- XGLMConfig configuration class: TFXGLMModel (XGLM model)
- XLMConfig configuration class: TFXLMModel (XLM model)
- XLMRobertaConfig configuration class: TFXLMRobertaModel (XLM-RoBERTa model)
- XLNetConfig configuration class: TFXLNetModel (XLNet model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the base model classes of the library from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the base model classes of the library from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β TFAlbertModel (ALBERT model)
- bart β TFBartModel (BART model)
- bert β TFBertModel (BERT model)
- blenderbot β TFBlenderbotModel (Blenderbot model)
- blenderbot-small β TFBlenderbotSmallModel (BlenderbotSmall model)
- blip β TFBlipModel (BLIP model)
- camembert β TFCamembertModel (CamemBERT model)
- clip β TFCLIPModel (CLIP model)
- convbert β TFConvBertModel (ConvBERT model)
- convnext β TFConvNextModel (ConvNeXT model)
- convnextv2 β TFConvNextV2Model (ConvNeXTV2 model)
- ctrl β TFCTRLModel (CTRL model)
- cvt β TFCvtModel (CvT model)
- data2vec-vision β TFData2VecVisionModel (Data2VecVision model)
- deberta β TFDebertaModel (DeBERTa model)
- deberta-v2 β TFDebertaV2Model (DeBERTa-v2 model)
- deit β TFDeiTModel (DeiT model)
- distilbert β TFDistilBertModel (DistilBERT model)
- dpr β TFDPRQuestionEncoder (DPR model)
- efficientformer β TFEfficientFormerModel (EfficientFormer model)
- electra β TFElectraModel (ELECTRA model)
- esm β TFEsmModel (ESM model)
- flaubert β TFFlaubertModel (FlauBERT model)
- funnel β TFFunnelModel or TFFunnelBaseModel (Funnel Transformer model)
- gpt-sw3 β TFGPT2Model (GPT-Sw3 model)
- gpt2 β TFGPT2Model (OpenAI GPT-2 model)
- gptj β TFGPTJModel (GPT-J model)
- groupvit β TFGroupViTModel (GroupViT model)
- hubert β TFHubertModel (Hubert model)
- idefics β TFIdeficsModel (IDEFICS model)
- layoutlm β TFLayoutLMModel (LayoutLM model)
- layoutlmv3 β TFLayoutLMv3Model (LayoutLMv3 model)
- led β TFLEDModel (LED model)
- longformer β TFLongformerModel (Longformer model)
- lxmert β TFLxmertModel (LXMERT model)
- marian β TFMarianModel (Marian model)
- mbart β TFMBartModel (mBART model)
- mistral β TFMistralModel (Mistral model)
- mobilebert β TFMobileBertModel (MobileBERT model)
- mobilevit β TFMobileViTModel (MobileViT model)
- mpnet β TFMPNetModel (MPNet model)
- mt5 β TFMT5Model (MT5 model)
- openai-gpt β TFOpenAIGPTModel (OpenAI GPT model)
- opt β TFOPTModel (OPT model)
- pegasus β TFPegasusModel (Pegasus model)
- regnet β TFRegNetModel (RegNet model)
- rembert β TFRemBertModel (RemBERT model)
- resnet β TFResNetModel (ResNet model)
- roberta β TFRobertaModel (RoBERTa model)
- roberta-prelayernorm β TFRobertaPreLayerNormModel (RoBERTa-PreLayerNorm model)
- roformer β TFRoFormerModel (RoFormer model)
- sam β TFSamModel (SAM model)
- segformer β TFSegformerModel (SegFormer model)
- speech_to_text β TFSpeech2TextModel (Speech2Text model)
- swiftformer β TFSwiftFormerModel (SwiftFormer model)
- swin β TFSwinModel (Swin Transformer model)
- t5 β TFT5Model (T5 model)
- tapas β TFTapasModel (TAPAS model)
- transfo-xl β TFTransfoXLModel (Transformer-XL model)
- vision-text-dual-encoder β TFVisionTextDualEncoderModel (VisionTextDualEncoder model)
- vit β TFViTModel (ViT model)
- vit_mae β TFViTMAEModel (ViTMAE model)
- wav2vec2 β TFWav2Vec2Model (Wav2Vec2 model)
- whisper β TFWhisperModel (Whisper model)
- xglm β TFXGLMModel (XGLM model)
- xlm β TFXLMModel (XLM model)
- xlm-roberta β TFXLMRobertaModel (XLM-RoBERTa model)
- xlnet β TFXLNetModel (XLNet model)
Examples:
>>> from transformers import AutoConfig, TFAutoModel
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModel.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModel.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModel.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModel
This is a generic model class that will be instantiated as one of the base model classes of the library when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: FlaxAlbertModel (ALBERT model)
- BartConfig configuration class: FlaxBartModel (BART model)
- BeitConfig configuration class: FlaxBeitModel (BEiT model)
- BertConfig configuration class: FlaxBertModel (BERT model)
- BigBirdConfig configuration class: FlaxBigBirdModel (BigBird model)
- BlenderbotConfig configuration class: FlaxBlenderbotModel (Blenderbot model)
- BlenderbotSmallConfig configuration class: FlaxBlenderbotSmallModel (BlenderbotSmall model)
- BloomConfig configuration class: FlaxBloomModel (BLOOM model)
- CLIPConfig configuration class: FlaxCLIPModel (CLIP model)
- Dinov2Config configuration class: FlaxDinov2Model (DINOv2 model)
- DistilBertConfig configuration class: FlaxDistilBertModel (DistilBERT model)
- ElectraConfig configuration class: FlaxElectraModel (ELECTRA model)
- GPT2Config configuration class: FlaxGPT2Model (OpenAI GPT-2 model)
- GPTJConfig configuration class: FlaxGPTJModel (GPT-J model)
- GPTNeoConfig configuration class: FlaxGPTNeoModel (GPT Neo model)
- GemmaConfig configuration class: FlaxGemmaModel (Gemma model)
- LlamaConfig configuration class: FlaxLlamaModel (LLaMA model)
- LongT5Config configuration class: FlaxLongT5Model (LongT5 model)
- MBartConfig configuration class: FlaxMBartModel (mBART model)
- MT5Config configuration class: FlaxMT5Model (MT5 model)
- MarianConfig configuration class: FlaxMarianModel (Marian model)
- MistralConfig configuration class: FlaxMistralModel (Mistral model)
- OPTConfig configuration class: FlaxOPTModel (OPT model)
- PegasusConfig configuration class: FlaxPegasusModel (Pegasus model)
- RegNetConfig configuration class: FlaxRegNetModel (RegNet model)
- ResNetConfig configuration class: FlaxResNetModel (ResNet model)
- RoFormerConfig configuration class: FlaxRoFormerModel (RoFormer model)
- RobertaConfig configuration class: FlaxRobertaModel (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: FlaxRobertaPreLayerNormModel (RoBERTa-PreLayerNorm model)
- T5Config configuration class: FlaxT5Model (T5 model)
- ViTConfig configuration class: FlaxViTModel (ViT model)
- VisionTextDualEncoderConfig configuration class: FlaxVisionTextDualEncoderModel (VisionTextDualEncoder model)
- Wav2Vec2Config configuration class: FlaxWav2Vec2Model (Wav2Vec2 model)
- WhisperConfig configuration class: FlaxWhisperModel (Whisper model)
- XGLMConfig configuration class: FlaxXGLMModel (XGLM model)
- XLMRobertaConfig configuration class: FlaxXLMRobertaModel (XLM-RoBERTa model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the base model classes of the library from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the base model classes of the library from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β FlaxAlbertModel (ALBERT model)
- bart β FlaxBartModel (BART model)
- beit β FlaxBeitModel (BEiT model)
- bert β FlaxBertModel (BERT model)
- big_bird β FlaxBigBirdModel (BigBird model)
- blenderbot β FlaxBlenderbotModel (Blenderbot model)
- blenderbot-small β FlaxBlenderbotSmallModel (BlenderbotSmall model)
- bloom β FlaxBloomModel (BLOOM model)
- clip β FlaxCLIPModel (CLIP model)
- dinov2 β FlaxDinov2Model (DINOv2 model)
- distilbert β FlaxDistilBertModel (DistilBERT model)
- electra β FlaxElectraModel (ELECTRA model)
- gemma β FlaxGemmaModel (Gemma model)
- gpt-sw3 β FlaxGPT2Model (GPT-Sw3 model)
- gpt2 β FlaxGPT2Model (OpenAI GPT-2 model)
- gpt_neo β FlaxGPTNeoModel (GPT Neo model)
- gptj β FlaxGPTJModel (GPT-J model)
- llama β FlaxLlamaModel (LLaMA model)
- longt5 β FlaxLongT5Model (LongT5 model)
- marian β FlaxMarianModel (Marian model)
- mbart β FlaxMBartModel (mBART model)
- mistral β FlaxMistralModel (Mistral model)
- mt5 β FlaxMT5Model (MT5 model)
- opt β FlaxOPTModel (OPT model)
- pegasus β FlaxPegasusModel (Pegasus model)
- regnet β FlaxRegNetModel (RegNet model)
- resnet β FlaxResNetModel (ResNet model)
- roberta β FlaxRobertaModel (RoBERTa model)
- roberta-prelayernorm β FlaxRobertaPreLayerNormModel (RoBERTa-PreLayerNorm model)
- roformer β FlaxRoFormerModel (RoFormer model)
- t5 β FlaxT5Model (T5 model)
- vision-text-dual-encoder β FlaxVisionTextDualEncoderModel (VisionTextDualEncoder model)
- vit β FlaxViTModel (ViT model)
- wav2vec2 β FlaxWav2Vec2Model (Wav2Vec2 model)
- whisper β FlaxWhisperModel (Whisper model)
- xglm β FlaxXGLMModel (XGLM model)
- xlm-roberta β FlaxXLMRobertaModel (XLM-RoBERTa model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModel
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModel.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModel.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModel.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
Generic pretraining classes
The following auto classes are available for instantiating a model with a pretraining head.
AutoModelForPreTraining
This is a generic model class that will be instantiated as one of the model classes of the library (with a pretraining head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: AlbertForPreTraining (ALBERT model)
- BartConfig configuration class: BartForConditionalGeneration (BART model)
- BertConfig configuration class: BertForPreTraining (BERT model)
- BigBirdConfig configuration class: BigBirdForPreTraining (BigBird model)
- BloomConfig configuration class: BloomForCausalLM (BLOOM model)
- CTRLConfig configuration class: CTRLLMHeadModel (CTRL model)
- CamembertConfig configuration class: CamembertForMaskedLM (CamemBERT model)
- ColPaliConfig configuration class: ColPaliForRetrieval (ColPali model)
- Data2VecTextConfig configuration class: Data2VecTextForMaskedLM (Data2VecText model)
- DebertaConfig configuration class: DebertaForMaskedLM (DeBERTa model)
- DebertaV2Config configuration class: DebertaV2ForMaskedLM (DeBERTa-v2 model)
- DistilBertConfig configuration class: DistilBertForMaskedLM (DistilBERT model)
- ElectraConfig configuration class: ElectraForPreTraining (ELECTRA model)
- ErnieConfig configuration class: ErnieForPreTraining (ERNIE model)
- FNetConfig configuration class: FNetForPreTraining (FNet model)
- FSMTConfig configuration class: FSMTForConditionalGeneration (FairSeq Machine-Translation model)
- FalconMambaConfig configuration class: FalconMambaForCausalLM (FalconMamba model)
- FlaubertConfig configuration class: FlaubertWithLMHeadModel (FlauBERT model)
- FlavaConfig configuration class: FlavaForPreTraining (FLAVA model)
- FunnelConfig configuration class: FunnelForPreTraining (Funnel Transformer model)
- GPT2Config configuration class: GPT2LMHeadModel (OpenAI GPT-2 model)
- GPTBigCodeConfig configuration class: GPTBigCodeForCausalLM (GPTBigCode model)
- GPTSanJapaneseConfig configuration class: GPTSanJapaneseForConditionalGeneration (GPTSAN-japanese model)
- HieraConfig configuration class: HieraForPreTraining (Hiera model)
- IBertConfig configuration class: IBertForMaskedLM (I-BERT model)
- Idefics2Config configuration class: Idefics2ForConditionalGeneration (Idefics2 model)
- Idefics3Config configuration class: Idefics3ForConditionalGeneration (Idefics3 model)
- IdeficsConfig configuration class: IdeficsForVisionText2Text (IDEFICS model)
- LayoutLMConfig configuration class: LayoutLMForMaskedLM (LayoutLM model)
- LlavaConfig configuration class: LlavaForConditionalGeneration (LLaVa model)
- LlavaNextConfig configuration class: LlavaNextForConditionalGeneration (LLaVA-NeXT model)
- LlavaNextVideoConfig configuration class: LlavaNextVideoForConditionalGeneration (LLaVa-NeXT-Video model)
- LlavaOnevisionConfig configuration class: LlavaOnevisionForConditionalGeneration (LLaVA-Onevision model)
- LongformerConfig configuration class: LongformerForMaskedLM (Longformer model)
- LukeConfig configuration class: LukeForMaskedLM (LUKE model)
- LxmertConfig configuration class: LxmertForPreTraining (LXMERT model)
- MPNetConfig configuration class: MPNetForMaskedLM (MPNet model)
- Mamba2Config configuration class: Mamba2ForCausalLM (mamba2 model)
- MambaConfig configuration class: MambaForCausalLM (Mamba model)
- MegaConfig configuration class: MegaForMaskedLM (MEGA model)
- MegatronBertConfig configuration class: MegatronBertForPreTraining (Megatron-BERT model)
- MllamaConfig configuration class: MllamaForConditionalGeneration (Mllama model)
- MobileBertConfig configuration class: MobileBertForPreTraining (MobileBERT model)
- MptConfig configuration class: MptForCausalLM (MPT model)
- MraConfig configuration class: MraForMaskedLM (MRA model)
- MvpConfig configuration class: MvpForConditionalGeneration (MVP model)
- NezhaConfig configuration class: NezhaForPreTraining (Nezha model)
- NllbMoeConfig configuration class: NllbMoeForConditionalGeneration (NLLB-MOE model)
- OpenAIGPTConfig configuration class: OpenAIGPTLMHeadModel (OpenAI GPT model)
- PaliGemmaConfig configuration class: PaliGemmaForConditionalGeneration (PaliGemma model)
- Qwen2AudioConfig configuration class: Qwen2AudioForConditionalGeneration (Qwen2Audio model)
- RetriBertConfig configuration class: RetriBertModel (RetriBERT model)
- RoCBertConfig configuration class: RoCBertForPreTraining (RoCBert model)
- RobertaConfig configuration class: RobertaForMaskedLM (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: RobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- RwkvConfig configuration class: RwkvForCausalLM (RWKV model)
- SplinterConfig configuration class: SplinterForPreTraining (Splinter model)
- SqueezeBertConfig configuration class: SqueezeBertForMaskedLM (SqueezeBERT model)
- SwitchTransformersConfig configuration class: SwitchTransformersForConditionalGeneration (SwitchTransformers model)
- T5Config configuration class: T5ForConditionalGeneration (T5 model)
- TapasConfig configuration class: TapasForMaskedLM (TAPAS model)
- TransfoXLConfig configuration class: TransfoXLLMHeadModel (Transformer-XL model)
- TvltConfig configuration class: TvltForPreTraining (TVLT model)
- UniSpeechConfig configuration class: UniSpeechForPreTraining (UniSpeech model)
- UniSpeechSatConfig configuration class: UniSpeechSatForPreTraining (UniSpeechSat model)
- ViTMAEConfig configuration class: ViTMAEForPreTraining (ViTMAE model)
- VideoLlavaConfig configuration class: VideoLlavaForConditionalGeneration (VideoLlava model)
- VideoMAEConfig configuration class: VideoMAEForPreTraining (VideoMAE model)
- VipLlavaConfig configuration class: VipLlavaForConditionalGeneration (VipLlava model)
- VisualBertConfig configuration class: VisualBertForPreTraining (VisualBERT model)
- Wav2Vec2Config configuration class: Wav2Vec2ForPreTraining (Wav2Vec2 model)
- Wav2Vec2ConformerConfig configuration class: Wav2Vec2ConformerForPreTraining (Wav2Vec2-Conformer model)
- XLMConfig configuration class: XLMWithLMHeadModel (XLM model)
- XLMRobertaConfig configuration class: XLMRobertaForMaskedLM (XLM-RoBERTa model)
- XLMRobertaXLConfig configuration class: XLMRobertaXLForMaskedLM (XLM-RoBERTa-XL model)
- XLNetConfig configuration class: XLNetLMHeadModel (XLNet model)
- XmodConfig configuration class: XmodForMaskedLM (X-MOD model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a pretraining head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a pretraining head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β AlbertForPreTraining (ALBERT model)
- bart β BartForConditionalGeneration (BART model)
- bert β BertForPreTraining (BERT model)
- big_bird β BigBirdForPreTraining (BigBird model)
- bloom β BloomForCausalLM (BLOOM model)
- camembert β CamembertForMaskedLM (CamemBERT model)
- colpali β ColPaliForRetrieval (ColPali model)
- ctrl β CTRLLMHeadModel (CTRL model)
- data2vec-text β Data2VecTextForMaskedLM (Data2VecText model)
- deberta β DebertaForMaskedLM (DeBERTa model)
- deberta-v2 β DebertaV2ForMaskedLM (DeBERTa-v2 model)
- distilbert β DistilBertForMaskedLM (DistilBERT model)
- electra β ElectraForPreTraining (ELECTRA model)
- ernie β ErnieForPreTraining (ERNIE model)
- falcon_mamba β FalconMambaForCausalLM (FalconMamba model)
- flaubert β FlaubertWithLMHeadModel (FlauBERT model)
- flava β FlavaForPreTraining (FLAVA model)
- fnet β FNetForPreTraining (FNet model)
- fsmt β FSMTForConditionalGeneration (FairSeq Machine-Translation model)
- funnel β FunnelForPreTraining (Funnel Transformer model)
- gpt-sw3 β GPT2LMHeadModel (GPT-Sw3 model)
- gpt2 β GPT2LMHeadModel (OpenAI GPT-2 model)
- gpt_bigcode β GPTBigCodeForCausalLM (GPTBigCode model)
- gptsan-japanese β GPTSanJapaneseForConditionalGeneration (GPTSAN-japanese model)
- hiera β HieraForPreTraining (Hiera model)
- ibert β IBertForMaskedLM (I-BERT model)
- idefics β IdeficsForVisionText2Text (IDEFICS model)
- idefics2 β Idefics2ForConditionalGeneration (Idefics2 model)
- idefics3 β Idefics3ForConditionalGeneration (Idefics3 model)
- layoutlm β LayoutLMForMaskedLM (LayoutLM model)
- llava β LlavaForConditionalGeneration (LLaVa model)
- llava_next β LlavaNextForConditionalGeneration (LLaVA-NeXT model)
- llava_next_video β LlavaNextVideoForConditionalGeneration (LLaVa-NeXT-Video model)
- llava_onevision β LlavaOnevisionForConditionalGeneration (LLaVA-Onevision model)
- longformer β LongformerForMaskedLM (Longformer model)
- luke β LukeForMaskedLM (LUKE model)
- lxmert β LxmertForPreTraining (LXMERT model)
- mamba β MambaForCausalLM (Mamba model)
- mamba2 β Mamba2ForCausalLM (mamba2 model)
- mega β MegaForMaskedLM (MEGA model)
- megatron-bert β MegatronBertForPreTraining (Megatron-BERT model)
- mllama β MllamaForConditionalGeneration (Mllama model)
- mobilebert β MobileBertForPreTraining (MobileBERT model)
- mpnet β MPNetForMaskedLM (MPNet model)
- mpt β MptForCausalLM (MPT model)
- mra β MraForMaskedLM (MRA model)
- mvp β MvpForConditionalGeneration (MVP model)
- nezha β NezhaForPreTraining (Nezha model)
- nllb-moe β NllbMoeForConditionalGeneration (NLLB-MOE model)
- openai-gpt β OpenAIGPTLMHeadModel (OpenAI GPT model)
- paligemma β PaliGemmaForConditionalGeneration (PaliGemma model)
- qwen2_audio β Qwen2AudioForConditionalGeneration (Qwen2Audio model)
- retribert β RetriBertModel (RetriBERT model)
- roberta β RobertaForMaskedLM (RoBERTa model)
- roberta-prelayernorm β RobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- roc_bert β RoCBertForPreTraining (RoCBert model)
- rwkv β RwkvForCausalLM (RWKV model)
- splinter β SplinterForPreTraining (Splinter model)
- squeezebert β SqueezeBertForMaskedLM (SqueezeBERT model)
- switch_transformers β SwitchTransformersForConditionalGeneration (SwitchTransformers model)
- t5 β T5ForConditionalGeneration (T5 model)
- tapas β TapasForMaskedLM (TAPAS model)
- transfo-xl β TransfoXLLMHeadModel (Transformer-XL model)
- tvlt β TvltForPreTraining (TVLT model)
- unispeech β UniSpeechForPreTraining (UniSpeech model)
- unispeech-sat β UniSpeechSatForPreTraining (UniSpeechSat model)
- video_llava β VideoLlavaForConditionalGeneration (VideoLlava model)
- videomae β VideoMAEForPreTraining (VideoMAE model)
- vipllava β VipLlavaForConditionalGeneration (VipLlava model)
- visual_bert β VisualBertForPreTraining (VisualBERT model)
- vit_mae β ViTMAEForPreTraining (ViTMAE model)
- wav2vec2 β Wav2Vec2ForPreTraining (Wav2Vec2 model)
- wav2vec2-conformer β Wav2Vec2ConformerForPreTraining (Wav2Vec2-Conformer model)
- xlm β XLMWithLMHeadModel (XLM model)
- xlm-roberta β XLMRobertaForMaskedLM (XLM-RoBERTa model)
- xlm-roberta-xl β XLMRobertaXLForMaskedLM (XLM-RoBERTa-XL model)
- xlnet β XLNetLMHeadModel (XLNet model)
- xmod β XmodForMaskedLM (X-MOD model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForPreTraining
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForPreTraining.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForPreTraining.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForPreTraining.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForPreTraining
This is a generic model class that will be instantiated as one of the model classes of the library (with a pretraining head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: TFAlbertForPreTraining (ALBERT model)
- BartConfig configuration class: TFBartForConditionalGeneration (BART model)
- BertConfig configuration class: TFBertForPreTraining (BERT model)
- CTRLConfig configuration class: TFCTRLLMHeadModel (CTRL model)
- CamembertConfig configuration class: TFCamembertForMaskedLM (CamemBERT model)
- DistilBertConfig configuration class: TFDistilBertForMaskedLM (DistilBERT model)
- ElectraConfig configuration class: TFElectraForPreTraining (ELECTRA model)
- FlaubertConfig configuration class: TFFlaubertWithLMHeadModel (FlauBERT model)
- FunnelConfig configuration class: TFFunnelForPreTraining (Funnel Transformer model)
- GPT2Config configuration class: TFGPT2LMHeadModel (OpenAI GPT-2 model)
- IdeficsConfig configuration class: TFIdeficsForVisionText2Text (IDEFICS model)
- LayoutLMConfig configuration class: TFLayoutLMForMaskedLM (LayoutLM model)
- LxmertConfig configuration class: TFLxmertForPreTraining (LXMERT model)
- MPNetConfig configuration class: TFMPNetForMaskedLM (MPNet model)
- MobileBertConfig configuration class: TFMobileBertForPreTraining (MobileBERT model)
- OpenAIGPTConfig configuration class: TFOpenAIGPTLMHeadModel (OpenAI GPT model)
- RobertaConfig configuration class: TFRobertaForMaskedLM (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: TFRobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- T5Config configuration class: TFT5ForConditionalGeneration (T5 model)
- TapasConfig configuration class: TFTapasForMaskedLM (TAPAS model)
- TransfoXLConfig configuration class: TFTransfoXLLMHeadModel (Transformer-XL model)
- ViTMAEConfig configuration class: TFViTMAEForPreTraining (ViTMAE model)
- XLMConfig configuration class: TFXLMWithLMHeadModel (XLM model)
- XLMRobertaConfig configuration class: TFXLMRobertaForMaskedLM (XLM-RoBERTa model)
- XLNetConfig configuration class: TFXLNetLMHeadModel (XLNet model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a pretraining head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a pretraining head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β TFAlbertForPreTraining (ALBERT model)
- bart β TFBartForConditionalGeneration (BART model)
- bert β TFBertForPreTraining (BERT model)
- camembert β TFCamembertForMaskedLM (CamemBERT model)
- ctrl β TFCTRLLMHeadModel (CTRL model)
- distilbert β TFDistilBertForMaskedLM (DistilBERT model)
- electra β TFElectraForPreTraining (ELECTRA model)
- flaubert β TFFlaubertWithLMHeadModel (FlauBERT model)
- funnel β TFFunnelForPreTraining (Funnel Transformer model)
- gpt-sw3 β TFGPT2LMHeadModel (GPT-Sw3 model)
- gpt2 β TFGPT2LMHeadModel (OpenAI GPT-2 model)
- idefics β TFIdeficsForVisionText2Text (IDEFICS model)
- layoutlm β TFLayoutLMForMaskedLM (LayoutLM model)
- lxmert β TFLxmertForPreTraining (LXMERT model)
- mobilebert β TFMobileBertForPreTraining (MobileBERT model)
- mpnet β TFMPNetForMaskedLM (MPNet model)
- openai-gpt β TFOpenAIGPTLMHeadModel (OpenAI GPT model)
- roberta β TFRobertaForMaskedLM (RoBERTa model)
- roberta-prelayernorm β TFRobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- t5 β TFT5ForConditionalGeneration (T5 model)
- tapas β TFTapasForMaskedLM (TAPAS model)
- transfo-xl β TFTransfoXLLMHeadModel (Transformer-XL model)
- vit_mae β TFViTMAEForPreTraining (ViTMAE model)
- xlm β TFXLMWithLMHeadModel (XLM model)
- xlm-roberta β TFXLMRobertaForMaskedLM (XLM-RoBERTa model)
- xlnet β TFXLNetLMHeadModel (XLNet model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForPreTraining
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForPreTraining.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForPreTraining.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForPreTraining.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForPreTraining
This is a generic model class that will be instantiated as one of the model classes of the library (with a pretraining head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: FlaxAlbertForPreTraining (ALBERT model)
- BartConfig configuration class: FlaxBartForConditionalGeneration (BART model)
- BertConfig configuration class: FlaxBertForPreTraining (BERT model)
- BigBirdConfig configuration class: FlaxBigBirdForPreTraining (BigBird model)
- ElectraConfig configuration class: FlaxElectraForPreTraining (ELECTRA model)
- LongT5Config configuration class: FlaxLongT5ForConditionalGeneration (LongT5 model)
- MBartConfig configuration class: FlaxMBartForConditionalGeneration (mBART model)
- MT5Config configuration class: FlaxMT5ForConditionalGeneration (MT5 model)
- RoFormerConfig configuration class: FlaxRoFormerForMaskedLM (RoFormer model)
- RobertaConfig configuration class: FlaxRobertaForMaskedLM (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: FlaxRobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- T5Config configuration class: FlaxT5ForConditionalGeneration (T5 model)
- Wav2Vec2Config configuration class: FlaxWav2Vec2ForPreTraining (Wav2Vec2 model)
- WhisperConfig configuration class: FlaxWhisperForConditionalGeneration (Whisper model)
- XLMRobertaConfig configuration class: FlaxXLMRobertaForMaskedLM (XLM-RoBERTa model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a pretraining head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a pretraining head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β FlaxAlbertForPreTraining (ALBERT model)
- bart β FlaxBartForConditionalGeneration (BART model)
- bert β FlaxBertForPreTraining (BERT model)
- big_bird β FlaxBigBirdForPreTraining (BigBird model)
- electra β FlaxElectraForPreTraining (ELECTRA model)
- longt5 β FlaxLongT5ForConditionalGeneration (LongT5 model)
- mbart β FlaxMBartForConditionalGeneration (mBART model)
- mt5 β FlaxMT5ForConditionalGeneration (MT5 model)
- roberta β FlaxRobertaForMaskedLM (RoBERTa model)
- roberta-prelayernorm β FlaxRobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- roformer β FlaxRoFormerForMaskedLM (RoFormer model)
- t5 β FlaxT5ForConditionalGeneration (T5 model)
- wav2vec2 β FlaxWav2Vec2ForPreTraining (Wav2Vec2 model)
- whisper β FlaxWhisperForConditionalGeneration (Whisper model)
- xlm-roberta β FlaxXLMRobertaForMaskedLM (XLM-RoBERTa model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForPreTraining
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForPreTraining.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForPreTraining.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForPreTraining.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
Natural Language Processing
The following auto classes are available for the following natural language processing tasks.
AutoModelForCausalLM
This is a generic model class that will be instantiated as one of the model classes of the library (with a causal language modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AriaTextConfig configuration class: AriaTextForCausalLM (AriaText model)
- BambaConfig configuration class: BambaForCausalLM (Bamba model)
- BartConfig configuration class: BartForCausalLM (BART model)
- BertConfig configuration class: BertLMHeadModel (BERT model)
- BertGenerationConfig configuration class: BertGenerationDecoder (Bert Generation model)
- BigBirdConfig configuration class: BigBirdForCausalLM (BigBird model)
- BigBirdPegasusConfig configuration class: BigBirdPegasusForCausalLM (BigBird-Pegasus model)
- BioGptConfig configuration class: BioGptForCausalLM (BioGpt model)
- BlenderbotConfig configuration class: BlenderbotForCausalLM (Blenderbot model)
- BlenderbotSmallConfig configuration class: BlenderbotSmallForCausalLM (BlenderbotSmall model)
- BloomConfig configuration class: BloomForCausalLM (BLOOM model)
- CTRLConfig configuration class: CTRLLMHeadModel (CTRL model)
- CamembertConfig configuration class: CamembertForCausalLM (CamemBERT model)
- CodeGenConfig configuration class: CodeGenForCausalLM (CodeGen model)
- Cohere2Config configuration class: Cohere2ForCausalLM (Cohere2 model)
- CohereConfig configuration class: CohereForCausalLM (Cohere model)
- CpmAntConfig configuration class: CpmAntForCausalLM (CPM-Ant model)
- Data2VecTextConfig configuration class: Data2VecTextForCausalLM (Data2VecText model)
- DbrxConfig configuration class: DbrxForCausalLM (DBRX model)
- ElectraConfig configuration class: ElectraForCausalLM (ELECTRA model)
- ErnieConfig configuration class: ErnieForCausalLM (ERNIE model)
- FalconConfig configuration class: FalconForCausalLM (Falcon model)
- FalconMambaConfig configuration class: FalconMambaForCausalLM (FalconMamba model)
- FuyuConfig configuration class: FuyuForCausalLM (Fuyu model)
- GPT2Config configuration class: GPT2LMHeadModel (OpenAI GPT-2 model)
- GPTBigCodeConfig configuration class: GPTBigCodeForCausalLM (GPTBigCode model)
- GPTJConfig configuration class: GPTJForCausalLM (GPT-J model)
- GPTNeoConfig configuration class: GPTNeoForCausalLM (GPT Neo model)
- GPTNeoXConfig configuration class: GPTNeoXForCausalLM (GPT NeoX model)
- GPTNeoXJapaneseConfig configuration class: GPTNeoXJapaneseForCausalLM (GPT NeoX Japanese model)
- Gemma2Config configuration class: Gemma2ForCausalLM (Gemma2 model)
- GemmaConfig configuration class: GemmaForCausalLM (Gemma model)
- GitConfig configuration class: GitForCausalLM (GIT model)
- GlmConfig configuration class: GlmForCausalLM (GLM model)
- GraniteConfig configuration class: GraniteForCausalLM (Granite model)
- GraniteMoeConfig configuration class: GraniteMoeForCausalLM (GraniteMoeMoe model)
- JambaConfig configuration class: JambaForCausalLM (Jamba model)
- JetMoeConfig configuration class: JetMoeForCausalLM (JetMoe model)
- LlamaConfig configuration class: LlamaForCausalLM (LLaMA model)
- MBartConfig configuration class: MBartForCausalLM (mBART model)
- Mamba2Config configuration class: Mamba2ForCausalLM (mamba2 model)
- MambaConfig configuration class: MambaForCausalLM (Mamba model)
- MarianConfig configuration class: MarianForCausalLM (Marian model)
- MegaConfig configuration class: MegaForCausalLM (MEGA model)
- MegatronBertConfig configuration class: MegatronBertForCausalLM (Megatron-BERT model)
- MistralConfig configuration class: MistralForCausalLM (Mistral model)
- MixtralConfig configuration class: MixtralForCausalLM (Mixtral model)
- MllamaConfig configuration class: MllamaForCausalLM (Mllama model)
- MoshiConfig configuration class: MoshiForCausalLM (Moshi model)
- MptConfig configuration class: MptForCausalLM (MPT model)
- MusicgenConfig configuration class: MusicgenForCausalLM (MusicGen model)
- MusicgenMelodyConfig configuration class: MusicgenMelodyForCausalLM (MusicGen Melody model)
- MvpConfig configuration class: MvpForCausalLM (MVP model)
- NemotronConfig configuration class: NemotronForCausalLM (Nemotron model)
- OPTConfig configuration class: OPTForCausalLM (OPT model)
- Olmo2Config configuration class: Olmo2ForCausalLM (OLMo2 model)
- OlmoConfig configuration class: OlmoForCausalLM (OLMo model)
- OlmoeConfig configuration class: OlmoeForCausalLM (OLMoE model)
- OpenAIGPTConfig configuration class: OpenAIGPTLMHeadModel (OpenAI GPT model)
- OpenLlamaConfig configuration class: OpenLlamaForCausalLM (OpenLlama model)
- PLBartConfig configuration class: PLBartForCausalLM (PLBart model)
- PegasusConfig configuration class: PegasusForCausalLM (Pegasus model)
- PersimmonConfig configuration class: PersimmonForCausalLM (Persimmon model)
- Phi3Config configuration class: Phi3ForCausalLM (Phi3 model)
- PhiConfig configuration class: PhiForCausalLM (Phi model)
- PhimoeConfig configuration class: PhimoeForCausalLM (Phimoe model)
- ProphetNetConfig configuration class: ProphetNetForCausalLM (ProphetNet model)
- QDQBertConfig configuration class: QDQBertLMHeadModel (QDQBert model)
- Qwen2Config configuration class: Qwen2ForCausalLM (Qwen2 model)
- Qwen2MoeConfig configuration class: Qwen2MoeForCausalLM (Qwen2MoE model)
- RecurrentGemmaConfig configuration class: RecurrentGemmaForCausalLM (RecurrentGemma model)
- ReformerConfig configuration class: ReformerModelWithLMHead (Reformer model)
- RemBertConfig configuration class: RemBertForCausalLM (RemBERT model)
- RoCBertConfig configuration class: RoCBertForCausalLM (RoCBert model)
- RoFormerConfig configuration class: RoFormerForCausalLM (RoFormer model)
- RobertaConfig configuration class: RobertaForCausalLM (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: RobertaPreLayerNormForCausalLM (RoBERTa-PreLayerNorm model)
- RwkvConfig configuration class: RwkvForCausalLM (RWKV model)
- Speech2Text2Config configuration class: Speech2Text2ForCausalLM (Speech2Text2 model)
- StableLmConfig configuration class: StableLmForCausalLM (StableLm model)
- Starcoder2Config configuration class: Starcoder2ForCausalLM (Starcoder2 model)
- TrOCRConfig configuration class: TrOCRForCausalLM (TrOCR model)
- TransfoXLConfig configuration class: TransfoXLLMHeadModel (Transformer-XL model)
- WhisperConfig configuration class: WhisperForCausalLM (Whisper model)
- XGLMConfig configuration class: XGLMForCausalLM (XGLM model)
- XLMConfig configuration class: XLMWithLMHeadModel (XLM model)
- XLMProphetNetConfig configuration class: XLMProphetNetForCausalLM (XLM-ProphetNet model)
- XLMRobertaConfig configuration class: XLMRobertaForCausalLM (XLM-RoBERTa model)
- XLMRobertaXLConfig configuration class: XLMRobertaXLForCausalLM (XLM-RoBERTa-XL model)
- XLNetConfig configuration class: XLNetLMHeadModel (XLNet model)
- XmodConfig configuration class: XmodForCausalLM (X-MOD model)
- ZambaConfig configuration class: ZambaForCausalLM (Zamba model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a causal language modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a causal language modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- aria_text β AriaTextForCausalLM (AriaText model)
- bamba β BambaForCausalLM (Bamba model)
- bart β BartForCausalLM (BART model)
- bert β BertLMHeadModel (BERT model)
- bert-generation β BertGenerationDecoder (Bert Generation model)
- big_bird β BigBirdForCausalLM (BigBird model)
- bigbird_pegasus β BigBirdPegasusForCausalLM (BigBird-Pegasus model)
- biogpt β BioGptForCausalLM (BioGpt model)
- blenderbot β BlenderbotForCausalLM (Blenderbot model)
- blenderbot-small β BlenderbotSmallForCausalLM (BlenderbotSmall model)
- bloom β BloomForCausalLM (BLOOM model)
- camembert β CamembertForCausalLM (CamemBERT model)
- code_llama β LlamaForCausalLM (CodeLlama model)
- codegen β CodeGenForCausalLM (CodeGen model)
- cohere β CohereForCausalLM (Cohere model)
- cohere2 β Cohere2ForCausalLM (Cohere2 model)
- cpmant β CpmAntForCausalLM (CPM-Ant model)
- ctrl β CTRLLMHeadModel (CTRL model)
- data2vec-text β Data2VecTextForCausalLM (Data2VecText model)
- dbrx β DbrxForCausalLM (DBRX model)
- electra β ElectraForCausalLM (ELECTRA model)
- ernie β ErnieForCausalLM (ERNIE model)
- falcon β FalconForCausalLM (Falcon model)
- falcon_mamba β FalconMambaForCausalLM (FalconMamba model)
- fuyu β FuyuForCausalLM (Fuyu model)
- gemma β GemmaForCausalLM (Gemma model)
- gemma2 β Gemma2ForCausalLM (Gemma2 model)
- git β GitForCausalLM (GIT model)
- glm β GlmForCausalLM (GLM model)
- gpt-sw3 β GPT2LMHeadModel (GPT-Sw3 model)
- gpt2 β GPT2LMHeadModel (OpenAI GPT-2 model)
- gpt_bigcode β GPTBigCodeForCausalLM (GPTBigCode model)
- gpt_neo β GPTNeoForCausalLM (GPT Neo model)
- gpt_neox β GPTNeoXForCausalLM (GPT NeoX model)
- gpt_neox_japanese β GPTNeoXJapaneseForCausalLM (GPT NeoX Japanese model)
- gptj β GPTJForCausalLM (GPT-J model)
- granite β GraniteForCausalLM (Granite model)
- granitemoe β GraniteMoeForCausalLM (GraniteMoeMoe model)
- jamba β JambaForCausalLM (Jamba model)
- jetmoe β JetMoeForCausalLM (JetMoe model)
- llama β LlamaForCausalLM (LLaMA model)
- mamba β MambaForCausalLM (Mamba model)
- mamba2 β Mamba2ForCausalLM (mamba2 model)
- marian β MarianForCausalLM (Marian model)
- mbart β MBartForCausalLM (mBART model)
- mega β MegaForCausalLM (MEGA model)
- megatron-bert β MegatronBertForCausalLM (Megatron-BERT model)
- mistral β MistralForCausalLM (Mistral model)
- mixtral β MixtralForCausalLM (Mixtral model)
- mllama β MllamaForCausalLM (Mllama model)
- moshi β MoshiForCausalLM (Moshi model)
- mpt β MptForCausalLM (MPT model)
- musicgen β MusicgenForCausalLM (MusicGen model)
- musicgen_melody β MusicgenMelodyForCausalLM (MusicGen Melody model)
- mvp β MvpForCausalLM (MVP model)
- nemotron β NemotronForCausalLM (Nemotron model)
- olmo β OlmoForCausalLM (OLMo model)
- olmo2 β Olmo2ForCausalLM (OLMo2 model)
- olmoe β OlmoeForCausalLM (OLMoE model)
- open-llama β OpenLlamaForCausalLM (OpenLlama model)
- openai-gpt β OpenAIGPTLMHeadModel (OpenAI GPT model)
- opt β OPTForCausalLM (OPT model)
- pegasus β PegasusForCausalLM (Pegasus model)
- persimmon β PersimmonForCausalLM (Persimmon model)
- phi β PhiForCausalLM (Phi model)
- phi3 β Phi3ForCausalLM (Phi3 model)
- phimoe β PhimoeForCausalLM (Phimoe model)
- plbart β PLBartForCausalLM (PLBart model)
- prophetnet β ProphetNetForCausalLM (ProphetNet model)
- qdqbert β QDQBertLMHeadModel (QDQBert model)
- qwen2 β Qwen2ForCausalLM (Qwen2 model)
- qwen2_moe β Qwen2MoeForCausalLM (Qwen2MoE model)
- recurrent_gemma β RecurrentGemmaForCausalLM (RecurrentGemma model)
- reformer β ReformerModelWithLMHead (Reformer model)
- rembert β RemBertForCausalLM (RemBERT model)
- roberta β RobertaForCausalLM (RoBERTa model)
- roberta-prelayernorm β RobertaPreLayerNormForCausalLM (RoBERTa-PreLayerNorm model)
- roc_bert β RoCBertForCausalLM (RoCBert model)
- roformer β RoFormerForCausalLM (RoFormer model)
- rwkv β RwkvForCausalLM (RWKV model)
- speech_to_text_2 β Speech2Text2ForCausalLM (Speech2Text2 model)
- stablelm β StableLmForCausalLM (StableLm model)
- starcoder2 β Starcoder2ForCausalLM (Starcoder2 model)
- transfo-xl β TransfoXLLMHeadModel (Transformer-XL model)
- trocr β TrOCRForCausalLM (TrOCR model)
- whisper β WhisperForCausalLM (Whisper model)
- xglm β XGLMForCausalLM (XGLM model)
- xlm β XLMWithLMHeadModel (XLM model)
- xlm-prophetnet β XLMProphetNetForCausalLM (XLM-ProphetNet model)
- xlm-roberta β XLMRobertaForCausalLM (XLM-RoBERTa model)
- xlm-roberta-xl β XLMRobertaXLForCausalLM (XLM-RoBERTa-XL model)
- xlnet β XLNetLMHeadModel (XLNet model)
- xmod β XmodForCausalLM (X-MOD model)
- zamba β ZambaForCausalLM (Zamba model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForCausalLM
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForCausalLM.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForCausalLM.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForCausalLM.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForCausalLM
This is a generic model class that will be instantiated as one of the model classes of the library (with a causal language modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BertConfig configuration class: TFBertLMHeadModel (BERT model)
- CTRLConfig configuration class: TFCTRLLMHeadModel (CTRL model)
- CamembertConfig configuration class: TFCamembertForCausalLM (CamemBERT model)
- GPT2Config configuration class: TFGPT2LMHeadModel (OpenAI GPT-2 model)
- GPTJConfig configuration class: TFGPTJForCausalLM (GPT-J model)
- MistralConfig configuration class: TFMistralForCausalLM (Mistral model)
- OPTConfig configuration class: TFOPTForCausalLM (OPT model)
- OpenAIGPTConfig configuration class: TFOpenAIGPTLMHeadModel (OpenAI GPT model)
- RemBertConfig configuration class: TFRemBertForCausalLM (RemBERT model)
- RoFormerConfig configuration class: TFRoFormerForCausalLM (RoFormer model)
- RobertaConfig configuration class: TFRobertaForCausalLM (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: TFRobertaPreLayerNormForCausalLM (RoBERTa-PreLayerNorm model)
- TransfoXLConfig configuration class: TFTransfoXLLMHeadModel (Transformer-XL model)
- XGLMConfig configuration class: TFXGLMForCausalLM (XGLM model)
- XLMConfig configuration class: TFXLMWithLMHeadModel (XLM model)
- XLMRobertaConfig configuration class: TFXLMRobertaForCausalLM (XLM-RoBERTa model)
- XLNetConfig configuration class: TFXLNetLMHeadModel (XLNet model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a causal language modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a causal language modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- bert β TFBertLMHeadModel (BERT model)
- camembert β TFCamembertForCausalLM (CamemBERT model)
- ctrl β TFCTRLLMHeadModel (CTRL model)
- gpt-sw3 β TFGPT2LMHeadModel (GPT-Sw3 model)
- gpt2 β TFGPT2LMHeadModel (OpenAI GPT-2 model)
- gptj β TFGPTJForCausalLM (GPT-J model)
- mistral β TFMistralForCausalLM (Mistral model)
- openai-gpt β TFOpenAIGPTLMHeadModel (OpenAI GPT model)
- opt β TFOPTForCausalLM (OPT model)
- rembert β TFRemBertForCausalLM (RemBERT model)
- roberta β TFRobertaForCausalLM (RoBERTa model)
- roberta-prelayernorm β TFRobertaPreLayerNormForCausalLM (RoBERTa-PreLayerNorm model)
- roformer β TFRoFormerForCausalLM (RoFormer model)
- transfo-xl β TFTransfoXLLMHeadModel (Transformer-XL model)
- xglm β TFXGLMForCausalLM (XGLM model)
- xlm β TFXLMWithLMHeadModel (XLM model)
- xlm-roberta β TFXLMRobertaForCausalLM (XLM-RoBERTa model)
- xlnet β TFXLNetLMHeadModel (XLNet model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForCausalLM
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForCausalLM.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForCausalLM.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForCausalLM.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForCausalLM
This is a generic model class that will be instantiated as one of the model classes of the library (with a causal language modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BartConfig configuration class: FlaxBartForCausalLM (BART model)
- BertConfig configuration class: FlaxBertForCausalLM (BERT model)
- BigBirdConfig configuration class: FlaxBigBirdForCausalLM (BigBird model)
- BloomConfig configuration class: FlaxBloomForCausalLM (BLOOM model)
- ElectraConfig configuration class: FlaxElectraForCausalLM (ELECTRA model)
- GPT2Config configuration class: FlaxGPT2LMHeadModel (OpenAI GPT-2 model)
- GPTJConfig configuration class: FlaxGPTJForCausalLM (GPT-J model)
- GPTNeoConfig configuration class: FlaxGPTNeoForCausalLM (GPT Neo model)
- GemmaConfig configuration class: FlaxGemmaForCausalLM (Gemma model)
- LlamaConfig configuration class: FlaxLlamaForCausalLM (LLaMA model)
- MistralConfig configuration class: FlaxMistralForCausalLM (Mistral model)
- OPTConfig configuration class: FlaxOPTForCausalLM (OPT model)
- RobertaConfig configuration class: FlaxRobertaForCausalLM (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: FlaxRobertaPreLayerNormForCausalLM (RoBERTa-PreLayerNorm model)
- XGLMConfig configuration class: FlaxXGLMForCausalLM (XGLM model)
- XLMRobertaConfig configuration class: FlaxXLMRobertaForCausalLM (XLM-RoBERTa model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a causal language modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a causal language modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- bart β FlaxBartForCausalLM (BART model)
- bert β FlaxBertForCausalLM (BERT model)
- big_bird β FlaxBigBirdForCausalLM (BigBird model)
- bloom β FlaxBloomForCausalLM (BLOOM model)
- electra β FlaxElectraForCausalLM (ELECTRA model)
- gemma β FlaxGemmaForCausalLM (Gemma model)
- gpt-sw3 β FlaxGPT2LMHeadModel (GPT-Sw3 model)
- gpt2 β FlaxGPT2LMHeadModel (OpenAI GPT-2 model)
- gpt_neo β FlaxGPTNeoForCausalLM (GPT Neo model)
- gptj β FlaxGPTJForCausalLM (GPT-J model)
- llama β FlaxLlamaForCausalLM (LLaMA model)
- mistral β FlaxMistralForCausalLM (Mistral model)
- opt β FlaxOPTForCausalLM (OPT model)
- roberta β FlaxRobertaForCausalLM (RoBERTa model)
- roberta-prelayernorm β FlaxRobertaPreLayerNormForCausalLM (RoBERTa-PreLayerNorm model)
- xglm β FlaxXGLMForCausalLM (XGLM model)
- xlm-roberta β FlaxXLMRobertaForCausalLM (XLM-RoBERTa model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForCausalLM
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForCausalLM.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForCausalLM.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForCausalLM.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForMaskedLM
This is a generic model class that will be instantiated as one of the model classes of the library (with a masked language modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: AlbertForMaskedLM (ALBERT model)
- BartConfig configuration class: BartForConditionalGeneration (BART model)
- BertConfig configuration class: BertForMaskedLM (BERT model)
- BigBirdConfig configuration class: BigBirdForMaskedLM (BigBird model)
- CamembertConfig configuration class: CamembertForMaskedLM (CamemBERT model)
- ConvBertConfig configuration class: ConvBertForMaskedLM (ConvBERT model)
- Data2VecTextConfig configuration class: Data2VecTextForMaskedLM (Data2VecText model)
- DebertaConfig configuration class: DebertaForMaskedLM (DeBERTa model)
- DebertaV2Config configuration class: DebertaV2ForMaskedLM (DeBERTa-v2 model)
- DistilBertConfig configuration class: DistilBertForMaskedLM (DistilBERT model)
- ElectraConfig configuration class: ElectraForMaskedLM (ELECTRA model)
- ErnieConfig configuration class: ErnieForMaskedLM (ERNIE model)
- EsmConfig configuration class: EsmForMaskedLM (ESM model)
- FNetConfig configuration class: FNetForMaskedLM (FNet model)
- FlaubertConfig configuration class: FlaubertWithLMHeadModel (FlauBERT model)
- FunnelConfig configuration class: FunnelForMaskedLM (Funnel Transformer model)
- IBertConfig configuration class: IBertForMaskedLM (I-BERT model)
- LayoutLMConfig configuration class: LayoutLMForMaskedLM (LayoutLM model)
- LongformerConfig configuration class: LongformerForMaskedLM (Longformer model)
- LukeConfig configuration class: LukeForMaskedLM (LUKE model)
- MBartConfig configuration class: MBartForConditionalGeneration (mBART model)
- MPNetConfig configuration class: MPNetForMaskedLM (MPNet model)
- MegaConfig configuration class: MegaForMaskedLM (MEGA model)
- MegatronBertConfig configuration class: MegatronBertForMaskedLM (Megatron-BERT model)
- MobileBertConfig configuration class: MobileBertForMaskedLM (MobileBERT model)
- ModernBertConfig configuration class: ModernBertForMaskedLM (ModernBERT model)
- MraConfig configuration class: MraForMaskedLM (MRA model)
- MvpConfig configuration class: MvpForConditionalGeneration (MVP model)
- NezhaConfig configuration class: NezhaForMaskedLM (Nezha model)
- NystromformerConfig configuration class: NystromformerForMaskedLM (Nyströmformer model)
- PerceiverConfig configuration class: PerceiverForMaskedLM (Perceiver model)
- QDQBertConfig configuration class: QDQBertForMaskedLM (QDQBert model)
- ReformerConfig configuration class: ReformerForMaskedLM (Reformer model)
- RemBertConfig configuration class: RemBertForMaskedLM (RemBERT model)
- RoCBertConfig configuration class: RoCBertForMaskedLM (RoCBert model)
- RoFormerConfig configuration class: RoFormerForMaskedLM (RoFormer model)
- RobertaConfig configuration class: RobertaForMaskedLM (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: RobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- SqueezeBertConfig configuration class: SqueezeBertForMaskedLM (SqueezeBERT model)
- TapasConfig configuration class: TapasForMaskedLM (TAPAS model)
- Wav2Vec2Config configuration class:
Wav2Vec2ForMaskedLM
(Wav2Vec2 model) - XLMConfig configuration class: XLMWithLMHeadModel (XLM model)
- XLMRobertaConfig configuration class: XLMRobertaForMaskedLM (XLM-RoBERTa model)
- XLMRobertaXLConfig configuration class: XLMRobertaXLForMaskedLM (XLM-RoBERTa-XL model)
- XmodConfig configuration class: XmodForMaskedLM (X-MOD model)
- YosoConfig configuration class: YosoForMaskedLM (YOSO model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a masked language modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a masked language modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β AlbertForMaskedLM (ALBERT model)
- bart β BartForConditionalGeneration (BART model)
- bert β BertForMaskedLM (BERT model)
- big_bird β BigBirdForMaskedLM (BigBird model)
- camembert β CamembertForMaskedLM (CamemBERT model)
- convbert β ConvBertForMaskedLM (ConvBERT model)
- data2vec-text β Data2VecTextForMaskedLM (Data2VecText model)
- deberta β DebertaForMaskedLM (DeBERTa model)
- deberta-v2 β DebertaV2ForMaskedLM (DeBERTa-v2 model)
- distilbert β DistilBertForMaskedLM (DistilBERT model)
- electra β ElectraForMaskedLM (ELECTRA model)
- ernie β ErnieForMaskedLM (ERNIE model)
- esm β EsmForMaskedLM (ESM model)
- flaubert β FlaubertWithLMHeadModel (FlauBERT model)
- fnet β FNetForMaskedLM (FNet model)
- funnel β FunnelForMaskedLM (Funnel Transformer model)
- ibert β IBertForMaskedLM (I-BERT model)
- layoutlm β LayoutLMForMaskedLM (LayoutLM model)
- longformer β LongformerForMaskedLM (Longformer model)
- luke β LukeForMaskedLM (LUKE model)
- mbart β MBartForConditionalGeneration (mBART model)
- mega β MegaForMaskedLM (MEGA model)
- megatron-bert β MegatronBertForMaskedLM (Megatron-BERT model)
- mobilebert β MobileBertForMaskedLM (MobileBERT model)
- modernbert β ModernBertForMaskedLM (ModernBERT model)
- mpnet β MPNetForMaskedLM (MPNet model)
- mra β MraForMaskedLM (MRA model)
- mvp β MvpForConditionalGeneration (MVP model)
- nezha β NezhaForMaskedLM (Nezha model)
- nystromformer β NystromformerForMaskedLM (NystrΓΆmformer model)
- perceiver β PerceiverForMaskedLM (Perceiver model)
- qdqbert β QDQBertForMaskedLM (QDQBert model)
- reformer β ReformerForMaskedLM (Reformer model)
- rembert β RemBertForMaskedLM (RemBERT model)
- roberta β RobertaForMaskedLM (RoBERTa model)
- roberta-prelayernorm β RobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- roc_bert β RoCBertForMaskedLM (RoCBert model)
- roformer β RoFormerForMaskedLM (RoFormer model)
- squeezebert β SqueezeBertForMaskedLM (SqueezeBERT model)
- tapas β TapasForMaskedLM (TAPAS model)
- wav2vec2 β
Wav2Vec2ForMaskedLM
(Wav2Vec2 model) - xlm β XLMWithLMHeadModel (XLM model)
- xlm-roberta β XLMRobertaForMaskedLM (XLM-RoBERTa model)
- xlm-roberta-xl β XLMRobertaXLForMaskedLM (XLM-RoBERTa-XL model)
- xmod β XmodForMaskedLM (X-MOD model)
- yoso β YosoForMaskedLM (YOSO model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForMaskedLM
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForMaskedLM.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForMaskedLM.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForMaskedLM.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForMaskedLM
This is a generic model class that will be instantiated as one of the model classes of the library (with a masked language modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: TFAlbertForMaskedLM (ALBERT model)
- BertConfig configuration class: TFBertForMaskedLM (BERT model)
- CamembertConfig configuration class: TFCamembertForMaskedLM (CamemBERT model)
- ConvBertConfig configuration class: TFConvBertForMaskedLM (ConvBERT model)
- DebertaConfig configuration class: TFDebertaForMaskedLM (DeBERTa model)
- DebertaV2Config configuration class: TFDebertaV2ForMaskedLM (DeBERTa-v2 model)
- DistilBertConfig configuration class: TFDistilBertForMaskedLM (DistilBERT model)
- ElectraConfig configuration class: TFElectraForMaskedLM (ELECTRA model)
- EsmConfig configuration class: TFEsmForMaskedLM (ESM model)
- FlaubertConfig configuration class: TFFlaubertWithLMHeadModel (FlauBERT model)
- FunnelConfig configuration class: TFFunnelForMaskedLM (Funnel Transformer model)
- LayoutLMConfig configuration class: TFLayoutLMForMaskedLM (LayoutLM model)
- LongformerConfig configuration class: TFLongformerForMaskedLM (Longformer model)
- MPNetConfig configuration class: TFMPNetForMaskedLM (MPNet model)
- MobileBertConfig configuration class: TFMobileBertForMaskedLM (MobileBERT model)
- RemBertConfig configuration class: TFRemBertForMaskedLM (RemBERT model)
- RoFormerConfig configuration class: TFRoFormerForMaskedLM (RoFormer model)
- RobertaConfig configuration class: TFRobertaForMaskedLM (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: TFRobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- TapasConfig configuration class: TFTapasForMaskedLM (TAPAS model)
- XLMConfig configuration class: TFXLMWithLMHeadModel (XLM model)
- XLMRobertaConfig configuration class: TFXLMRobertaForMaskedLM (XLM-RoBERTa model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a masked language modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a masked language modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β TFAlbertForMaskedLM (ALBERT model)
- bert β TFBertForMaskedLM (BERT model)
- camembert β TFCamembertForMaskedLM (CamemBERT model)
- convbert β TFConvBertForMaskedLM (ConvBERT model)
- deberta β TFDebertaForMaskedLM (DeBERTa model)
- deberta-v2 β TFDebertaV2ForMaskedLM (DeBERTa-v2 model)
- distilbert β TFDistilBertForMaskedLM (DistilBERT model)
- electra β TFElectraForMaskedLM (ELECTRA model)
- esm β TFEsmForMaskedLM (ESM model)
- flaubert β TFFlaubertWithLMHeadModel (FlauBERT model)
- funnel β TFFunnelForMaskedLM (Funnel Transformer model)
- layoutlm β TFLayoutLMForMaskedLM (LayoutLM model)
- longformer β TFLongformerForMaskedLM (Longformer model)
- mobilebert β TFMobileBertForMaskedLM (MobileBERT model)
- mpnet β TFMPNetForMaskedLM (MPNet model)
- rembert β TFRemBertForMaskedLM (RemBERT model)
- roberta β TFRobertaForMaskedLM (RoBERTa model)
- roberta-prelayernorm β TFRobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- roformer β TFRoFormerForMaskedLM (RoFormer model)
- tapas β TFTapasForMaskedLM (TAPAS model)
- xlm β TFXLMWithLMHeadModel (XLM model)
- xlm-roberta β TFXLMRobertaForMaskedLM (XLM-RoBERTa model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForMaskedLM
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForMaskedLM.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForMaskedLM.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForMaskedLM.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForMaskedLM
This is a generic model class that will be instantiated as one of the model classes of the library (with a masked language modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: FlaxAlbertForMaskedLM (ALBERT model)
- BartConfig configuration class: FlaxBartForConditionalGeneration (BART model)
- BertConfig configuration class: FlaxBertForMaskedLM (BERT model)
- BigBirdConfig configuration class: FlaxBigBirdForMaskedLM (BigBird model)
- DistilBertConfig configuration class: FlaxDistilBertForMaskedLM (DistilBERT model)
- ElectraConfig configuration class: FlaxElectraForMaskedLM (ELECTRA model)
- MBartConfig configuration class: FlaxMBartForConditionalGeneration (mBART model)
- RoFormerConfig configuration class: FlaxRoFormerForMaskedLM (RoFormer model)
- RobertaConfig configuration class: FlaxRobertaForMaskedLM (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: FlaxRobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- XLMRobertaConfig configuration class: FlaxXLMRobertaForMaskedLM (XLM-RoBERTa model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a masked language modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a masked language modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β FlaxAlbertForMaskedLM (ALBERT model)
- bart β FlaxBartForConditionalGeneration (BART model)
- bert β FlaxBertForMaskedLM (BERT model)
- big_bird β FlaxBigBirdForMaskedLM (BigBird model)
- distilbert β FlaxDistilBertForMaskedLM (DistilBERT model)
- electra β FlaxElectraForMaskedLM (ELECTRA model)
- mbart β FlaxMBartForConditionalGeneration (mBART model)
- roberta β FlaxRobertaForMaskedLM (RoBERTa model)
- roberta-prelayernorm β FlaxRobertaPreLayerNormForMaskedLM (RoBERTa-PreLayerNorm model)
- roformer β FlaxRoFormerForMaskedLM (RoFormer model)
- xlm-roberta β FlaxXLMRobertaForMaskedLM (XLM-RoBERTa model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForMaskedLM
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForMaskedLM.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForMaskedLM.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForMaskedLM.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForMaskGeneration
TFAutoModelForMaskGeneration
AutoModelForSeq2SeqLM
This is a generic model class that will be instantiated as one of the model classes of the library (with a sequence-to-sequence language modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BartConfig configuration class: BartForConditionalGeneration (BART model)
- BigBirdPegasusConfig configuration class: BigBirdPegasusForConditionalGeneration (BigBird-Pegasus model)
- BlenderbotConfig configuration class: BlenderbotForConditionalGeneration (Blenderbot model)
- BlenderbotSmallConfig configuration class: BlenderbotSmallForConditionalGeneration (BlenderbotSmall model)
- EncoderDecoderConfig configuration class: EncoderDecoderModel (Encoder decoder model)
- FSMTConfig configuration class: FSMTForConditionalGeneration (FairSeq Machine-Translation model)
- GPTSanJapaneseConfig configuration class: GPTSanJapaneseForConditionalGeneration (GPTSAN-japanese model)
- LEDConfig configuration class: LEDForConditionalGeneration (LED model)
- LongT5Config configuration class: LongT5ForConditionalGeneration (LongT5 model)
- M2M100Config configuration class: M2M100ForConditionalGeneration (M2M100 model)
- MBartConfig configuration class: MBartForConditionalGeneration (mBART model)
- MT5Config configuration class: MT5ForConditionalGeneration (MT5 model)
- MarianConfig configuration class: MarianMTModel (Marian model)
- MvpConfig configuration class: MvpForConditionalGeneration (MVP model)
- NllbMoeConfig configuration class: NllbMoeForConditionalGeneration (NLLB-MOE model)
- PLBartConfig configuration class: PLBartForConditionalGeneration (PLBart model)
- PegasusConfig configuration class: PegasusForConditionalGeneration (Pegasus model)
- PegasusXConfig configuration class: PegasusXForConditionalGeneration (PEGASUS-X model)
- ProphetNetConfig configuration class: ProphetNetForConditionalGeneration (ProphetNet model)
- Qwen2AudioConfig configuration class: Qwen2AudioForConditionalGeneration (Qwen2Audio model)
- SeamlessM4TConfig configuration class: SeamlessM4TForTextToText (SeamlessM4T model)
- SeamlessM4Tv2Config configuration class: SeamlessM4Tv2ForTextToText (SeamlessM4Tv2 model)
- SwitchTransformersConfig configuration class: SwitchTransformersForConditionalGeneration (SwitchTransformers model)
- T5Config configuration class: T5ForConditionalGeneration (T5 model)
- UMT5Config configuration class: UMT5ForConditionalGeneration (UMT5 model)
- XLMProphetNetConfig configuration class: XLMProphetNetForConditionalGeneration (XLM-ProphetNet model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a sequence-to-sequence language modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a sequence-to-sequence language modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- bart β BartForConditionalGeneration (BART model)
- bigbird_pegasus β BigBirdPegasusForConditionalGeneration (BigBird-Pegasus model)
- blenderbot β BlenderbotForConditionalGeneration (Blenderbot model)
- blenderbot-small β BlenderbotSmallForConditionalGeneration (BlenderbotSmall model)
- encoder-decoder β EncoderDecoderModel (Encoder decoder model)
- fsmt β FSMTForConditionalGeneration (FairSeq Machine-Translation model)
- gptsan-japanese β GPTSanJapaneseForConditionalGeneration (GPTSAN-japanese model)
- led β LEDForConditionalGeneration (LED model)
- longt5 β LongT5ForConditionalGeneration (LongT5 model)
- m2m_100 β M2M100ForConditionalGeneration (M2M100 model)
- marian β MarianMTModel (Marian model)
- mbart β MBartForConditionalGeneration (mBART model)
- mt5 β MT5ForConditionalGeneration (MT5 model)
- mvp β MvpForConditionalGeneration (MVP model)
- nllb-moe β NllbMoeForConditionalGeneration (NLLB-MOE model)
- pegasus β PegasusForConditionalGeneration (Pegasus model)
- pegasus_x β PegasusXForConditionalGeneration (PEGASUS-X model)
- plbart β PLBartForConditionalGeneration (PLBart model)
- prophetnet β ProphetNetForConditionalGeneration (ProphetNet model)
- qwen2_audio β Qwen2AudioForConditionalGeneration (Qwen2Audio model)
- seamless_m4t β SeamlessM4TForTextToText (SeamlessM4T model)
- seamless_m4t_v2 β SeamlessM4Tv2ForTextToText (SeamlessM4Tv2 model)
- switch_transformers β SwitchTransformersForConditionalGeneration (SwitchTransformers model)
- t5 β T5ForConditionalGeneration (T5 model)
- umt5 β UMT5ForConditionalGeneration (UMT5 model)
- xlm-prophetnet β XLMProphetNetForConditionalGeneration (XLM-ProphetNet model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForSeq2SeqLM
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
>>> # Update configuration during loading
>>> model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/t5_tf_model_config.json")
>>> model = AutoModelForSeq2SeqLM.from_pretrained(
... "./tf_model/t5_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForSeq2SeqLM
This is a generic model class that will be instantiated as one of the model classes of the library (with a sequence-to-sequence language modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BartConfig configuration class: TFBartForConditionalGeneration (BART model)
- BlenderbotConfig configuration class: TFBlenderbotForConditionalGeneration (Blenderbot model)
- BlenderbotSmallConfig configuration class: TFBlenderbotSmallForConditionalGeneration (BlenderbotSmall model)
- EncoderDecoderConfig configuration class: TFEncoderDecoderModel (Encoder decoder model)
- LEDConfig configuration class: TFLEDForConditionalGeneration (LED model)
- MBartConfig configuration class: TFMBartForConditionalGeneration (mBART model)
- MT5Config configuration class: TFMT5ForConditionalGeneration (MT5 model)
- MarianConfig configuration class: TFMarianMTModel (Marian model)
- PegasusConfig configuration class: TFPegasusForConditionalGeneration (Pegasus model)
- T5Config configuration class: TFT5ForConditionalGeneration (T5 model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a sequence-to-sequence language modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a sequence-to-sequence language modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- bart β TFBartForConditionalGeneration (BART model)
- blenderbot β TFBlenderbotForConditionalGeneration (Blenderbot model)
- blenderbot-small β TFBlenderbotSmallForConditionalGeneration (BlenderbotSmall model)
- encoder-decoder β TFEncoderDecoderModel (Encoder decoder model)
- led β TFLEDForConditionalGeneration (LED model)
- marian β TFMarianMTModel (Marian model)
- mbart β TFMBartForConditionalGeneration (mBART model)
- mt5 β TFMT5ForConditionalGeneration (MT5 model)
- pegasus β TFPegasusForConditionalGeneration (Pegasus model)
- t5 β TFT5ForConditionalGeneration (T5 model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForSeq2SeqLM
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
>>> # Update configuration during loading
>>> model = TFAutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/t5_pt_model_config.json")
>>> model = TFAutoModelForSeq2SeqLM.from_pretrained(
... "./pt_model/t5_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForSeq2SeqLM
This is a generic model class that will be instantiated as one of the model classes of the library (with a sequence-to-sequence language modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BartConfig configuration class: FlaxBartForConditionalGeneration (BART model)
- BlenderbotConfig configuration class: FlaxBlenderbotForConditionalGeneration (Blenderbot model)
- BlenderbotSmallConfig configuration class: FlaxBlenderbotSmallForConditionalGeneration (BlenderbotSmall model)
- EncoderDecoderConfig configuration class: FlaxEncoderDecoderModel (Encoder decoder model)
- LongT5Config configuration class: FlaxLongT5ForConditionalGeneration (LongT5 model)
- MBartConfig configuration class: FlaxMBartForConditionalGeneration (mBART model)
- MT5Config configuration class: FlaxMT5ForConditionalGeneration (MT5 model)
- MarianConfig configuration class: FlaxMarianMTModel (Marian model)
- PegasusConfig configuration class: FlaxPegasusForConditionalGeneration (Pegasus model)
- T5Config configuration class: FlaxT5ForConditionalGeneration (T5 model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a sequence-to-sequence language modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a sequence-to-sequence language modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- bart β FlaxBartForConditionalGeneration (BART model)
- blenderbot β FlaxBlenderbotForConditionalGeneration (Blenderbot model)
- blenderbot-small β FlaxBlenderbotSmallForConditionalGeneration (BlenderbotSmall model)
- encoder-decoder β FlaxEncoderDecoderModel (Encoder decoder model)
- longt5 β FlaxLongT5ForConditionalGeneration (LongT5 model)
- marian β FlaxMarianMTModel (Marian model)
- mbart β FlaxMBartForConditionalGeneration (mBART model)
- mt5 β FlaxMT5ForConditionalGeneration (MT5 model)
- pegasus β FlaxPegasusForConditionalGeneration (Pegasus model)
- t5 β FlaxT5ForConditionalGeneration (T5 model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForSeq2SeqLM
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/t5_pt_model_config.json")
>>> model = FlaxAutoModelForSeq2SeqLM.from_pretrained(
... "./pt_model/t5_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForSequenceClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a sequence classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: AlbertForSequenceClassification (ALBERT model)
- BartConfig configuration class: BartForSequenceClassification (BART model)
- BertConfig configuration class: BertForSequenceClassification (BERT model)
- BigBirdConfig configuration class: BigBirdForSequenceClassification (BigBird model)
- BigBirdPegasusConfig configuration class: BigBirdPegasusForSequenceClassification (BigBird-Pegasus model)
- BioGptConfig configuration class: BioGptForSequenceClassification (BioGpt model)
- BloomConfig configuration class: BloomForSequenceClassification (BLOOM model)
- CTRLConfig configuration class: CTRLForSequenceClassification (CTRL model)
- CamembertConfig configuration class: CamembertForSequenceClassification (CamemBERT model)
- CanineConfig configuration class: CanineForSequenceClassification (CANINE model)
- ConvBertConfig configuration class: ConvBertForSequenceClassification (ConvBERT model)
- Data2VecTextConfig configuration class: Data2VecTextForSequenceClassification (Data2VecText model)
- DebertaConfig configuration class: DebertaForSequenceClassification (DeBERTa model)
- DebertaV2Config configuration class: DebertaV2ForSequenceClassification (DeBERTa-v2 model)
- DistilBertConfig configuration class: DistilBertForSequenceClassification (DistilBERT model)
- ElectraConfig configuration class: ElectraForSequenceClassification (ELECTRA model)
- ErnieConfig configuration class: ErnieForSequenceClassification (ERNIE model)
- ErnieMConfig configuration class: ErnieMForSequenceClassification (ErnieM model)
- EsmConfig configuration class: EsmForSequenceClassification (ESM model)
- FNetConfig configuration class: FNetForSequenceClassification (FNet model)
- FalconConfig configuration class: FalconForSequenceClassification (Falcon model)
- FlaubertConfig configuration class: FlaubertForSequenceClassification (FlauBERT model)
- FunnelConfig configuration class: FunnelForSequenceClassification (Funnel Transformer model)
- GPT2Config configuration class: GPT2ForSequenceClassification (OpenAI GPT-2 model)
- GPTBigCodeConfig configuration class: GPTBigCodeForSequenceClassification (GPTBigCode model)
- GPTJConfig configuration class: GPTJForSequenceClassification (GPT-J model)
- GPTNeoConfig configuration class: GPTNeoForSequenceClassification (GPT Neo model)
- GPTNeoXConfig configuration class: GPTNeoXForSequenceClassification (GPT NeoX model)
- Gemma2Config configuration class: Gemma2ForSequenceClassification (Gemma2 model)
- GemmaConfig configuration class: GemmaForSequenceClassification (Gemma model)
- GlmConfig configuration class: GlmForSequenceClassification (GLM model)
- IBertConfig configuration class: IBertForSequenceClassification (I-BERT model)
- JambaConfig configuration class: JambaForSequenceClassification (Jamba model)
- JetMoeConfig configuration class: JetMoeForSequenceClassification (JetMoe model)
- LEDConfig configuration class: LEDForSequenceClassification (LED model)
- LayoutLMConfig configuration class: LayoutLMForSequenceClassification (LayoutLM model)
- LayoutLMv2Config configuration class: LayoutLMv2ForSequenceClassification (LayoutLMv2 model)
- LayoutLMv3Config configuration class: LayoutLMv3ForSequenceClassification (LayoutLMv3 model)
- LiltConfig configuration class: LiltForSequenceClassification (LiLT model)
- LlamaConfig configuration class: LlamaForSequenceClassification (LLaMA model)
- LongformerConfig configuration class: LongformerForSequenceClassification (Longformer model)
- LukeConfig configuration class: LukeForSequenceClassification (LUKE model)
- MBartConfig configuration class: MBartForSequenceClassification (mBART model)
- MPNetConfig configuration class: MPNetForSequenceClassification (MPNet model)
- MT5Config configuration class: MT5ForSequenceClassification (MT5 model)
- MarkupLMConfig configuration class: MarkupLMForSequenceClassification (MarkupLM model)
- MegaConfig configuration class: MegaForSequenceClassification (MEGA model)
- MegatronBertConfig configuration class: MegatronBertForSequenceClassification (Megatron-BERT model)
- MistralConfig configuration class: MistralForSequenceClassification (Mistral model)
- MixtralConfig configuration class: MixtralForSequenceClassification (Mixtral model)
- MobileBertConfig configuration class: MobileBertForSequenceClassification (MobileBERT model)
- ModernBertConfig configuration class: ModernBertForSequenceClassification (ModernBERT model)
- MptConfig configuration class: MptForSequenceClassification (MPT model)
- MraConfig configuration class: MraForSequenceClassification (MRA model)
- MvpConfig configuration class: MvpForSequenceClassification (MVP model)
- NemotronConfig configuration class: NemotronForSequenceClassification (Nemotron model)
- NezhaConfig configuration class: NezhaForSequenceClassification (Nezha model)
- NystromformerConfig configuration class: NystromformerForSequenceClassification (Nyströmformer model)
- OPTConfig configuration class: OPTForSequenceClassification (OPT model)
- OpenAIGPTConfig configuration class: OpenAIGPTForSequenceClassification (OpenAI GPT model)
- OpenLlamaConfig configuration class: OpenLlamaForSequenceClassification (OpenLlama model)
- PLBartConfig configuration class: PLBartForSequenceClassification (PLBart model)
- PerceiverConfig configuration class: PerceiverForSequenceClassification (Perceiver model)
- PersimmonConfig configuration class: PersimmonForSequenceClassification (Persimmon model)
- Phi3Config configuration class: Phi3ForSequenceClassification (Phi3 model)
- PhiConfig configuration class: PhiForSequenceClassification (Phi model)
- PhimoeConfig configuration class: PhimoeForSequenceClassification (Phimoe model)
- QDQBertConfig configuration class: QDQBertForSequenceClassification (QDQBert model)
- Qwen2Config configuration class: Qwen2ForSequenceClassification (Qwen2 model)
- Qwen2MoeConfig configuration class: Qwen2MoeForSequenceClassification (Qwen2MoE model)
- ReformerConfig configuration class: ReformerForSequenceClassification (Reformer model)
- RemBertConfig configuration class: RemBertForSequenceClassification (RemBERT model)
- RoCBertConfig configuration class: RoCBertForSequenceClassification (RoCBert model)
- RoFormerConfig configuration class: RoFormerForSequenceClassification (RoFormer model)
- RobertaConfig configuration class: RobertaForSequenceClassification (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: RobertaPreLayerNormForSequenceClassification (RoBERTa-PreLayerNorm model)
- SqueezeBertConfig configuration class: SqueezeBertForSequenceClassification (SqueezeBERT model)
- StableLmConfig configuration class: StableLmForSequenceClassification (StableLm model)
- Starcoder2Config configuration class: Starcoder2ForSequenceClassification (Starcoder2 model)
- T5Config configuration class: T5ForSequenceClassification (T5 model)
- TapasConfig configuration class: TapasForSequenceClassification (TAPAS model)
- TransfoXLConfig configuration class: TransfoXLForSequenceClassification (Transformer-XL model)
- UMT5Config configuration class: UMT5ForSequenceClassification (UMT5 model)
- XLMConfig configuration class: XLMForSequenceClassification (XLM model)
- XLMRobertaConfig configuration class: XLMRobertaForSequenceClassification (XLM-RoBERTa model)
- XLMRobertaXLConfig configuration class: XLMRobertaXLForSequenceClassification (XLM-RoBERTa-XL model)
- XLNetConfig configuration class: XLNetForSequenceClassification (XLNet model)
- XmodConfig configuration class: XmodForSequenceClassification (X-MOD model)
- YosoConfig configuration class: YosoForSequenceClassification (YOSO model)
- ZambaConfig configuration class: ZambaForSequenceClassification (Zamba model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a sequence classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a sequence classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β AlbertForSequenceClassification (ALBERT model)
- bart β BartForSequenceClassification (BART model)
- bert β BertForSequenceClassification (BERT model)
- big_bird β BigBirdForSequenceClassification (BigBird model)
- bigbird_pegasus β BigBirdPegasusForSequenceClassification (BigBird-Pegasus model)
- biogpt β BioGptForSequenceClassification (BioGpt model)
- bloom β BloomForSequenceClassification (BLOOM model)
- camembert β CamembertForSequenceClassification (CamemBERT model)
- canine β CanineForSequenceClassification (CANINE model)
- code_llama β LlamaForSequenceClassification (CodeLlama model)
- convbert β ConvBertForSequenceClassification (ConvBERT model)
- ctrl β CTRLForSequenceClassification (CTRL model)
- data2vec-text β Data2VecTextForSequenceClassification (Data2VecText model)
- deberta β DebertaForSequenceClassification (DeBERTa model)
- deberta-v2 β DebertaV2ForSequenceClassification (DeBERTa-v2 model)
- distilbert β DistilBertForSequenceClassification (DistilBERT model)
- electra β ElectraForSequenceClassification (ELECTRA model)
- ernie β ErnieForSequenceClassification (ERNIE model)
- ernie_m β ErnieMForSequenceClassification (ErnieM model)
- esm β EsmForSequenceClassification (ESM model)
- falcon β FalconForSequenceClassification (Falcon model)
- flaubert β FlaubertForSequenceClassification (FlauBERT model)
- fnet β FNetForSequenceClassification (FNet model)
- funnel β FunnelForSequenceClassification (Funnel Transformer model)
- gemma β GemmaForSequenceClassification (Gemma model)
- gemma2 β Gemma2ForSequenceClassification (Gemma2 model)
- glm β GlmForSequenceClassification (GLM model)
- gpt-sw3 β GPT2ForSequenceClassification (GPT-Sw3 model)
- gpt2 β GPT2ForSequenceClassification (OpenAI GPT-2 model)
- gpt_bigcode β GPTBigCodeForSequenceClassification (GPTBigCode model)
- gpt_neo β GPTNeoForSequenceClassification (GPT Neo model)
- gpt_neox β GPTNeoXForSequenceClassification (GPT NeoX model)
- gptj β GPTJForSequenceClassification (GPT-J model)
- ibert β IBertForSequenceClassification (I-BERT model)
- jamba β JambaForSequenceClassification (Jamba model)
- jetmoe β JetMoeForSequenceClassification (JetMoe model)
- layoutlm β LayoutLMForSequenceClassification (LayoutLM model)
- layoutlmv2 β LayoutLMv2ForSequenceClassification (LayoutLMv2 model)
- layoutlmv3 β LayoutLMv3ForSequenceClassification (LayoutLMv3 model)
- led β LEDForSequenceClassification (LED model)
- lilt β LiltForSequenceClassification (LiLT model)
- llama β LlamaForSequenceClassification (LLaMA model)
- longformer β LongformerForSequenceClassification (Longformer model)
- luke β LukeForSequenceClassification (LUKE model)
- markuplm β MarkupLMForSequenceClassification (MarkupLM model)
- mbart β MBartForSequenceClassification (mBART model)
- mega β MegaForSequenceClassification (MEGA model)
- megatron-bert β MegatronBertForSequenceClassification (Megatron-BERT model)
- mistral β MistralForSequenceClassification (Mistral model)
- mixtral β MixtralForSequenceClassification (Mixtral model)
- mobilebert β MobileBertForSequenceClassification (MobileBERT model)
- modernbert β ModernBertForSequenceClassification (ModernBERT model)
- mpnet β MPNetForSequenceClassification (MPNet model)
- mpt β MptForSequenceClassification (MPT model)
- mra β MraForSequenceClassification (MRA model)
- mt5 β MT5ForSequenceClassification (MT5 model)
- mvp β MvpForSequenceClassification (MVP model)
- nemotron β NemotronForSequenceClassification (Nemotron model)
- nezha β NezhaForSequenceClassification (Nezha model)
- nystromformer β NystromformerForSequenceClassification (NystrΓΆmformer model)
- open-llama β OpenLlamaForSequenceClassification (OpenLlama model)
- openai-gpt β OpenAIGPTForSequenceClassification (OpenAI GPT model)
- opt β OPTForSequenceClassification (OPT model)
- perceiver β PerceiverForSequenceClassification (Perceiver model)
- persimmon β PersimmonForSequenceClassification (Persimmon model)
- phi β PhiForSequenceClassification (Phi model)
- phi3 β Phi3ForSequenceClassification (Phi3 model)
- phimoe β PhimoeForSequenceClassification (Phimoe model)
- plbart β PLBartForSequenceClassification (PLBart model)
- qdqbert β QDQBertForSequenceClassification (QDQBert model)
- qwen2 β Qwen2ForSequenceClassification (Qwen2 model)
- qwen2_moe β Qwen2MoeForSequenceClassification (Qwen2MoE model)
- reformer β ReformerForSequenceClassification (Reformer model)
- rembert β RemBertForSequenceClassification (RemBERT model)
- roberta β RobertaForSequenceClassification (RoBERTa model)
- roberta-prelayernorm β RobertaPreLayerNormForSequenceClassification (RoBERTa-PreLayerNorm model)
- roc_bert β RoCBertForSequenceClassification (RoCBert model)
- roformer β RoFormerForSequenceClassification (RoFormer model)
- squeezebert β SqueezeBertForSequenceClassification (SqueezeBERT model)
- stablelm β StableLmForSequenceClassification (StableLm model)
- starcoder2 β Starcoder2ForSequenceClassification (Starcoder2 model)
- t5 β T5ForSequenceClassification (T5 model)
- tapas β TapasForSequenceClassification (TAPAS model)
- transfo-xl β TransfoXLForSequenceClassification (Transformer-XL model)
- umt5 β UMT5ForSequenceClassification (UMT5 model)
- xlm β XLMForSequenceClassification (XLM model)
- xlm-roberta β XLMRobertaForSequenceClassification (XLM-RoBERTa model)
- xlm-roberta-xl β XLMRobertaXLForSequenceClassification (XLM-RoBERTa-XL model)
- xlnet β XLNetForSequenceClassification (XLNet model)
- xmod β XmodForSequenceClassification (X-MOD model)
- yoso β YosoForSequenceClassification (YOSO model)
- zamba β ZambaForSequenceClassification (Zamba model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForSequenceClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForSequenceClassification.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForSequenceClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a sequence classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: TFAlbertForSequenceClassification (ALBERT model)
- BartConfig configuration class: TFBartForSequenceClassification (BART model)
- BertConfig configuration class: TFBertForSequenceClassification (BERT model)
- CTRLConfig configuration class: TFCTRLForSequenceClassification (CTRL model)
- CamembertConfig configuration class: TFCamembertForSequenceClassification (CamemBERT model)
- ConvBertConfig configuration class: TFConvBertForSequenceClassification (ConvBERT model)
- DebertaConfig configuration class: TFDebertaForSequenceClassification (DeBERTa model)
- DebertaV2Config configuration class: TFDebertaV2ForSequenceClassification (DeBERTa-v2 model)
- DistilBertConfig configuration class: TFDistilBertForSequenceClassification (DistilBERT model)
- ElectraConfig configuration class: TFElectraForSequenceClassification (ELECTRA model)
- EsmConfig configuration class: TFEsmForSequenceClassification (ESM model)
- FlaubertConfig configuration class: TFFlaubertForSequenceClassification (FlauBERT model)
- FunnelConfig configuration class: TFFunnelForSequenceClassification (Funnel Transformer model)
- GPT2Config configuration class: TFGPT2ForSequenceClassification (OpenAI GPT-2 model)
- GPTJConfig configuration class: TFGPTJForSequenceClassification (GPT-J model)
- LayoutLMConfig configuration class: TFLayoutLMForSequenceClassification (LayoutLM model)
- LayoutLMv3Config configuration class: TFLayoutLMv3ForSequenceClassification (LayoutLMv3 model)
- LongformerConfig configuration class: TFLongformerForSequenceClassification (Longformer model)
- MPNetConfig configuration class: TFMPNetForSequenceClassification (MPNet model)
- MistralConfig configuration class: TFMistralForSequenceClassification (Mistral model)
- MobileBertConfig configuration class: TFMobileBertForSequenceClassification (MobileBERT model)
- OpenAIGPTConfig configuration class: TFOpenAIGPTForSequenceClassification (OpenAI GPT model)
- RemBertConfig configuration class: TFRemBertForSequenceClassification (RemBERT model)
- RoFormerConfig configuration class: TFRoFormerForSequenceClassification (RoFormer model)
- RobertaConfig configuration class: TFRobertaForSequenceClassification (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: TFRobertaPreLayerNormForSequenceClassification (RoBERTa-PreLayerNorm model)
- TapasConfig configuration class: TFTapasForSequenceClassification (TAPAS model)
- TransfoXLConfig configuration class: TFTransfoXLForSequenceClassification (Transformer-XL model)
- XLMConfig configuration class: TFXLMForSequenceClassification (XLM model)
- XLMRobertaConfig configuration class: TFXLMRobertaForSequenceClassification (XLM-RoBERTa model)
- XLNetConfig configuration class: TFXLNetForSequenceClassification (XLNet model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a sequence classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a sequence classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β TFAlbertForSequenceClassification (ALBERT model)
- bart β TFBartForSequenceClassification (BART model)
- bert β TFBertForSequenceClassification (BERT model)
- camembert β TFCamembertForSequenceClassification (CamemBERT model)
- convbert β TFConvBertForSequenceClassification (ConvBERT model)
- ctrl β TFCTRLForSequenceClassification (CTRL model)
- deberta β TFDebertaForSequenceClassification (DeBERTa model)
- deberta-v2 β TFDebertaV2ForSequenceClassification (DeBERTa-v2 model)
- distilbert β TFDistilBertForSequenceClassification (DistilBERT model)
- electra β TFElectraForSequenceClassification (ELECTRA model)
- esm β TFEsmForSequenceClassification (ESM model)
- flaubert β TFFlaubertForSequenceClassification (FlauBERT model)
- funnel β TFFunnelForSequenceClassification (Funnel Transformer model)
- gpt-sw3 β TFGPT2ForSequenceClassification (GPT-Sw3 model)
- gpt2 β TFGPT2ForSequenceClassification (OpenAI GPT-2 model)
- gptj β TFGPTJForSequenceClassification (GPT-J model)
- layoutlm β TFLayoutLMForSequenceClassification (LayoutLM model)
- layoutlmv3 β TFLayoutLMv3ForSequenceClassification (LayoutLMv3 model)
- longformer β TFLongformerForSequenceClassification (Longformer model)
- mistral β TFMistralForSequenceClassification (Mistral model)
- mobilebert β TFMobileBertForSequenceClassification (MobileBERT model)
- mpnet β TFMPNetForSequenceClassification (MPNet model)
- openai-gpt β TFOpenAIGPTForSequenceClassification (OpenAI GPT model)
- rembert β TFRemBertForSequenceClassification (RemBERT model)
- roberta β TFRobertaForSequenceClassification (RoBERTa model)
- roberta-prelayernorm β TFRobertaPreLayerNormForSequenceClassification (RoBERTa-PreLayerNorm model)
- roformer β TFRoFormerForSequenceClassification (RoFormer model)
- tapas β TFTapasForSequenceClassification (TAPAS model)
- transfo-xl β TFTransfoXLForSequenceClassification (Transformer-XL model)
- xlm β TFXLMForSequenceClassification (XLM model)
- xlm-roberta β TFXLMRobertaForSequenceClassification (XLM-RoBERTa model)
- xlnet β TFXLNetForSequenceClassification (XLNet model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForSequenceClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForSequenceClassification.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForSequenceClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a sequence classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: FlaxAlbertForSequenceClassification (ALBERT model)
- BartConfig configuration class: FlaxBartForSequenceClassification (BART model)
- BertConfig configuration class: FlaxBertForSequenceClassification (BERT model)
- BigBirdConfig configuration class: FlaxBigBirdForSequenceClassification (BigBird model)
- DistilBertConfig configuration class: FlaxDistilBertForSequenceClassification (DistilBERT model)
- ElectraConfig configuration class: FlaxElectraForSequenceClassification (ELECTRA model)
- MBartConfig configuration class: FlaxMBartForSequenceClassification (mBART model)
- RoFormerConfig configuration class: FlaxRoFormerForSequenceClassification (RoFormer model)
- RobertaConfig configuration class: FlaxRobertaForSequenceClassification (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: FlaxRobertaPreLayerNormForSequenceClassification (RoBERTa-PreLayerNorm model)
- XLMRobertaConfig configuration class: FlaxXLMRobertaForSequenceClassification (XLM-RoBERTa model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a sequence classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a sequence classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β FlaxAlbertForSequenceClassification (ALBERT model)
- bart β FlaxBartForSequenceClassification (BART model)
- bert β FlaxBertForSequenceClassification (BERT model)
- big_bird β FlaxBigBirdForSequenceClassification (BigBird model)
- distilbert β FlaxDistilBertForSequenceClassification (DistilBERT model)
- electra β FlaxElectraForSequenceClassification (ELECTRA model)
- mbart β FlaxMBartForSequenceClassification (mBART model)
- roberta β FlaxRobertaForSequenceClassification (RoBERTa model)
- roberta-prelayernorm β FlaxRobertaPreLayerNormForSequenceClassification (RoBERTa-PreLayerNorm model)
- roformer β FlaxRoFormerForSequenceClassification (RoFormer model)
- xlm-roberta β FlaxXLMRobertaForSequenceClassification (XLM-RoBERTa model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForSequenceClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForSequenceClassification.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForMultipleChoice
This is a generic model class that will be instantiated as one of the model classes of the library (with a multiple choice head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: AlbertForMultipleChoice (ALBERT model)
- BertConfig configuration class: BertForMultipleChoice (BERT model)
- BigBirdConfig configuration class: BigBirdForMultipleChoice (BigBird model)
- CamembertConfig configuration class: CamembertForMultipleChoice (CamemBERT model)
- CanineConfig configuration class: CanineForMultipleChoice (CANINE model)
- ConvBertConfig configuration class: ConvBertForMultipleChoice (ConvBERT model)
- Data2VecTextConfig configuration class: Data2VecTextForMultipleChoice (Data2VecText model)
- DebertaV2Config configuration class: DebertaV2ForMultipleChoice (DeBERTa-v2 model)
- DistilBertConfig configuration class: DistilBertForMultipleChoice (DistilBERT model)
- ElectraConfig configuration class: ElectraForMultipleChoice (ELECTRA model)
- ErnieConfig configuration class: ErnieForMultipleChoice (ERNIE model)
- ErnieMConfig configuration class: ErnieMForMultipleChoice (ErnieM model)
- FNetConfig configuration class: FNetForMultipleChoice (FNet model)
- FlaubertConfig configuration class: FlaubertForMultipleChoice (FlauBERT model)
- FunnelConfig configuration class: FunnelForMultipleChoice (Funnel Transformer model)
- IBertConfig configuration class: IBertForMultipleChoice (I-BERT model)
- LongformerConfig configuration class: LongformerForMultipleChoice (Longformer model)
- LukeConfig configuration class: LukeForMultipleChoice (LUKE model)
- MPNetConfig configuration class: MPNetForMultipleChoice (MPNet model)
- MegaConfig configuration class: MegaForMultipleChoice (MEGA model)
- MegatronBertConfig configuration class: MegatronBertForMultipleChoice (Megatron-BERT model)
- MobileBertConfig configuration class: MobileBertForMultipleChoice (MobileBERT model)
- MraConfig configuration class: MraForMultipleChoice (MRA model)
- NezhaConfig configuration class: NezhaForMultipleChoice (Nezha model)
- NystromformerConfig configuration class: NystromformerForMultipleChoice (Nyströmformer model)
- QDQBertConfig configuration class: QDQBertForMultipleChoice (QDQBert model)
- RemBertConfig configuration class: RemBertForMultipleChoice (RemBERT model)
- RoCBertConfig configuration class: RoCBertForMultipleChoice (RoCBert model)
- RoFormerConfig configuration class: RoFormerForMultipleChoice (RoFormer model)
- RobertaConfig configuration class: RobertaForMultipleChoice (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: RobertaPreLayerNormForMultipleChoice (RoBERTa-PreLayerNorm model)
- SqueezeBertConfig configuration class: SqueezeBertForMultipleChoice (SqueezeBERT model)
- XLMConfig configuration class: XLMForMultipleChoice (XLM model)
- XLMRobertaConfig configuration class: XLMRobertaForMultipleChoice (XLM-RoBERTa model)
- XLMRobertaXLConfig configuration class: XLMRobertaXLForMultipleChoice (XLM-RoBERTa-XL model)
- XLNetConfig configuration class: XLNetForMultipleChoice (XLNet model)
- XmodConfig configuration class: XmodForMultipleChoice (X-MOD model)
- YosoConfig configuration class: YosoForMultipleChoice (YOSO model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a multiple choice head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a multiple choice head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β AlbertForMultipleChoice (ALBERT model)
- bert β BertForMultipleChoice (BERT model)
- big_bird β BigBirdForMultipleChoice (BigBird model)
- camembert β CamembertForMultipleChoice (CamemBERT model)
- canine β CanineForMultipleChoice (CANINE model)
- convbert β ConvBertForMultipleChoice (ConvBERT model)
- data2vec-text β Data2VecTextForMultipleChoice (Data2VecText model)
- deberta-v2 β DebertaV2ForMultipleChoice (DeBERTa-v2 model)
- distilbert β DistilBertForMultipleChoice (DistilBERT model)
- electra β ElectraForMultipleChoice (ELECTRA model)
- ernie β ErnieForMultipleChoice (ERNIE model)
- ernie_m β ErnieMForMultipleChoice (ErnieM model)
- flaubert β FlaubertForMultipleChoice (FlauBERT model)
- fnet β FNetForMultipleChoice (FNet model)
- funnel β FunnelForMultipleChoice (Funnel Transformer model)
- ibert β IBertForMultipleChoice (I-BERT model)
- longformer β LongformerForMultipleChoice (Longformer model)
- luke β LukeForMultipleChoice (LUKE model)
- mega β MegaForMultipleChoice (MEGA model)
- megatron-bert β MegatronBertForMultipleChoice (Megatron-BERT model)
- mobilebert β MobileBertForMultipleChoice (MobileBERT model)
- mpnet β MPNetForMultipleChoice (MPNet model)
- mra β MraForMultipleChoice (MRA model)
- nezha β NezhaForMultipleChoice (Nezha model)
- nystromformer β NystromformerForMultipleChoice (NystrΓΆmformer model)
- qdqbert β QDQBertForMultipleChoice (QDQBert model)
- rembert β RemBertForMultipleChoice (RemBERT model)
- roberta β RobertaForMultipleChoice (RoBERTa model)
- roberta-prelayernorm β RobertaPreLayerNormForMultipleChoice (RoBERTa-PreLayerNorm model)
- roc_bert β RoCBertForMultipleChoice (RoCBert model)
- roformer β RoFormerForMultipleChoice (RoFormer model)
- squeezebert β SqueezeBertForMultipleChoice (SqueezeBERT model)
- xlm β XLMForMultipleChoice (XLM model)
- xlm-roberta β XLMRobertaForMultipleChoice (XLM-RoBERTa model)
- xlm-roberta-xl β XLMRobertaXLForMultipleChoice (XLM-RoBERTa-XL model)
- xlnet β XLNetForMultipleChoice (XLNet model)
- xmod β XmodForMultipleChoice (X-MOD model)
- yoso β YosoForMultipleChoice (YOSO model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForMultipleChoice
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForMultipleChoice.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForMultipleChoice
This is a generic model class that will be instantiated as one of the model classes of the library (with a multiple choice head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: TFAlbertForMultipleChoice (ALBERT model)
- BertConfig configuration class: TFBertForMultipleChoice (BERT model)
- CamembertConfig configuration class: TFCamembertForMultipleChoice (CamemBERT model)
- ConvBertConfig configuration class: TFConvBertForMultipleChoice (ConvBERT model)
- DebertaV2Config configuration class: TFDebertaV2ForMultipleChoice (DeBERTa-v2 model)
- DistilBertConfig configuration class: TFDistilBertForMultipleChoice (DistilBERT model)
- ElectraConfig configuration class: TFElectraForMultipleChoice (ELECTRA model)
- FlaubertConfig configuration class: TFFlaubertForMultipleChoice (FlauBERT model)
- FunnelConfig configuration class: TFFunnelForMultipleChoice (Funnel Transformer model)
- LongformerConfig configuration class: TFLongformerForMultipleChoice (Longformer model)
- MPNetConfig configuration class: TFMPNetForMultipleChoice (MPNet model)
- MobileBertConfig configuration class: TFMobileBertForMultipleChoice (MobileBERT model)
- RemBertConfig configuration class: TFRemBertForMultipleChoice (RemBERT model)
- RoFormerConfig configuration class: TFRoFormerForMultipleChoice (RoFormer model)
- RobertaConfig configuration class: TFRobertaForMultipleChoice (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: TFRobertaPreLayerNormForMultipleChoice (RoBERTa-PreLayerNorm model)
- XLMConfig configuration class: TFXLMForMultipleChoice (XLM model)
- XLMRobertaConfig configuration class: TFXLMRobertaForMultipleChoice (XLM-RoBERTa model)
- XLNetConfig configuration class: TFXLNetForMultipleChoice (XLNet model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a multiple choice head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a multiple choice head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β TFAlbertForMultipleChoice (ALBERT model)
- bert β TFBertForMultipleChoice (BERT model)
- camembert β TFCamembertForMultipleChoice (CamemBERT model)
- convbert β TFConvBertForMultipleChoice (ConvBERT model)
- deberta-v2 β TFDebertaV2ForMultipleChoice (DeBERTa-v2 model)
- distilbert β TFDistilBertForMultipleChoice (DistilBERT model)
- electra β TFElectraForMultipleChoice (ELECTRA model)
- flaubert β TFFlaubertForMultipleChoice (FlauBERT model)
- funnel β TFFunnelForMultipleChoice (Funnel Transformer model)
- longformer β TFLongformerForMultipleChoice (Longformer model)
- mobilebert β TFMobileBertForMultipleChoice (MobileBERT model)
- mpnet β TFMPNetForMultipleChoice (MPNet model)
- rembert β TFRemBertForMultipleChoice (RemBERT model)
- roberta β TFRobertaForMultipleChoice (RoBERTa model)
- roberta-prelayernorm β TFRobertaPreLayerNormForMultipleChoice (RoBERTa-PreLayerNorm model)
- roformer β TFRoFormerForMultipleChoice (RoFormer model)
- xlm β TFXLMForMultipleChoice (XLM model)
- xlm-roberta β TFXLMRobertaForMultipleChoice (XLM-RoBERTa model)
- xlnet β TFXLNetForMultipleChoice (XLNet model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForMultipleChoice
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForMultipleChoice.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForMultipleChoice
This is a generic model class that will be instantiated as one of the model classes of the library (with a multiple choice head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: FlaxAlbertForMultipleChoice (ALBERT model)
- BertConfig configuration class: FlaxBertForMultipleChoice (BERT model)
- BigBirdConfig configuration class: FlaxBigBirdForMultipleChoice (BigBird model)
- DistilBertConfig configuration class: FlaxDistilBertForMultipleChoice (DistilBERT model)
- ElectraConfig configuration class: FlaxElectraForMultipleChoice (ELECTRA model)
- RoFormerConfig configuration class: FlaxRoFormerForMultipleChoice (RoFormer model)
- RobertaConfig configuration class: FlaxRobertaForMultipleChoice (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: FlaxRobertaPreLayerNormForMultipleChoice (RoBERTa-PreLayerNorm model)
- XLMRobertaConfig configuration class: FlaxXLMRobertaForMultipleChoice (XLM-RoBERTa model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a multiple choice head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a multiple choice head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β FlaxAlbertForMultipleChoice (ALBERT model)
- bert β FlaxBertForMultipleChoice (BERT model)
- big_bird β FlaxBigBirdForMultipleChoice (BigBird model)
- distilbert β FlaxDistilBertForMultipleChoice (DistilBERT model)
- electra β FlaxElectraForMultipleChoice (ELECTRA model)
- roberta β FlaxRobertaForMultipleChoice (RoBERTa model)
- roberta-prelayernorm β FlaxRobertaPreLayerNormForMultipleChoice (RoBERTa-PreLayerNorm model)
- roformer β FlaxRoFormerForMultipleChoice (RoFormer model)
- xlm-roberta β FlaxXLMRobertaForMultipleChoice (XLM-RoBERTa model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForMultipleChoice
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForMultipleChoice.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForMultipleChoice.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForNextSentencePrediction
This is a generic model class that will be instantiated as one of the model classes of the library (with a next sentence prediction head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BertConfig configuration class: BertForNextSentencePrediction (BERT model)
- ErnieConfig configuration class: ErnieForNextSentencePrediction (ERNIE model)
- FNetConfig configuration class: FNetForNextSentencePrediction (FNet model)
- MegatronBertConfig configuration class: MegatronBertForNextSentencePrediction (Megatron-BERT model)
- MobileBertConfig configuration class: MobileBertForNextSentencePrediction (MobileBERT model)
- NezhaConfig configuration class: NezhaForNextSentencePrediction (Nezha model)
- QDQBertConfig configuration class: QDQBertForNextSentencePrediction (QDQBert model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a next sentence prediction head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a next sentence prediction head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- bert β BertForNextSentencePrediction (BERT model)
- ernie β ErnieForNextSentencePrediction (ERNIE model)
- fnet β FNetForNextSentencePrediction (FNet model)
- megatron-bert β MegatronBertForNextSentencePrediction (Megatron-BERT model)
- mobilebert β MobileBertForNextSentencePrediction (MobileBERT model)
- nezha β NezhaForNextSentencePrediction (Nezha model)
- qdqbert β QDQBertForNextSentencePrediction (QDQBert model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForNextSentencePrediction
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForNextSentencePrediction.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForNextSentencePrediction.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForNextSentencePrediction.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForNextSentencePrediction
This is a generic model class that will be instantiated as one of the model classes of the library (with a next sentence prediction head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BertConfig configuration class: TFBertForNextSentencePrediction (BERT model)
- MobileBertConfig configuration class: TFMobileBertForNextSentencePrediction (MobileBERT model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a next sentence prediction head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a next sentence prediction head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- bert β TFBertForNextSentencePrediction (BERT model)
- mobilebert β TFMobileBertForNextSentencePrediction (MobileBERT model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForNextSentencePrediction
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForNextSentencePrediction.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForNextSentencePrediction.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForNextSentencePrediction.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForNextSentencePrediction
This is a generic model class that will be instantiated as one of the model classes of the library (with a next sentence prediction head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BertConfig configuration class: FlaxBertForNextSentencePrediction (BERT model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a next sentence prediction head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a next sentence prediction head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- bert β FlaxBertForNextSentencePrediction (BERT model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForNextSentencePrediction
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForNextSentencePrediction.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForNextSentencePrediction.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForNextSentencePrediction.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForTokenClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a token classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: AlbertForTokenClassification (ALBERT model)
- BertConfig configuration class: BertForTokenClassification (BERT model)
- BigBirdConfig configuration class: BigBirdForTokenClassification (BigBird model)
- BioGptConfig configuration class: BioGptForTokenClassification (BioGpt model)
- BloomConfig configuration class: BloomForTokenClassification (BLOOM model)
- BrosConfig configuration class: BrosForTokenClassification (BROS model)
- CamembertConfig configuration class: CamembertForTokenClassification (CamemBERT model)
- CanineConfig configuration class: CanineForTokenClassification (CANINE model)
- ConvBertConfig configuration class: ConvBertForTokenClassification (ConvBERT model)
- Data2VecTextConfig configuration class: Data2VecTextForTokenClassification (Data2VecText model)
- DebertaConfig configuration class: DebertaForTokenClassification (DeBERTa model)
- DebertaV2Config configuration class: DebertaV2ForTokenClassification (DeBERTa-v2 model)
- DistilBertConfig configuration class: DistilBertForTokenClassification (DistilBERT model)
- ElectraConfig configuration class: ElectraForTokenClassification (ELECTRA model)
- ErnieConfig configuration class: ErnieForTokenClassification (ERNIE model)
- ErnieMConfig configuration class: ErnieMForTokenClassification (ErnieM model)
- EsmConfig configuration class: EsmForTokenClassification (ESM model)
- FNetConfig configuration class: FNetForTokenClassification (FNet model)
- FalconConfig configuration class: FalconForTokenClassification (Falcon model)
- FlaubertConfig configuration class: FlaubertForTokenClassification (FlauBERT model)
- FunnelConfig configuration class: FunnelForTokenClassification (Funnel Transformer model)
- GPT2Config configuration class: GPT2ForTokenClassification (OpenAI GPT-2 model)
- GPTBigCodeConfig configuration class: GPTBigCodeForTokenClassification (GPTBigCode model)
- GPTNeoConfig configuration class: GPTNeoForTokenClassification (GPT Neo model)
- GPTNeoXConfig configuration class: GPTNeoXForTokenClassification (GPT NeoX model)
- Gemma2Config configuration class: Gemma2ForTokenClassification (Gemma2 model)
- GemmaConfig configuration class: GemmaForTokenClassification (Gemma model)
- GlmConfig configuration class: GlmForTokenClassification (GLM model)
- IBertConfig configuration class: IBertForTokenClassification (I-BERT model)
- LayoutLMConfig configuration class: LayoutLMForTokenClassification (LayoutLM model)
- LayoutLMv2Config configuration class: LayoutLMv2ForTokenClassification (LayoutLMv2 model)
- LayoutLMv3Config configuration class: LayoutLMv3ForTokenClassification (LayoutLMv3 model)
- LiltConfig configuration class: LiltForTokenClassification (LiLT model)
- LlamaConfig configuration class: LlamaForTokenClassification (LLaMA model)
- LongformerConfig configuration class: LongformerForTokenClassification (Longformer model)
- LukeConfig configuration class: LukeForTokenClassification (LUKE model)
- MPNetConfig configuration class: MPNetForTokenClassification (MPNet model)
- MT5Config configuration class: MT5ForTokenClassification (MT5 model)
- MarkupLMConfig configuration class: MarkupLMForTokenClassification (MarkupLM model)
- MegaConfig configuration class: MegaForTokenClassification (MEGA model)
- MegatronBertConfig configuration class: MegatronBertForTokenClassification (Megatron-BERT model)
- MistralConfig configuration class: MistralForTokenClassification (Mistral model)
- MixtralConfig configuration class: MixtralForTokenClassification (Mixtral model)
- MobileBertConfig configuration class: MobileBertForTokenClassification (MobileBERT model)
- ModernBertConfig configuration class: ModernBertForTokenClassification (ModernBERT model)
- MptConfig configuration class: MptForTokenClassification (MPT model)
- MraConfig configuration class: MraForTokenClassification (MRA model)
- NemotronConfig configuration class: NemotronForTokenClassification (Nemotron model)
- NezhaConfig configuration class: NezhaForTokenClassification (Nezha model)
- NystromformerConfig configuration class: NystromformerForTokenClassification (Nyströmformer model)
- PersimmonConfig configuration class: PersimmonForTokenClassification (Persimmon model)
- Phi3Config configuration class: Phi3ForTokenClassification (Phi3 model)
- PhiConfig configuration class: PhiForTokenClassification (Phi model)
- QDQBertConfig configuration class: QDQBertForTokenClassification (QDQBert model)
- Qwen2Config configuration class: Qwen2ForTokenClassification (Qwen2 model)
- Qwen2MoeConfig configuration class: Qwen2MoeForTokenClassification (Qwen2MoE model)
- RemBertConfig configuration class: RemBertForTokenClassification (RemBERT model)
- RoCBertConfig configuration class: RoCBertForTokenClassification (RoCBert model)
- RoFormerConfig configuration class: RoFormerForTokenClassification (RoFormer model)
- RobertaConfig configuration class: RobertaForTokenClassification (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: RobertaPreLayerNormForTokenClassification (RoBERTa-PreLayerNorm model)
- SqueezeBertConfig configuration class: SqueezeBertForTokenClassification (SqueezeBERT model)
- StableLmConfig configuration class: StableLmForTokenClassification (StableLm model)
- Starcoder2Config configuration class: Starcoder2ForTokenClassification (Starcoder2 model)
- T5Config configuration class: T5ForTokenClassification (T5 model)
- UMT5Config configuration class: UMT5ForTokenClassification (UMT5 model)
- XLMConfig configuration class: XLMForTokenClassification (XLM model)
- XLMRobertaConfig configuration class: XLMRobertaForTokenClassification (XLM-RoBERTa model)
- XLMRobertaXLConfig configuration class: XLMRobertaXLForTokenClassification (XLM-RoBERTa-XL model)
- XLNetConfig configuration class: XLNetForTokenClassification (XLNet model)
- XmodConfig configuration class: XmodForTokenClassification (X-MOD model)
- YosoConfig configuration class: YosoForTokenClassification (YOSO model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a token classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a token classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β AlbertForTokenClassification (ALBERT model)
- bert β BertForTokenClassification (BERT model)
- big_bird β BigBirdForTokenClassification (BigBird model)
- biogpt β BioGptForTokenClassification (BioGpt model)
- bloom β BloomForTokenClassification (BLOOM model)
- bros β BrosForTokenClassification (BROS model)
- camembert β CamembertForTokenClassification (CamemBERT model)
- canine β CanineForTokenClassification (CANINE model)
- convbert β ConvBertForTokenClassification (ConvBERT model)
- data2vec-text β Data2VecTextForTokenClassification (Data2VecText model)
- deberta β DebertaForTokenClassification (DeBERTa model)
- deberta-v2 β DebertaV2ForTokenClassification (DeBERTa-v2 model)
- distilbert β DistilBertForTokenClassification (DistilBERT model)
- electra β ElectraForTokenClassification (ELECTRA model)
- ernie β ErnieForTokenClassification (ERNIE model)
- ernie_m β ErnieMForTokenClassification (ErnieM model)
- esm β EsmForTokenClassification (ESM model)
- falcon β FalconForTokenClassification (Falcon model)
- flaubert β FlaubertForTokenClassification (FlauBERT model)
- fnet β FNetForTokenClassification (FNet model)
- funnel β FunnelForTokenClassification (Funnel Transformer model)
- gemma β GemmaForTokenClassification (Gemma model)
- gemma2 β Gemma2ForTokenClassification (Gemma2 model)
- glm β GlmForTokenClassification (GLM model)
- gpt-sw3 β GPT2ForTokenClassification (GPT-Sw3 model)
- gpt2 β GPT2ForTokenClassification (OpenAI GPT-2 model)
- gpt_bigcode β GPTBigCodeForTokenClassification (GPTBigCode model)
- gpt_neo β GPTNeoForTokenClassification (GPT Neo model)
- gpt_neox β GPTNeoXForTokenClassification (GPT NeoX model)
- ibert β IBertForTokenClassification (I-BERT model)
- layoutlm β LayoutLMForTokenClassification (LayoutLM model)
- layoutlmv2 β LayoutLMv2ForTokenClassification (LayoutLMv2 model)
- layoutlmv3 β LayoutLMv3ForTokenClassification (LayoutLMv3 model)
- lilt β LiltForTokenClassification (LiLT model)
- llama β LlamaForTokenClassification (LLaMA model)
- longformer β LongformerForTokenClassification (Longformer model)
- luke β LukeForTokenClassification (LUKE model)
- markuplm β MarkupLMForTokenClassification (MarkupLM model)
- mega β MegaForTokenClassification (MEGA model)
- megatron-bert β MegatronBertForTokenClassification (Megatron-BERT model)
- mistral β MistralForTokenClassification (Mistral model)
- mixtral β MixtralForTokenClassification (Mixtral model)
- mobilebert β MobileBertForTokenClassification (MobileBERT model)
- modernbert β ModernBertForTokenClassification (ModernBERT model)
- mpnet β MPNetForTokenClassification (MPNet model)
- mpt β MptForTokenClassification (MPT model)
- mra β MraForTokenClassification (MRA model)
- mt5 β MT5ForTokenClassification (MT5 model)
- nemotron β NemotronForTokenClassification (Nemotron model)
- nezha β NezhaForTokenClassification (Nezha model)
- nystromformer β NystromformerForTokenClassification (NystrΓΆmformer model)
- persimmon β PersimmonForTokenClassification (Persimmon model)
- phi β PhiForTokenClassification (Phi model)
- phi3 β Phi3ForTokenClassification (Phi3 model)
- qdqbert β QDQBertForTokenClassification (QDQBert model)
- qwen2 β Qwen2ForTokenClassification (Qwen2 model)
- qwen2_moe β Qwen2MoeForTokenClassification (Qwen2MoE model)
- rembert β RemBertForTokenClassification (RemBERT model)
- roberta β RobertaForTokenClassification (RoBERTa model)
- roberta-prelayernorm β RobertaPreLayerNormForTokenClassification (RoBERTa-PreLayerNorm model)
- roc_bert β RoCBertForTokenClassification (RoCBert model)
- roformer β RoFormerForTokenClassification (RoFormer model)
- squeezebert β SqueezeBertForTokenClassification (SqueezeBERT model)
- stablelm β StableLmForTokenClassification (StableLm model)
- starcoder2 β Starcoder2ForTokenClassification (Starcoder2 model)
- t5 β T5ForTokenClassification (T5 model)
- umt5 β UMT5ForTokenClassification (UMT5 model)
- xlm β XLMForTokenClassification (XLM model)
- xlm-roberta β XLMRobertaForTokenClassification (XLM-RoBERTa model)
- xlm-roberta-xl β XLMRobertaXLForTokenClassification (XLM-RoBERTa-XL model)
- xlnet β XLNetForTokenClassification (XLNet model)
- xmod β XmodForTokenClassification (X-MOD model)
- yoso β YosoForTokenClassification (YOSO model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForTokenClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForTokenClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForTokenClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForTokenClassification.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForTokenClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a token classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: TFAlbertForTokenClassification (ALBERT model)
- BertConfig configuration class: TFBertForTokenClassification (BERT model)
- CamembertConfig configuration class: TFCamembertForTokenClassification (CamemBERT model)
- ConvBertConfig configuration class: TFConvBertForTokenClassification (ConvBERT model)
- DebertaConfig configuration class: TFDebertaForTokenClassification (DeBERTa model)
- DebertaV2Config configuration class: TFDebertaV2ForTokenClassification (DeBERTa-v2 model)
- DistilBertConfig configuration class: TFDistilBertForTokenClassification (DistilBERT model)
- ElectraConfig configuration class: TFElectraForTokenClassification (ELECTRA model)
- EsmConfig configuration class: TFEsmForTokenClassification (ESM model)
- FlaubertConfig configuration class: TFFlaubertForTokenClassification (FlauBERT model)
- FunnelConfig configuration class: TFFunnelForTokenClassification (Funnel Transformer model)
- LayoutLMConfig configuration class: TFLayoutLMForTokenClassification (LayoutLM model)
- LayoutLMv3Config configuration class: TFLayoutLMv3ForTokenClassification (LayoutLMv3 model)
- LongformerConfig configuration class: TFLongformerForTokenClassification (Longformer model)
- MPNetConfig configuration class: TFMPNetForTokenClassification (MPNet model)
- MobileBertConfig configuration class: TFMobileBertForTokenClassification (MobileBERT model)
- RemBertConfig configuration class: TFRemBertForTokenClassification (RemBERT model)
- RoFormerConfig configuration class: TFRoFormerForTokenClassification (RoFormer model)
- RobertaConfig configuration class: TFRobertaForTokenClassification (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: TFRobertaPreLayerNormForTokenClassification (RoBERTa-PreLayerNorm model)
- XLMConfig configuration class: TFXLMForTokenClassification (XLM model)
- XLMRobertaConfig configuration class: TFXLMRobertaForTokenClassification (XLM-RoBERTa model)
- XLNetConfig configuration class: TFXLNetForTokenClassification (XLNet model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a token classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a token classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β TFAlbertForTokenClassification (ALBERT model)
- bert β TFBertForTokenClassification (BERT model)
- camembert β TFCamembertForTokenClassification (CamemBERT model)
- convbert β TFConvBertForTokenClassification (ConvBERT model)
- deberta β TFDebertaForTokenClassification (DeBERTa model)
- deberta-v2 β TFDebertaV2ForTokenClassification (DeBERTa-v2 model)
- distilbert β TFDistilBertForTokenClassification (DistilBERT model)
- electra β TFElectraForTokenClassification (ELECTRA model)
- esm β TFEsmForTokenClassification (ESM model)
- flaubert β TFFlaubertForTokenClassification (FlauBERT model)
- funnel β TFFunnelForTokenClassification (Funnel Transformer model)
- layoutlm β TFLayoutLMForTokenClassification (LayoutLM model)
- layoutlmv3 β TFLayoutLMv3ForTokenClassification (LayoutLMv3 model)
- longformer β TFLongformerForTokenClassification (Longformer model)
- mobilebert β TFMobileBertForTokenClassification (MobileBERT model)
- mpnet β TFMPNetForTokenClassification (MPNet model)
- rembert β TFRemBertForTokenClassification (RemBERT model)
- roberta β TFRobertaForTokenClassification (RoBERTa model)
- roberta-prelayernorm β TFRobertaPreLayerNormForTokenClassification (RoBERTa-PreLayerNorm model)
- roformer β TFRoFormerForTokenClassification (RoFormer model)
- xlm β TFXLMForTokenClassification (XLM model)
- xlm-roberta β TFXLMRobertaForTokenClassification (XLM-RoBERTa model)
- xlnet β TFXLNetForTokenClassification (XLNet model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForTokenClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForTokenClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForTokenClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForTokenClassification.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForTokenClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a token classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: FlaxAlbertForTokenClassification (ALBERT model)
- BertConfig configuration class: FlaxBertForTokenClassification (BERT model)
- BigBirdConfig configuration class: FlaxBigBirdForTokenClassification (BigBird model)
- DistilBertConfig configuration class: FlaxDistilBertForTokenClassification (DistilBERT model)
- ElectraConfig configuration class: FlaxElectraForTokenClassification (ELECTRA model)
- RoFormerConfig configuration class: FlaxRoFormerForTokenClassification (RoFormer model)
- RobertaConfig configuration class: FlaxRobertaForTokenClassification (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: FlaxRobertaPreLayerNormForTokenClassification (RoBERTa-PreLayerNorm model)
- XLMRobertaConfig configuration class: FlaxXLMRobertaForTokenClassification (XLM-RoBERTa model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a token classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a token classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β FlaxAlbertForTokenClassification (ALBERT model)
- bert β FlaxBertForTokenClassification (BERT model)
- big_bird β FlaxBigBirdForTokenClassification (BigBird model)
- distilbert β FlaxDistilBertForTokenClassification (DistilBERT model)
- electra β FlaxElectraForTokenClassification (ELECTRA model)
- roberta β FlaxRobertaForTokenClassification (RoBERTa model)
- roberta-prelayernorm β FlaxRobertaPreLayerNormForTokenClassification (RoBERTa-PreLayerNorm model)
- roformer β FlaxRoFormerForTokenClassification (RoFormer model)
- xlm-roberta β FlaxXLMRobertaForTokenClassification (XLM-RoBERTa model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForTokenClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForTokenClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForTokenClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForTokenClassification.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForQuestionAnswering
This is a generic model class that will be instantiated as one of the model classes of the library (with a question answering head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: AlbertForQuestionAnswering (ALBERT model)
- BartConfig configuration class: BartForQuestionAnswering (BART model)
- BertConfig configuration class: BertForQuestionAnswering (BERT model)
- BigBirdConfig configuration class: BigBirdForQuestionAnswering (BigBird model)
- BigBirdPegasusConfig configuration class: BigBirdPegasusForQuestionAnswering (BigBird-Pegasus model)
- BloomConfig configuration class: BloomForQuestionAnswering (BLOOM model)
- CamembertConfig configuration class: CamembertForQuestionAnswering (CamemBERT model)
- CanineConfig configuration class: CanineForQuestionAnswering (CANINE model)
- ConvBertConfig configuration class: ConvBertForQuestionAnswering (ConvBERT model)
- Data2VecTextConfig configuration class: Data2VecTextForQuestionAnswering (Data2VecText model)
- DebertaConfig configuration class: DebertaForQuestionAnswering (DeBERTa model)
- DebertaV2Config configuration class: DebertaV2ForQuestionAnswering (DeBERTa-v2 model)
- DistilBertConfig configuration class: DistilBertForQuestionAnswering (DistilBERT model)
- ElectraConfig configuration class: ElectraForQuestionAnswering (ELECTRA model)
- ErnieConfig configuration class: ErnieForQuestionAnswering (ERNIE model)
- ErnieMConfig configuration class: ErnieMForQuestionAnswering (ErnieM model)
- FNetConfig configuration class: FNetForQuestionAnswering (FNet model)
- FalconConfig configuration class: FalconForQuestionAnswering (Falcon model)
- FlaubertConfig configuration class: FlaubertForQuestionAnsweringSimple (FlauBERT model)
- FunnelConfig configuration class: FunnelForQuestionAnswering (Funnel Transformer model)
- GPT2Config configuration class: GPT2ForQuestionAnswering (OpenAI GPT-2 model)
- GPTJConfig configuration class: GPTJForQuestionAnswering (GPT-J model)
- GPTNeoConfig configuration class: GPTNeoForQuestionAnswering (GPT Neo model)
- GPTNeoXConfig configuration class: GPTNeoXForQuestionAnswering (GPT NeoX model)
- IBertConfig configuration class: IBertForQuestionAnswering (I-BERT model)
- LEDConfig configuration class: LEDForQuestionAnswering (LED model)
- LayoutLMv2Config configuration class: LayoutLMv2ForQuestionAnswering (LayoutLMv2 model)
- LayoutLMv3Config configuration class: LayoutLMv3ForQuestionAnswering (LayoutLMv3 model)
- LiltConfig configuration class: LiltForQuestionAnswering (LiLT model)
- LlamaConfig configuration class: LlamaForQuestionAnswering (LLaMA model)
- LongformerConfig configuration class: LongformerForQuestionAnswering (Longformer model)
- LukeConfig configuration class: LukeForQuestionAnswering (LUKE model)
- LxmertConfig configuration class: LxmertForQuestionAnswering (LXMERT model)
- MBartConfig configuration class: MBartForQuestionAnswering (mBART model)
- MPNetConfig configuration class: MPNetForQuestionAnswering (MPNet model)
- MT5Config configuration class: MT5ForQuestionAnswering (MT5 model)
- MarkupLMConfig configuration class: MarkupLMForQuestionAnswering (MarkupLM model)
- MegaConfig configuration class: MegaForQuestionAnswering (MEGA model)
- MegatronBertConfig configuration class: MegatronBertForQuestionAnswering (Megatron-BERT model)
- MistralConfig configuration class: MistralForQuestionAnswering (Mistral model)
- MixtralConfig configuration class: MixtralForQuestionAnswering (Mixtral model)
- MobileBertConfig configuration class: MobileBertForQuestionAnswering (MobileBERT model)
- MptConfig configuration class: MptForQuestionAnswering (MPT model)
- MraConfig configuration class: MraForQuestionAnswering (MRA model)
- MvpConfig configuration class: MvpForQuestionAnswering (MVP model)
- NemotronConfig configuration class: NemotronForQuestionAnswering (Nemotron model)
- NezhaConfig configuration class: NezhaForQuestionAnswering (Nezha model)
- NystromformerConfig configuration class: NystromformerForQuestionAnswering (Nyströmformer model)
- OPTConfig configuration class: OPTForQuestionAnswering (OPT model)
- QDQBertConfig configuration class: QDQBertForQuestionAnswering (QDQBert model)
- Qwen2Config configuration class: Qwen2ForQuestionAnswering (Qwen2 model)
- Qwen2MoeConfig configuration class: Qwen2MoeForQuestionAnswering (Qwen2MoE model)
- ReformerConfig configuration class: ReformerForQuestionAnswering (Reformer model)
- RemBertConfig configuration class: RemBertForQuestionAnswering (RemBERT model)
- RoCBertConfig configuration class: RoCBertForQuestionAnswering (RoCBert model)
- RoFormerConfig configuration class: RoFormerForQuestionAnswering (RoFormer model)
- RobertaConfig configuration class: RobertaForQuestionAnswering (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: RobertaPreLayerNormForQuestionAnswering (RoBERTa-PreLayerNorm model)
- SplinterConfig configuration class: SplinterForQuestionAnswering (Splinter model)
- SqueezeBertConfig configuration class: SqueezeBertForQuestionAnswering (SqueezeBERT model)
- T5Config configuration class: T5ForQuestionAnswering (T5 model)
- UMT5Config configuration class: UMT5ForQuestionAnswering (UMT5 model)
- XLMConfig configuration class: XLMForQuestionAnsweringSimple (XLM model)
- XLMRobertaConfig configuration class: XLMRobertaForQuestionAnswering (XLM-RoBERTa model)
- XLMRobertaXLConfig configuration class: XLMRobertaXLForQuestionAnswering (XLM-RoBERTa-XL model)
- XLNetConfig configuration class: XLNetForQuestionAnsweringSimple (XLNet model)
- XmodConfig configuration class: XmodForQuestionAnswering (X-MOD model)
- YosoConfig configuration class: YosoForQuestionAnswering (YOSO model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a question answering head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a question answering head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β AlbertForQuestionAnswering (ALBERT model)
- bart β BartForQuestionAnswering (BART model)
- bert β BertForQuestionAnswering (BERT model)
- big_bird β BigBirdForQuestionAnswering (BigBird model)
- bigbird_pegasus β BigBirdPegasusForQuestionAnswering (BigBird-Pegasus model)
- bloom β BloomForQuestionAnswering (BLOOM model)
- camembert β CamembertForQuestionAnswering (CamemBERT model)
- canine β CanineForQuestionAnswering (CANINE model)
- convbert β ConvBertForQuestionAnswering (ConvBERT model)
- data2vec-text β Data2VecTextForQuestionAnswering (Data2VecText model)
- deberta β DebertaForQuestionAnswering (DeBERTa model)
- deberta-v2 β DebertaV2ForQuestionAnswering (DeBERTa-v2 model)
- distilbert β DistilBertForQuestionAnswering (DistilBERT model)
- electra β ElectraForQuestionAnswering (ELECTRA model)
- ernie β ErnieForQuestionAnswering (ERNIE model)
- ernie_m β ErnieMForQuestionAnswering (ErnieM model)
- falcon β FalconForQuestionAnswering (Falcon model)
- flaubert β FlaubertForQuestionAnsweringSimple (FlauBERT model)
- fnet β FNetForQuestionAnswering (FNet model)
- funnel β FunnelForQuestionAnswering (Funnel Transformer model)
- gpt2 β GPT2ForQuestionAnswering (OpenAI GPT-2 model)
- gpt_neo β GPTNeoForQuestionAnswering (GPT Neo model)
- gpt_neox β GPTNeoXForQuestionAnswering (GPT NeoX model)
- gptj β GPTJForQuestionAnswering (GPT-J model)
- ibert β IBertForQuestionAnswering (I-BERT model)
- layoutlmv2 β LayoutLMv2ForQuestionAnswering (LayoutLMv2 model)
- layoutlmv3 β LayoutLMv3ForQuestionAnswering (LayoutLMv3 model)
- led β LEDForQuestionAnswering (LED model)
- lilt β LiltForQuestionAnswering (LiLT model)
- llama β LlamaForQuestionAnswering (LLaMA model)
- longformer β LongformerForQuestionAnswering (Longformer model)
- luke β LukeForQuestionAnswering (LUKE model)
- lxmert β LxmertForQuestionAnswering (LXMERT model)
- markuplm β MarkupLMForQuestionAnswering (MarkupLM model)
- mbart β MBartForQuestionAnswering (mBART model)
- mega β MegaForQuestionAnswering (MEGA model)
- megatron-bert β MegatronBertForQuestionAnswering (Megatron-BERT model)
- mistral β MistralForQuestionAnswering (Mistral model)
- mixtral β MixtralForQuestionAnswering (Mixtral model)
- mobilebert β MobileBertForQuestionAnswering (MobileBERT model)
- mpnet β MPNetForQuestionAnswering (MPNet model)
- mpt β MptForQuestionAnswering (MPT model)
- mra β MraForQuestionAnswering (MRA model)
- mt5 β MT5ForQuestionAnswering (MT5 model)
- mvp β MvpForQuestionAnswering (MVP model)
- nemotron β NemotronForQuestionAnswering (Nemotron model)
- nezha β NezhaForQuestionAnswering (Nezha model)
- nystromformer β NystromformerForQuestionAnswering (NystrΓΆmformer model)
- opt β OPTForQuestionAnswering (OPT model)
- qdqbert β QDQBertForQuestionAnswering (QDQBert model)
- qwen2 β Qwen2ForQuestionAnswering (Qwen2 model)
- qwen2_moe β Qwen2MoeForQuestionAnswering (Qwen2MoE model)
- reformer β ReformerForQuestionAnswering (Reformer model)
- rembert β RemBertForQuestionAnswering (RemBERT model)
- roberta β RobertaForQuestionAnswering (RoBERTa model)
- roberta-prelayernorm β RobertaPreLayerNormForQuestionAnswering (RoBERTa-PreLayerNorm model)
- roc_bert β RoCBertForQuestionAnswering (RoCBert model)
- roformer β RoFormerForQuestionAnswering (RoFormer model)
- splinter β SplinterForQuestionAnswering (Splinter model)
- squeezebert β SqueezeBertForQuestionAnswering (SqueezeBERT model)
- t5 β T5ForQuestionAnswering (T5 model)
- umt5 β UMT5ForQuestionAnswering (UMT5 model)
- xlm β XLMForQuestionAnsweringSimple (XLM model)
- xlm-roberta β XLMRobertaForQuestionAnswering (XLM-RoBERTa model)
- xlm-roberta-xl β XLMRobertaXLForQuestionAnswering (XLM-RoBERTa-XL model)
- xlnet β XLNetForQuestionAnsweringSimple (XLNet model)
- xmod β XmodForQuestionAnswering (X-MOD model)
- yoso β YosoForQuestionAnswering (YOSO model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForQuestionAnswering
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForQuestionAnswering.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForQuestionAnswering.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForQuestionAnswering.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForQuestionAnswering
This is a generic model class that will be instantiated as one of the model classes of the library (with a question answering head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: TFAlbertForQuestionAnswering (ALBERT model)
- BertConfig configuration class: TFBertForQuestionAnswering (BERT model)
- CamembertConfig configuration class: TFCamembertForQuestionAnswering (CamemBERT model)
- ConvBertConfig configuration class: TFConvBertForQuestionAnswering (ConvBERT model)
- DebertaConfig configuration class: TFDebertaForQuestionAnswering (DeBERTa model)
- DebertaV2Config configuration class: TFDebertaV2ForQuestionAnswering (DeBERTa-v2 model)
- DistilBertConfig configuration class: TFDistilBertForQuestionAnswering (DistilBERT model)
- ElectraConfig configuration class: TFElectraForQuestionAnswering (ELECTRA model)
- FlaubertConfig configuration class: TFFlaubertForQuestionAnsweringSimple (FlauBERT model)
- FunnelConfig configuration class: TFFunnelForQuestionAnswering (Funnel Transformer model)
- GPTJConfig configuration class: TFGPTJForQuestionAnswering (GPT-J model)
- LayoutLMv3Config configuration class: TFLayoutLMv3ForQuestionAnswering (LayoutLMv3 model)
- LongformerConfig configuration class: TFLongformerForQuestionAnswering (Longformer model)
- MPNetConfig configuration class: TFMPNetForQuestionAnswering (MPNet model)
- MobileBertConfig configuration class: TFMobileBertForQuestionAnswering (MobileBERT model)
- RemBertConfig configuration class: TFRemBertForQuestionAnswering (RemBERT model)
- RoFormerConfig configuration class: TFRoFormerForQuestionAnswering (RoFormer model)
- RobertaConfig configuration class: TFRobertaForQuestionAnswering (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: TFRobertaPreLayerNormForQuestionAnswering (RoBERTa-PreLayerNorm model)
- XLMConfig configuration class: TFXLMForQuestionAnsweringSimple (XLM model)
- XLMRobertaConfig configuration class: TFXLMRobertaForQuestionAnswering (XLM-RoBERTa model)
- XLNetConfig configuration class: TFXLNetForQuestionAnsweringSimple (XLNet model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a question answering head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a question answering head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β TFAlbertForQuestionAnswering (ALBERT model)
- bert β TFBertForQuestionAnswering (BERT model)
- camembert β TFCamembertForQuestionAnswering (CamemBERT model)
- convbert β TFConvBertForQuestionAnswering (ConvBERT model)
- deberta β TFDebertaForQuestionAnswering (DeBERTa model)
- deberta-v2 β TFDebertaV2ForQuestionAnswering (DeBERTa-v2 model)
- distilbert β TFDistilBertForQuestionAnswering (DistilBERT model)
- electra β TFElectraForQuestionAnswering (ELECTRA model)
- flaubert β TFFlaubertForQuestionAnsweringSimple (FlauBERT model)
- funnel β TFFunnelForQuestionAnswering (Funnel Transformer model)
- gptj β TFGPTJForQuestionAnswering (GPT-J model)
- layoutlmv3 β TFLayoutLMv3ForQuestionAnswering (LayoutLMv3 model)
- longformer β TFLongformerForQuestionAnswering (Longformer model)
- mobilebert β TFMobileBertForQuestionAnswering (MobileBERT model)
- mpnet β TFMPNetForQuestionAnswering (MPNet model)
- rembert β TFRemBertForQuestionAnswering (RemBERT model)
- roberta β TFRobertaForQuestionAnswering (RoBERTa model)
- roberta-prelayernorm β TFRobertaPreLayerNormForQuestionAnswering (RoBERTa-PreLayerNorm model)
- roformer β TFRoFormerForQuestionAnswering (RoFormer model)
- xlm β TFXLMForQuestionAnsweringSimple (XLM model)
- xlm-roberta β TFXLMRobertaForQuestionAnswering (XLM-RoBERTa model)
- xlnet β TFXLNetForQuestionAnsweringSimple (XLNet model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForQuestionAnswering
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForQuestionAnswering.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForQuestionAnswering.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForQuestionAnswering.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForQuestionAnswering
This is a generic model class that will be instantiated as one of the model classes of the library (with a question answering head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlbertConfig configuration class: FlaxAlbertForQuestionAnswering (ALBERT model)
- BartConfig configuration class: FlaxBartForQuestionAnswering (BART model)
- BertConfig configuration class: FlaxBertForQuestionAnswering (BERT model)
- BigBirdConfig configuration class: FlaxBigBirdForQuestionAnswering (BigBird model)
- DistilBertConfig configuration class: FlaxDistilBertForQuestionAnswering (DistilBERT model)
- ElectraConfig configuration class: FlaxElectraForQuestionAnswering (ELECTRA model)
- MBartConfig configuration class: FlaxMBartForQuestionAnswering (mBART model)
- RoFormerConfig configuration class: FlaxRoFormerForQuestionAnswering (RoFormer model)
- RobertaConfig configuration class: FlaxRobertaForQuestionAnswering (RoBERTa model)
- RobertaPreLayerNormConfig configuration class: FlaxRobertaPreLayerNormForQuestionAnswering (RoBERTa-PreLayerNorm model)
- XLMRobertaConfig configuration class: FlaxXLMRobertaForQuestionAnswering (XLM-RoBERTa model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a question answering head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a question answering head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- albert β FlaxAlbertForQuestionAnswering (ALBERT model)
- bart β FlaxBartForQuestionAnswering (BART model)
- bert β FlaxBertForQuestionAnswering (BERT model)
- big_bird β FlaxBigBirdForQuestionAnswering (BigBird model)
- distilbert β FlaxDistilBertForQuestionAnswering (DistilBERT model)
- electra β FlaxElectraForQuestionAnswering (ELECTRA model)
- mbart β FlaxMBartForQuestionAnswering (mBART model)
- roberta β FlaxRobertaForQuestionAnswering (RoBERTa model)
- roberta-prelayernorm β FlaxRobertaPreLayerNormForQuestionAnswering (RoBERTa-PreLayerNorm model)
- roformer β FlaxRoFormerForQuestionAnswering (RoFormer model)
- xlm-roberta β FlaxXLMRobertaForQuestionAnswering (XLM-RoBERTa model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForQuestionAnswering
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForQuestionAnswering.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForQuestionAnswering.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForQuestionAnswering.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForTextEncoding
TFAutoModelForTextEncoding
Computer vision
The following auto classes are available for the following computer vision tasks.
AutoModelForDepthEstimation
This is a generic model class that will be instantiated as one of the model classes of the library (with a depth estimation head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- DPTConfig configuration class: DPTForDepthEstimation (DPT model)
- DepthAnythingConfig configuration class: DepthAnythingForDepthEstimation (Depth Anything model)
- GLPNConfig configuration class: GLPNForDepthEstimation (GLPN model)
- ZoeDepthConfig configuration class: ZoeDepthForDepthEstimation (ZoeDepth model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a depth estimation head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a depth estimation head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- depth_anything β DepthAnythingForDepthEstimation (Depth Anything model)
- dpt β DPTForDepthEstimation (DPT model)
- glpn β GLPNForDepthEstimation (GLPN model)
- zoedepth β ZoeDepthForDepthEstimation (ZoeDepth model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForDepthEstimation
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForDepthEstimation.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForDepthEstimation.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForDepthEstimation.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForImageClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a image classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BeitConfig configuration class: BeitForImageClassification (BEiT model)
- BitConfig configuration class: BitForImageClassification (BiT model)
- CLIPConfig configuration class: CLIPForImageClassification (CLIP model)
- ConvNextConfig configuration class: ConvNextForImageClassification (ConvNeXT model)
- ConvNextV2Config configuration class: ConvNextV2ForImageClassification (ConvNeXTV2 model)
- CvtConfig configuration class: CvtForImageClassification (CvT model)
- Data2VecVisionConfig configuration class: Data2VecVisionForImageClassification (Data2VecVision model)
- DeiTConfig configuration class: DeiTForImageClassification or DeiTForImageClassificationWithTeacher (DeiT model)
- DinatConfig configuration class: DinatForImageClassification (DiNAT model)
- Dinov2Config configuration class: Dinov2ForImageClassification (DINOv2 model)
- EfficientFormerConfig configuration class: EfficientFormerForImageClassification or EfficientFormerForImageClassificationWithTeacher (EfficientFormer model)
- EfficientNetConfig configuration class: EfficientNetForImageClassification (EfficientNet model)
- FocalNetConfig configuration class: FocalNetForImageClassification (FocalNet model)
- HieraConfig configuration class: HieraForImageClassification (Hiera model)
- IJepaConfig configuration class: IJepaForImageClassification (I-JEPA model)
- ImageGPTConfig configuration class: ImageGPTForImageClassification (ImageGPT model)
- LevitConfig configuration class: LevitForImageClassification or LevitForImageClassificationWithTeacher (LeViT model)
- MobileNetV1Config configuration class: MobileNetV1ForImageClassification (MobileNetV1 model)
- MobileNetV2Config configuration class: MobileNetV2ForImageClassification (MobileNetV2 model)
- MobileViTConfig configuration class: MobileViTForImageClassification (MobileViT model)
- MobileViTV2Config configuration class: MobileViTV2ForImageClassification (MobileViTV2 model)
- NatConfig configuration class: NatForImageClassification (NAT model)
- PerceiverConfig configuration class: PerceiverForImageClassificationLearned or PerceiverForImageClassificationFourier or PerceiverForImageClassificationConvProcessing (Perceiver model)
- PoolFormerConfig configuration class: PoolFormerForImageClassification (PoolFormer model)
- PvtConfig configuration class: PvtForImageClassification (PVT model)
- PvtV2Config configuration class: PvtV2ForImageClassification (PVTv2 model)
- RegNetConfig configuration class: RegNetForImageClassification (RegNet model)
- ResNetConfig configuration class: ResNetForImageClassification (ResNet model)
- SegformerConfig configuration class: SegformerForImageClassification (SegFormer model)
- SiglipConfig configuration class: SiglipForImageClassification (SigLIP model)
- SwiftFormerConfig configuration class: SwiftFormerForImageClassification (SwiftFormer model)
- SwinConfig configuration class: SwinForImageClassification (Swin Transformer model)
- Swinv2Config configuration class: Swinv2ForImageClassification (Swin Transformer V2 model)
- TimmWrapperConfig configuration class: TimmWrapperForImageClassification (TimmWrapperModel model)
- VanConfig configuration class: VanForImageClassification (VAN model)
- ViTConfig configuration class: ViTForImageClassification (ViT model)
- ViTHybridConfig configuration class: ViTHybridForImageClassification (ViT Hybrid model)
- ViTMSNConfig configuration class: ViTMSNForImageClassification (ViTMSN model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a image classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a image classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- beit β BeitForImageClassification (BEiT model)
- bit β BitForImageClassification (BiT model)
- clip β CLIPForImageClassification (CLIP model)
- convnext β ConvNextForImageClassification (ConvNeXT model)
- convnextv2 β ConvNextV2ForImageClassification (ConvNeXTV2 model)
- cvt β CvtForImageClassification (CvT model)
- data2vec-vision β Data2VecVisionForImageClassification (Data2VecVision model)
- deit β DeiTForImageClassification or DeiTForImageClassificationWithTeacher (DeiT model)
- dinat β DinatForImageClassification (DiNAT model)
- dinov2 β Dinov2ForImageClassification (DINOv2 model)
- efficientformer β EfficientFormerForImageClassification or EfficientFormerForImageClassificationWithTeacher (EfficientFormer model)
- efficientnet β EfficientNetForImageClassification (EfficientNet model)
- focalnet β FocalNetForImageClassification (FocalNet model)
- hiera β HieraForImageClassification (Hiera model)
- ijepa β IJepaForImageClassification (I-JEPA model)
- imagegpt β ImageGPTForImageClassification (ImageGPT model)
- levit β LevitForImageClassification or LevitForImageClassificationWithTeacher (LeViT model)
- mobilenet_v1 β MobileNetV1ForImageClassification (MobileNetV1 model)
- mobilenet_v2 β MobileNetV2ForImageClassification (MobileNetV2 model)
- mobilevit β MobileViTForImageClassification (MobileViT model)
- mobilevitv2 β MobileViTV2ForImageClassification (MobileViTV2 model)
- nat β NatForImageClassification (NAT model)
- perceiver β PerceiverForImageClassificationLearned or PerceiverForImageClassificationFourier or PerceiverForImageClassificationConvProcessing (Perceiver model)
- poolformer β PoolFormerForImageClassification (PoolFormer model)
- pvt β PvtForImageClassification (PVT model)
- pvt_v2 β PvtV2ForImageClassification (PVTv2 model)
- regnet β RegNetForImageClassification (RegNet model)
- resnet β ResNetForImageClassification (ResNet model)
- segformer β SegformerForImageClassification (SegFormer model)
- siglip β SiglipForImageClassification (SigLIP model)
- swiftformer β SwiftFormerForImageClassification (SwiftFormer model)
- swin β SwinForImageClassification (Swin Transformer model)
- swinv2 β Swinv2ForImageClassification (Swin Transformer V2 model)
- timm_wrapper β TimmWrapperForImageClassification (TimmWrapperModel model)
- van β VanForImageClassification (VAN model)
- vit β ViTForImageClassification (ViT model)
- vit_hybrid β ViTHybridForImageClassification (ViT Hybrid model)
- vit_msn β ViTMSNForImageClassification (ViTMSN model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForImageClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForImageClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForImageClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForImageClassification.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForImageClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a image classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- ConvNextConfig configuration class: TFConvNextForImageClassification (ConvNeXT model)
- ConvNextV2Config configuration class: TFConvNextV2ForImageClassification (ConvNeXTV2 model)
- CvtConfig configuration class: TFCvtForImageClassification (CvT model)
- Data2VecVisionConfig configuration class: TFData2VecVisionForImageClassification (Data2VecVision model)
- DeiTConfig configuration class: TFDeiTForImageClassification or TFDeiTForImageClassificationWithTeacher (DeiT model)
- EfficientFormerConfig configuration class: TFEfficientFormerForImageClassification or TFEfficientFormerForImageClassificationWithTeacher (EfficientFormer model)
- MobileViTConfig configuration class: TFMobileViTForImageClassification (MobileViT model)
- RegNetConfig configuration class: TFRegNetForImageClassification (RegNet model)
- ResNetConfig configuration class: TFResNetForImageClassification (ResNet model)
- SegformerConfig configuration class: TFSegformerForImageClassification (SegFormer model)
- SwiftFormerConfig configuration class: TFSwiftFormerForImageClassification (SwiftFormer model)
- SwinConfig configuration class: TFSwinForImageClassification (Swin Transformer model)
- ViTConfig configuration class: TFViTForImageClassification (ViT model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a image classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a image classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- convnext β TFConvNextForImageClassification (ConvNeXT model)
- convnextv2 β TFConvNextV2ForImageClassification (ConvNeXTV2 model)
- cvt β TFCvtForImageClassification (CvT model)
- data2vec-vision β TFData2VecVisionForImageClassification (Data2VecVision model)
- deit β TFDeiTForImageClassification or TFDeiTForImageClassificationWithTeacher (DeiT model)
- efficientformer β TFEfficientFormerForImageClassification or TFEfficientFormerForImageClassificationWithTeacher (EfficientFormer model)
- mobilevit β TFMobileViTForImageClassification (MobileViT model)
- regnet β TFRegNetForImageClassification (RegNet model)
- resnet β TFResNetForImageClassification (ResNet model)
- segformer β TFSegformerForImageClassification (SegFormer model)
- swiftformer β TFSwiftFormerForImageClassification (SwiftFormer model)
- swin β TFSwinForImageClassification (Swin Transformer model)
- vit β TFViTForImageClassification (ViT model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForImageClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForImageClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForImageClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForImageClassification.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForImageClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a image classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BeitConfig configuration class: FlaxBeitForImageClassification (BEiT model)
- Dinov2Config configuration class: FlaxDinov2ForImageClassification (DINOv2 model)
- RegNetConfig configuration class: FlaxRegNetForImageClassification (RegNet model)
- ResNetConfig configuration class: FlaxResNetForImageClassification (ResNet model)
- ViTConfig configuration class: FlaxViTForImageClassification (ViT model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a image classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a image classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- beit β FlaxBeitForImageClassification (BEiT model)
- dinov2 β FlaxDinov2ForImageClassification (DINOv2 model)
- regnet β FlaxRegNetForImageClassification (RegNet model)
- resnet β FlaxResNetForImageClassification (ResNet model)
- vit β FlaxViTForImageClassification (ViT model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForImageClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForImageClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForImageClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForImageClassification.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForVideoClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a video classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- TimesformerConfig configuration class: TimesformerForVideoClassification (TimeSformer model)
- VideoMAEConfig configuration class: VideoMAEForVideoClassification (VideoMAE model)
- VivitConfig configuration class: VivitForVideoClassification (ViViT model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a video classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a video classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- timesformer β TimesformerForVideoClassification (TimeSformer model)
- videomae β VideoMAEForVideoClassification (VideoMAE model)
- vivit β VivitForVideoClassification (ViViT model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForVideoClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForVideoClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForVideoClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForVideoClassification.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForKeypointDetection
AutoModelForMaskedImageModeling
This is a generic model class that will be instantiated as one of the model classes of the library (with a masked image modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- DeiTConfig configuration class: DeiTForMaskedImageModeling (DeiT model)
- FocalNetConfig configuration class: FocalNetForMaskedImageModeling (FocalNet model)
- SwinConfig configuration class: SwinForMaskedImageModeling (Swin Transformer model)
- Swinv2Config configuration class: Swinv2ForMaskedImageModeling (Swin Transformer V2 model)
- ViTConfig configuration class: ViTForMaskedImageModeling (ViT model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a masked image modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a masked image modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- deit β DeiTForMaskedImageModeling (DeiT model)
- focalnet β FocalNetForMaskedImageModeling (FocalNet model)
- swin β SwinForMaskedImageModeling (Swin Transformer model)
- swinv2 β Swinv2ForMaskedImageModeling (Swin Transformer V2 model)
- vit β ViTForMaskedImageModeling (ViT model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForMaskedImageModeling
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForMaskedImageModeling.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForMaskedImageModeling.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForMaskedImageModeling.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForMaskedImageModeling
This is a generic model class that will be instantiated as one of the model classes of the library (with a masked image modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- DeiTConfig configuration class: TFDeiTForMaskedImageModeling (DeiT model)
- SwinConfig configuration class: TFSwinForMaskedImageModeling (Swin Transformer model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a masked image modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a masked image modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- deit β TFDeiTForMaskedImageModeling (DeiT model)
- swin β TFSwinForMaskedImageModeling (Swin Transformer model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForMaskedImageModeling
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForMaskedImageModeling.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForMaskedImageModeling.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForMaskedImageModeling.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForObjectDetection
This is a generic model class that will be instantiated as one of the model classes of the library (with a object detection head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- ConditionalDetrConfig configuration class: ConditionalDetrForObjectDetection (Conditional DETR model)
- DeformableDetrConfig configuration class: DeformableDetrForObjectDetection (Deformable DETR model)
- DetaConfig configuration class: DetaForObjectDetection (DETA model)
- DetrConfig configuration class: DetrForObjectDetection (DETR model)
- RTDetrConfig configuration class: RTDetrForObjectDetection (RT-DETR model)
- TableTransformerConfig configuration class: TableTransformerForObjectDetection (Table Transformer model)
- YolosConfig configuration class: YolosForObjectDetection (YOLOS model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a object detection head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a object detection head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- conditional_detr β ConditionalDetrForObjectDetection (Conditional DETR model)
- deformable_detr β DeformableDetrForObjectDetection (Deformable DETR model)
- deta β DetaForObjectDetection (DETA model)
- detr β DetrForObjectDetection (DETR model)
- rt_detr β RTDetrForObjectDetection (RT-DETR model)
- table-transformer β TableTransformerForObjectDetection (Table Transformer model)
- yolos β YolosForObjectDetection (YOLOS model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForObjectDetection
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForObjectDetection.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForObjectDetection.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForObjectDetection.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForImageSegmentation
This is a generic model class that will be instantiated as one of the model classes of the library (with a image segmentation head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- DetrConfig configuration class: DetrForSegmentation (DETR model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a image segmentation head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a image segmentation head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- detr β DetrForSegmentation (DETR model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForImageSegmentation
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForImageSegmentation.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForImageSegmentation.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForImageSegmentation.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForImageToImage
AutoModelForSemanticSegmentation
This is a generic model class that will be instantiated as one of the model classes of the library (with a semantic segmentation head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BeitConfig configuration class: BeitForSemanticSegmentation (BEiT model)
- DPTConfig configuration class: DPTForSemanticSegmentation (DPT model)
- Data2VecVisionConfig configuration class: Data2VecVisionForSemanticSegmentation (Data2VecVision model)
- MobileNetV2Config configuration class: MobileNetV2ForSemanticSegmentation (MobileNetV2 model)
- MobileViTConfig configuration class: MobileViTForSemanticSegmentation (MobileViT model)
- MobileViTV2Config configuration class: MobileViTV2ForSemanticSegmentation (MobileViTV2 model)
- SegformerConfig configuration class: SegformerForSemanticSegmentation (SegFormer model)
- UperNetConfig configuration class: UperNetForSemanticSegmentation (UPerNet model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a semantic segmentation head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a semantic segmentation head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- beit β BeitForSemanticSegmentation (BEiT model)
- data2vec-vision β Data2VecVisionForSemanticSegmentation (Data2VecVision model)
- dpt β DPTForSemanticSegmentation (DPT model)
- mobilenet_v2 β MobileNetV2ForSemanticSegmentation (MobileNetV2 model)
- mobilevit β MobileViTForSemanticSegmentation (MobileViT model)
- mobilevitv2 β MobileViTV2ForSemanticSegmentation (MobileViTV2 model)
- segformer β SegformerForSemanticSegmentation (SegFormer model)
- upernet β UperNetForSemanticSegmentation (UPerNet model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForSemanticSegmentation
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForSemanticSegmentation.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForSemanticSegmentation.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForSemanticSegmentation.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForSemanticSegmentation
This is a generic model class that will be instantiated as one of the model classes of the library (with a semantic segmentation head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- Data2VecVisionConfig configuration class: TFData2VecVisionForSemanticSegmentation (Data2VecVision model)
- MobileViTConfig configuration class: TFMobileViTForSemanticSegmentation (MobileViT model)
- SegformerConfig configuration class: TFSegformerForSemanticSegmentation (SegFormer model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a semantic segmentation head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a semantic segmentation head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- data2vec-vision β TFData2VecVisionForSemanticSegmentation (Data2VecVision model)
- mobilevit β TFMobileViTForSemanticSegmentation (MobileViT model)
- segformer β TFSegformerForSemanticSegmentation (SegFormer model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForSemanticSegmentation
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForSemanticSegmentation.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForSemanticSegmentation.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForSemanticSegmentation.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForInstanceSegmentation
This is a generic model class that will be instantiated as one of the model classes of the library (with a instance segmentation head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- MaskFormerConfig configuration class: MaskFormerForInstanceSegmentation (MaskFormer model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a instance segmentation head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a instance segmentation head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- maskformer β MaskFormerForInstanceSegmentation (MaskFormer model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForInstanceSegmentation
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForInstanceSegmentation.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForInstanceSegmentation.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForInstanceSegmentation.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForUniversalSegmentation
This is a generic model class that will be instantiated as one of the model classes of the library (with a universal image segmentation head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- DetrConfig configuration class: DetrForSegmentation (DETR model)
- Mask2FormerConfig configuration class: Mask2FormerForUniversalSegmentation (Mask2Former model)
- MaskFormerConfig configuration class: MaskFormerForInstanceSegmentation (MaskFormer model)
- OneFormerConfig configuration class: OneFormerForUniversalSegmentation (OneFormer model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a universal image segmentation head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a universal image segmentation head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- detr β DetrForSegmentation (DETR model)
- mask2former β Mask2FormerForUniversalSegmentation (Mask2Former model)
- maskformer β MaskFormerForInstanceSegmentation (MaskFormer model)
- oneformer β OneFormerForUniversalSegmentation (OneFormer model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForUniversalSegmentation
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForUniversalSegmentation.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForUniversalSegmentation.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForUniversalSegmentation.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForZeroShotImageClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a zero-shot image classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AlignConfig configuration class: AlignModel (ALIGN model)
- AltCLIPConfig configuration class: AltCLIPModel (AltCLIP model)
- Blip2Config configuration class: Blip2ForImageTextRetrieval (BLIP-2 model)
- BlipConfig configuration class: BlipModel (BLIP model)
- CLIPConfig configuration class: CLIPModel (CLIP model)
- CLIPSegConfig configuration class: CLIPSegModel (CLIPSeg model)
- ChineseCLIPConfig configuration class: ChineseCLIPModel (Chinese-CLIP model)
- SiglipConfig configuration class: SiglipModel (SigLIP model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a zero-shot image classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a zero-shot image classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- align β AlignModel (ALIGN model)
- altclip β AltCLIPModel (AltCLIP model)
- blip β BlipModel (BLIP model)
- blip-2 β Blip2ForImageTextRetrieval (BLIP-2 model)
- chinese_clip β ChineseCLIPModel (Chinese-CLIP model)
- clip β CLIPModel (CLIP model)
- clipseg β CLIPSegModel (CLIPSeg model)
- siglip β SiglipModel (SigLIP model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForZeroShotImageClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForZeroShotImageClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForZeroShotImageClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForZeroShotImageClassification.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForZeroShotImageClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a zero-shot image classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BlipConfig configuration class: TFBlipModel (BLIP model)
- CLIPConfig configuration class: TFCLIPModel (CLIP model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a zero-shot image classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a zero-shot image classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- blip β TFBlipModel (BLIP model)
- clip β TFCLIPModel (CLIP model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForZeroShotImageClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForZeroShotImageClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForZeroShotImageClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForZeroShotImageClassification.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForZeroShotObjectDetection
This is a generic model class that will be instantiated as one of the model classes of the library (with a zero-shot object detection head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- GroundingDinoConfig configuration class: GroundingDinoForObjectDetection (Grounding DINO model)
- OmDetTurboConfig configuration class: OmDetTurboForObjectDetection (OmDet-Turbo model)
- OwlViTConfig configuration class: OwlViTForObjectDetection (OWL-ViT model)
- Owlv2Config configuration class: Owlv2ForObjectDetection (OWLv2 model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a zero-shot object detection head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a zero-shot object detection head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- grounding-dino β GroundingDinoForObjectDetection (Grounding DINO model)
- omdet-turbo β OmDetTurboForObjectDetection (OmDet-Turbo model)
- owlv2 β Owlv2ForObjectDetection (OWLv2 model)
- owlvit β OwlViTForObjectDetection (OWL-ViT model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForZeroShotObjectDetection
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForZeroShotObjectDetection.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForZeroShotObjectDetection.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForZeroShotObjectDetection.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
Audio
The following auto classes are available for the following audio tasks.
AutoModelForAudioClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a audio classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- ASTConfig configuration class: ASTForAudioClassification (Audio Spectrogram Transformer model)
- Data2VecAudioConfig configuration class: Data2VecAudioForSequenceClassification (Data2VecAudio model)
- HubertConfig configuration class: HubertForSequenceClassification (Hubert model)
- SEWConfig configuration class: SEWForSequenceClassification (SEW model)
- SEWDConfig configuration class: SEWDForSequenceClassification (SEW-D model)
- UniSpeechConfig configuration class: UniSpeechForSequenceClassification (UniSpeech model)
- UniSpeechSatConfig configuration class: UniSpeechSatForSequenceClassification (UniSpeechSat model)
- Wav2Vec2BertConfig configuration class: Wav2Vec2BertForSequenceClassification (Wav2Vec2-BERT model)
- Wav2Vec2Config configuration class: Wav2Vec2ForSequenceClassification (Wav2Vec2 model)
- Wav2Vec2ConformerConfig configuration class: Wav2Vec2ConformerForSequenceClassification (Wav2Vec2-Conformer model)
- WavLMConfig configuration class: WavLMForSequenceClassification (WavLM model)
- WhisperConfig configuration class: WhisperForAudioClassification (Whisper model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a audio classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a audio classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- audio-spectrogram-transformer β ASTForAudioClassification (Audio Spectrogram Transformer model)
- data2vec-audio β Data2VecAudioForSequenceClassification (Data2VecAudio model)
- hubert β HubertForSequenceClassification (Hubert model)
- sew β SEWForSequenceClassification (SEW model)
- sew-d β SEWDForSequenceClassification (SEW-D model)
- unispeech β UniSpeechForSequenceClassification (UniSpeech model)
- unispeech-sat β UniSpeechSatForSequenceClassification (UniSpeechSat model)
- wav2vec2 β Wav2Vec2ForSequenceClassification (Wav2Vec2 model)
- wav2vec2-bert β Wav2Vec2BertForSequenceClassification (Wav2Vec2-BERT model)
- wav2vec2-conformer β Wav2Vec2ConformerForSequenceClassification (Wav2Vec2-Conformer model)
- wavlm β WavLMForSequenceClassification (WavLM model)
- whisper β WhisperForAudioClassification (Whisper model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForAudioClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForAudioClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForAudioClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForAudioClassification.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForAudioFrameClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a audio classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- Wav2Vec2Config configuration class: TFWav2Vec2ForSequenceClassification (Wav2Vec2 model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a audio classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a audio classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- wav2vec2 β TFWav2Vec2ForSequenceClassification (Wav2Vec2 model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForAudioClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForAudioClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForAudioClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForAudioClassification.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
TFAutoModelForAudioFrameClassification
This is a generic model class that will be instantiated as one of the model classes of the library (with a audio frame (token) classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- Data2VecAudioConfig configuration class: Data2VecAudioForAudioFrameClassification (Data2VecAudio model)
- UniSpeechSatConfig configuration class: UniSpeechSatForAudioFrameClassification (UniSpeechSat model)
- Wav2Vec2BertConfig configuration class: Wav2Vec2BertForAudioFrameClassification (Wav2Vec2-BERT model)
- Wav2Vec2Config configuration class: Wav2Vec2ForAudioFrameClassification (Wav2Vec2 model)
- Wav2Vec2ConformerConfig configuration class: Wav2Vec2ConformerForAudioFrameClassification (Wav2Vec2-Conformer model)
- WavLMConfig configuration class: WavLMForAudioFrameClassification (WavLM model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a audio frame (token) classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a audio frame (token) classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- data2vec-audio β Data2VecAudioForAudioFrameClassification (Data2VecAudio model)
- unispeech-sat β UniSpeechSatForAudioFrameClassification (UniSpeechSat model)
- wav2vec2 β Wav2Vec2ForAudioFrameClassification (Wav2Vec2 model)
- wav2vec2-bert β Wav2Vec2BertForAudioFrameClassification (Wav2Vec2-BERT model)
- wav2vec2-conformer β Wav2Vec2ConformerForAudioFrameClassification (Wav2Vec2-Conformer model)
- wavlm β WavLMForAudioFrameClassification (WavLM model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForAudioFrameClassification
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForAudioFrameClassification.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForAudioFrameClassification.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForAudioFrameClassification.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForCTC
This is a generic model class that will be instantiated as one of the model classes of the library (with a connectionist temporal classification head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- Data2VecAudioConfig configuration class: Data2VecAudioForCTC (Data2VecAudio model)
- HubertConfig configuration class: HubertForCTC (Hubert model)
- MCTCTConfig configuration class: MCTCTForCTC (M-CTC-T model)
- SEWConfig configuration class: SEWForCTC (SEW model)
- SEWDConfig configuration class: SEWDForCTC (SEW-D model)
- UniSpeechConfig configuration class: UniSpeechForCTC (UniSpeech model)
- UniSpeechSatConfig configuration class: UniSpeechSatForCTC (UniSpeechSat model)
- Wav2Vec2BertConfig configuration class: Wav2Vec2BertForCTC (Wav2Vec2-BERT model)
- Wav2Vec2Config configuration class: Wav2Vec2ForCTC (Wav2Vec2 model)
- Wav2Vec2ConformerConfig configuration class: Wav2Vec2ConformerForCTC (Wav2Vec2-Conformer model)
- WavLMConfig configuration class: WavLMForCTC (WavLM model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a connectionist temporal classification head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a connectionist temporal classification head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- data2vec-audio β Data2VecAudioForCTC (Data2VecAudio model)
- hubert β HubertForCTC (Hubert model)
- mctct β MCTCTForCTC (M-CTC-T model)
- sew β SEWForCTC (SEW model)
- sew-d β SEWDForCTC (SEW-D model)
- unispeech β UniSpeechForCTC (UniSpeech model)
- unispeech-sat β UniSpeechSatForCTC (UniSpeechSat model)
- wav2vec2 β Wav2Vec2ForCTC (Wav2Vec2 model)
- wav2vec2-bert β Wav2Vec2BertForCTC (Wav2Vec2-BERT model)
- wav2vec2-conformer β Wav2Vec2ConformerForCTC (Wav2Vec2-Conformer model)
- wavlm β WavLMForCTC (WavLM model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForCTC
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForCTC.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForCTC.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForCTC.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForSpeechSeq2Seq
This is a generic model class that will be instantiated as one of the model classes of the library (with a sequence-to-sequence speech-to-text modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- Pop2PianoConfig configuration class: Pop2PianoForConditionalGeneration (Pop2Piano model)
- SeamlessM4TConfig configuration class: SeamlessM4TForSpeechToText (SeamlessM4T model)
- SeamlessM4Tv2Config configuration class: SeamlessM4Tv2ForSpeechToText (SeamlessM4Tv2 model)
- Speech2TextConfig configuration class: Speech2TextForConditionalGeneration (Speech2Text model)
- SpeechEncoderDecoderConfig configuration class: SpeechEncoderDecoderModel (Speech Encoder decoder model)
- SpeechT5Config configuration class: SpeechT5ForSpeechToText (SpeechT5 model)
- WhisperConfig configuration class: WhisperForConditionalGeneration (Whisper model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a sequence-to-sequence speech-to-text modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a sequence-to-sequence speech-to-text modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- pop2piano β Pop2PianoForConditionalGeneration (Pop2Piano model)
- seamless_m4t β SeamlessM4TForSpeechToText (SeamlessM4T model)
- seamless_m4t_v2 β SeamlessM4Tv2ForSpeechToText (SeamlessM4Tv2 model)
- speech-encoder-decoder β SpeechEncoderDecoderModel (Speech Encoder decoder model)
- speech_to_text β Speech2TextForConditionalGeneration (Speech2Text model)
- speecht5 β SpeechT5ForSpeechToText (SpeechT5 model)
- whisper β WhisperForConditionalGeneration (Whisper model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForSpeechSeq2Seq
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForSpeechSeq2Seq.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForSpeechSeq2Seq.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForSpeechSeq2Seq.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForSpeechSeq2Seq
This is a generic model class that will be instantiated as one of the model classes of the library (with a sequence-to-sequence speech-to-text modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- Speech2TextConfig configuration class: TFSpeech2TextForConditionalGeneration (Speech2Text model)
- WhisperConfig configuration class: TFWhisperForConditionalGeneration (Whisper model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a sequence-to-sequence speech-to-text modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a sequence-to-sequence speech-to-text modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- speech_to_text β TFSpeech2TextForConditionalGeneration (Speech2Text model)
- whisper β TFWhisperForConditionalGeneration (Whisper model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForSpeechSeq2Seq
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForSpeechSeq2Seq.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForSpeechSeq2Seq.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForSpeechSeq2Seq.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForSpeechSeq2Seq
This is a generic model class that will be instantiated as one of the model classes of the library (with a sequence-to-sequence speech-to-text modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- SpeechEncoderDecoderConfig configuration class: FlaxSpeechEncoderDecoderModel (Speech Encoder decoder model)
- WhisperConfig configuration class: FlaxWhisperForConditionalGeneration (Whisper model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a sequence-to-sequence speech-to-text modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a sequence-to-sequence speech-to-text modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- speech-encoder-decoder β FlaxSpeechEncoderDecoderModel (Speech Encoder decoder model)
- whisper β FlaxWhisperForConditionalGeneration (Whisper model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForSpeechSeq2Seq
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForSpeechSeq2Seq.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForSpeechSeq2Seq.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForSpeechSeq2Seq.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForAudioXVector
This is a generic model class that will be instantiated as one of the model classes of the library (with a audio retrieval via x-vector head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- Data2VecAudioConfig configuration class: Data2VecAudioForXVector (Data2VecAudio model)
- UniSpeechSatConfig configuration class: UniSpeechSatForXVector (UniSpeechSat model)
- Wav2Vec2BertConfig configuration class: Wav2Vec2BertForXVector (Wav2Vec2-BERT model)
- Wav2Vec2Config configuration class: Wav2Vec2ForXVector (Wav2Vec2 model)
- Wav2Vec2ConformerConfig configuration class: Wav2Vec2ConformerForXVector (Wav2Vec2-Conformer model)
- WavLMConfig configuration class: WavLMForXVector (WavLM model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a audio retrieval via x-vector head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a audio retrieval via x-vector head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- data2vec-audio β Data2VecAudioForXVector (Data2VecAudio model)
- unispeech-sat β UniSpeechSatForXVector (UniSpeechSat model)
- wav2vec2 β Wav2Vec2ForXVector (Wav2Vec2 model)
- wav2vec2-bert β Wav2Vec2BertForXVector (Wav2Vec2-BERT model)
- wav2vec2-conformer β Wav2Vec2ConformerForXVector (Wav2Vec2-Conformer model)
- wavlm β WavLMForXVector (WavLM model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForAudioXVector
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForAudioXVector.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForAudioXVector.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForAudioXVector.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForTextToSpectrogram
AutoModelForTextToWaveform
Multimodal
The following auto classes are available for the following multimodal tasks.
AutoModelForTableQuestionAnswering
This is a generic model class that will be instantiated as one of the model classes of the library (with a table question answering head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- TapasConfig configuration class: TapasForQuestionAnswering (TAPAS model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a table question answering head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a table question answering head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- tapas β TapasForQuestionAnswering (TAPAS model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForTableQuestionAnswering
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForTableQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq")
>>> # Update configuration during loading
>>> model = AutoModelForTableQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/tapas_tf_model_config.json")
>>> model = AutoModelForTableQuestionAnswering.from_pretrained(
... "./tf_model/tapas_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForTableQuestionAnswering
This is a generic model class that will be instantiated as one of the model classes of the library (with a table question answering head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- TapasConfig configuration class: TFTapasForQuestionAnswering (TAPAS model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a table question answering head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a table question answering head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- tapas β TFTapasForQuestionAnswering (TAPAS model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForTableQuestionAnswering
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForTableQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq")
>>> # Update configuration during loading
>>> model = TFAutoModelForTableQuestionAnswering.from_pretrained("google/tapas-base-finetuned-wtq", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/tapas_pt_model_config.json")
>>> model = TFAutoModelForTableQuestionAnswering.from_pretrained(
... "./pt_model/tapas_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForDocumentQuestionAnswering
This is a generic model class that will be instantiated as one of the model classes of the library (with a document question answering head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- LayoutLMConfig configuration class: LayoutLMForQuestionAnswering (LayoutLM model)
- LayoutLMv2Config configuration class: LayoutLMv2ForQuestionAnswering (LayoutLMv2 model)
- LayoutLMv3Config configuration class: LayoutLMv3ForQuestionAnswering (LayoutLMv3 model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a document question answering head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
Examples:
>>> from transformers import AutoConfig, AutoModelForDocumentQuestionAnswering
>>> # Download configuration from huggingface.co and cache.
>>> config = AutoConfig.from_pretrained("impira/layoutlm-document-qa", revision="52e01b3")
>>> model = AutoModelForDocumentQuestionAnswering.from_config(config)
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a document question answering head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- layoutlm β LayoutLMForQuestionAnswering (LayoutLM model)
- layoutlmv2 β LayoutLMv2ForQuestionAnswering (LayoutLMv2 model)
- layoutlmv3 β LayoutLMv3ForQuestionAnswering (LayoutLMv3 model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForDocumentQuestionAnswering
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForDocumentQuestionAnswering.from_pretrained("impira/layoutlm-document-qa", revision="52e01b3")
>>> # Update configuration during loading
>>> model = AutoModelForDocumentQuestionAnswering.from_pretrained("impira/layoutlm-document-qa", revision="52e01b3", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/layoutlm_tf_model_config.json")
>>> model = AutoModelForDocumentQuestionAnswering.from_pretrained(
... "./tf_model/layoutlm_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForDocumentQuestionAnswering
This is a generic model class that will be instantiated as one of the model classes of the library (with a document question answering head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- LayoutLMConfig configuration class: TFLayoutLMForQuestionAnswering (LayoutLM model)
- LayoutLMv3Config configuration class: TFLayoutLMv3ForQuestionAnswering (LayoutLMv3 model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a document question answering head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
Examples:
>>> from transformers import AutoConfig, TFAutoModelForDocumentQuestionAnswering
>>> # Download configuration from huggingface.co and cache.
>>> config = AutoConfig.from_pretrained("impira/layoutlm-document-qa", revision="52e01b3")
>>> model = TFAutoModelForDocumentQuestionAnswering.from_config(config)
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a document question answering head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- layoutlm β TFLayoutLMForQuestionAnswering (LayoutLM model)
- layoutlmv3 β TFLayoutLMv3ForQuestionAnswering (LayoutLMv3 model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForDocumentQuestionAnswering
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForDocumentQuestionAnswering.from_pretrained("impira/layoutlm-document-qa", revision="52e01b3")
>>> # Update configuration during loading
>>> model = TFAutoModelForDocumentQuestionAnswering.from_pretrained("impira/layoutlm-document-qa", revision="52e01b3", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/layoutlm_pt_model_config.json")
>>> model = TFAutoModelForDocumentQuestionAnswering.from_pretrained(
... "./pt_model/layoutlm_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForVisualQuestionAnswering
This is a generic model class that will be instantiated as one of the model classes of the library (with a visual question answering head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- Blip2Config configuration class: Blip2ForConditionalGeneration (BLIP-2 model)
- BlipConfig configuration class: BlipForQuestionAnswering (BLIP model)
- ViltConfig configuration class: ViltForQuestionAnswering (ViLT model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a visual question answering head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a visual question answering head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- blip β BlipForQuestionAnswering (BLIP model)
- blip-2 β Blip2ForConditionalGeneration (BLIP-2 model)
- vilt β ViltForQuestionAnswering (ViLT model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForVisualQuestionAnswering
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForVisualQuestionAnswering.from_pretrained("dandelin/vilt-b32-finetuned-vqa")
>>> # Update configuration during loading
>>> model = AutoModelForVisualQuestionAnswering.from_pretrained("dandelin/vilt-b32-finetuned-vqa", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/vilt_tf_model_config.json")
>>> model = AutoModelForVisualQuestionAnswering.from_pretrained(
... "./tf_model/vilt_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
AutoModelForVision2Seq
This is a generic model class that will be instantiated as one of the model classes of the library (with a vision-to-text modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- Blip2Config configuration class: Blip2ForConditionalGeneration (BLIP-2 model)
- BlipConfig configuration class: BlipForConditionalGeneration (BLIP model)
- ChameleonConfig configuration class: ChameleonForConditionalGeneration (Chameleon model)
- GitConfig configuration class: GitForCausalLM (GIT model)
- Idefics2Config configuration class: Idefics2ForConditionalGeneration (Idefics2 model)
- Idefics3Config configuration class: Idefics3ForConditionalGeneration (Idefics3 model)
- InstructBlipConfig configuration class: InstructBlipForConditionalGeneration (InstructBLIP model)
- InstructBlipVideoConfig configuration class: InstructBlipVideoForConditionalGeneration (InstructBlipVideo model)
- Kosmos2Config configuration class: Kosmos2ForConditionalGeneration (KOSMOS-2 model)
- LlavaConfig configuration class: LlavaForConditionalGeneration (LLaVa model)
- LlavaNextConfig configuration class: LlavaNextForConditionalGeneration (LLaVA-NeXT model)
- LlavaNextVideoConfig configuration class: LlavaNextVideoForConditionalGeneration (LLaVa-NeXT-Video model)
- LlavaOnevisionConfig configuration class: LlavaOnevisionForConditionalGeneration (LLaVA-Onevision model)
- MllamaConfig configuration class: MllamaForConditionalGeneration (Mllama model)
- PaliGemmaConfig configuration class: PaliGemmaForConditionalGeneration (PaliGemma model)
- Pix2StructConfig configuration class: Pix2StructForConditionalGeneration (Pix2Struct model)
- Qwen2VLConfig configuration class: Qwen2VLForConditionalGeneration (Qwen2VL model)
- VideoLlavaConfig configuration class: VideoLlavaForConditionalGeneration (VideoLlava model)
- VipLlavaConfig configuration class: VipLlavaForConditionalGeneration (VipLlava model)
- VisionEncoderDecoderConfig configuration class: VisionEncoderDecoderModel (Vision Encoder decoder model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a vision-to-text modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a vision-to-text modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- blip β BlipForConditionalGeneration (BLIP model)
- blip-2 β Blip2ForConditionalGeneration (BLIP-2 model)
- chameleon β ChameleonForConditionalGeneration (Chameleon model)
- git β GitForCausalLM (GIT model)
- idefics2 β Idefics2ForConditionalGeneration (Idefics2 model)
- idefics3 β Idefics3ForConditionalGeneration (Idefics3 model)
- instructblip β InstructBlipForConditionalGeneration (InstructBLIP model)
- instructblipvideo β InstructBlipVideoForConditionalGeneration (InstructBlipVideo model)
- kosmos-2 β Kosmos2ForConditionalGeneration (KOSMOS-2 model)
- llava β LlavaForConditionalGeneration (LLaVa model)
- llava_next β LlavaNextForConditionalGeneration (LLaVA-NeXT model)
- llava_next_video β LlavaNextVideoForConditionalGeneration (LLaVa-NeXT-Video model)
- llava_onevision β LlavaOnevisionForConditionalGeneration (LLaVA-Onevision model)
- mllama β MllamaForConditionalGeneration (Mllama model)
- paligemma β PaliGemmaForConditionalGeneration (PaliGemma model)
- pix2struct β Pix2StructForConditionalGeneration (Pix2Struct model)
- qwen2_vl β Qwen2VLForConditionalGeneration (Qwen2VL model)
- video_llava β VideoLlavaForConditionalGeneration (VideoLlava model)
- vipllava β VipLlavaForConditionalGeneration (VipLlava model)
- vision-encoder-decoder β VisionEncoderDecoderModel (Vision Encoder decoder model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForVision2Seq
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForVision2Seq.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForVision2Seq.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForVision2Seq.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )
TFAutoModelForVision2Seq
This is a generic model class that will be instantiated as one of the model classes of the library (with a vision-to-text modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- BlipConfig configuration class: TFBlipForConditionalGeneration (BLIP model)
- VisionEncoderDecoderConfig configuration class: TFVisionEncoderDecoderModel (Vision Encoder decoder model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a vision-to-text modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a vision-to-text modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- blip β TFBlipForConditionalGeneration (BLIP model)
- vision-encoder-decoder β TFVisionEncoderDecoderModel (Vision Encoder decoder model)
Examples:
>>> from transformers import AutoConfig, TFAutoModelForVision2Seq
>>> # Download model and configuration from huggingface.co and cache.
>>> model = TFAutoModelForVision2Seq.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = TFAutoModelForVision2Seq.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = TFAutoModelForVision2Seq.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
FlaxAutoModelForVision2Seq
This is a generic model class that will be instantiated as one of the model classes of the library (with a vision-to-text modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- VisionEncoderDecoderConfig configuration class: FlaxVisionEncoderDecoderModel (Vision Encoder decoder model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a vision-to-text modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a PyTorch state_dict save file (e.g,
./pt_model/pytorch_model.bin
). In this case,from_pt
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model using the provided conversion scripts and loading the TensorFlow model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_pt (
bool
, optional, defaults toFalse
) — Load the model weights from a PyTorch checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a vision-to-text modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- vision-encoder-decoder β FlaxVisionEncoderDecoderModel (Vision Encoder decoder model)
Examples:
>>> from transformers import AutoConfig, FlaxAutoModelForVision2Seq
>>> # Download model and configuration from huggingface.co and cache.
>>> model = FlaxAutoModelForVision2Seq.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = FlaxAutoModelForVision2Seq.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
>>> config = AutoConfig.from_pretrained("./pt_model/bert_pt_model_config.json")
>>> model = FlaxAutoModelForVision2Seq.from_pretrained(
... "./pt_model/bert_pytorch_model.bin", from_pt=True, config=config
... )
AutoModelForImageTextToText
This is a generic model class that will be instantiated as one of the model classes of the library (with a image-text-to-text modeling head) when created with the from_pretrained() class method or the from_config() class method.
This class cannot be instantiated directly using __init__()
(throws an error).
from_config
< source >( **kwargs )
Parameters
- config (PretrainedConfig) —
The model class to instantiate is selected based on the configuration class:
- AriaConfig configuration class: AriaForConditionalGeneration (Aria model)
- Blip2Config configuration class: Blip2ForConditionalGeneration (BLIP-2 model)
- BlipConfig configuration class: BlipForConditionalGeneration (BLIP model)
- ChameleonConfig configuration class: ChameleonForConditionalGeneration (Chameleon model)
- FuyuConfig configuration class: FuyuForCausalLM (Fuyu model)
- GitConfig configuration class: GitForCausalLM (GIT model)
- Idefics2Config configuration class: Idefics2ForConditionalGeneration (Idefics2 model)
- Idefics3Config configuration class: Idefics3ForConditionalGeneration (Idefics3 model)
- IdeficsConfig configuration class: IdeficsForVisionText2Text (IDEFICS model)
- InstructBlipConfig configuration class: InstructBlipForConditionalGeneration (InstructBLIP model)
- Kosmos2Config configuration class: Kosmos2ForConditionalGeneration (KOSMOS-2 model)
- LlavaConfig configuration class: LlavaForConditionalGeneration (LLaVa model)
- LlavaNextConfig configuration class: LlavaNextForConditionalGeneration (LLaVA-NeXT model)
- LlavaOnevisionConfig configuration class: LlavaOnevisionForConditionalGeneration (LLaVA-Onevision model)
- MllamaConfig configuration class: MllamaForConditionalGeneration (Mllama model)
- PaliGemmaConfig configuration class: PaliGemmaForConditionalGeneration (PaliGemma model)
- Pix2StructConfig configuration class: Pix2StructForConditionalGeneration (Pix2Struct model)
- PixtralVisionConfig configuration class: LlavaForConditionalGeneration (Pixtral model)
- Qwen2VLConfig configuration class: Qwen2VLForConditionalGeneration (Qwen2VL model)
- UdopConfig configuration class: UdopForConditionalGeneration (UDOP model)
- VipLlavaConfig configuration class: VipLlavaForConditionalGeneration (VipLlava model)
- VisionEncoderDecoderConfig configuration class: VisionEncoderDecoderModel (Vision Encoder decoder model)
- attn_implementation (
str
, optional) — The attention implementation to use in the model (if relevant). Can be any of"eager"
(manual implementation of the attention),"sdpa"
(usingF.scaled_dot_product_attention
), or"flash_attention_2"
(using Dao-AILab/flash-attention). By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual"eager"
implementation.
Instantiates one of the model classes of the library (with a image-text-to-text modeling head) from a configuration.
Note: Loading a model from its configuration file does not load the model weights. It only affects the modelβs configuration. Use from_pretrained() to load the model weights.
from_pretrained
< source >( *model_args **kwargs )
Parameters
- pretrained_model_name_or_path (
str
oros.PathLike
) — Can be either:- A string, the model id of a pretrained model hosted inside a model repo on huggingface.co.
- A path to a directory containing model weights saved using
save_pretrained(), e.g.,
./my_model_directory/
. - A path or url to a tensorflow index checkpoint file (e.g,
./tf_model/model.ckpt.index
). In this case,from_tf
should be set toTrue
and a configuration object should be provided asconfig
argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
- model_args (additional positional arguments, optional) —
Will be passed along to the underlying model
__init__()
method. - config (PretrainedConfig, optional) —
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
be automatically loaded when:
- The model is a model provided by the library (loaded with the model id string of a pretrained model).
- The model was saved using save_pretrained() and is reloaded by supplying the save directory.
- The model is loaded by supplying a local directory as
pretrained_model_name_or_path
and a configuration JSON file named config.json is found in the directory.
- state_dict (Dict[str, torch.Tensor], optional) —
A state dictionary to use instead of a state dictionary loaded from saved weights file.
This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using save_pretrained() and from_pretrained() is not a simpler option.
- cache_dir (
str
oros.PathLike
, optional) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - from_tf (
bool
, optional, defaults toFalse
) — Load the model weights from a TensorFlow checkpoint save file (see docstring ofpretrained_model_name_or_path
argument). - force_download (
bool
, optional, defaults toFalse
) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. - resume_download — Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers.
- proxies (
Dict[str, str]
, optional) — A dictionary of proxy servers to use by protocol or endpoint, e.g.,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on each request. - output_loading_info(
bool
, optional, defaults toFalse
) — Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages. - local_files_only(
bool
, optional, defaults toFalse
) — Whether or not to only look at local files (e.g., not try downloading the model). - revision (
str
, optional, defaults to"main"
) — The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - trust_remote_code (
bool
, optional, defaults toFalse
) — Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set toTrue
for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. - code_revision (
str
, optional, defaults to"main"
) — The specific revision to use for the code on the Hub, if the code leaves in a different repository than the rest of the model. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, sorevision
can be any identifier allowed by git. - kwargs (additional keyword arguments, optional) —
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
output_attentions=True
). Behaves differently depending on whether aconfig
is provided or automatically loaded:- If a configuration is provided with
config
,**kwargs
will be directly passed to the underlying model’s__init__
method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided,
kwargs
will be first passed to the configuration class initialization function (from_pretrained()). Each key ofkwargs
that corresponds to a configuration attribute will be used to override said attribute with the suppliedkwargs
value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s__init__
function.
- If a configuration is provided with
Instantiate one of the model classes of the library (with a image-text-to-text modeling head) from a pretrained model.
The model class to instantiate is selected based on the model_type
property of the config object (either
passed as an argument or loaded from pretrained_model_name_or_path
if possible), or when itβs missing, by
falling back to using pattern matching on pretrained_model_name_or_path
:
- aria β AriaForConditionalGeneration (Aria model)
- blip β BlipForConditionalGeneration (BLIP model)
- blip-2 β Blip2ForConditionalGeneration (BLIP-2 model)
- chameleon β ChameleonForConditionalGeneration (Chameleon model)
- fuyu β FuyuForCausalLM (Fuyu model)
- git β GitForCausalLM (GIT model)
- idefics β IdeficsForVisionText2Text (IDEFICS model)
- idefics2 β Idefics2ForConditionalGeneration (Idefics2 model)
- idefics3 β Idefics3ForConditionalGeneration (Idefics3 model)
- instructblip β InstructBlipForConditionalGeneration (InstructBLIP model)
- kosmos-2 β Kosmos2ForConditionalGeneration (KOSMOS-2 model)
- llava β LlavaForConditionalGeneration (LLaVa model)
- llava_next β LlavaNextForConditionalGeneration (LLaVA-NeXT model)
- llava_onevision β LlavaOnevisionForConditionalGeneration (LLaVA-Onevision model)
- mllama β MllamaForConditionalGeneration (Mllama model)
- paligemma β PaliGemmaForConditionalGeneration (PaliGemma model)
- pix2struct β Pix2StructForConditionalGeneration (Pix2Struct model)
- pixtral β LlavaForConditionalGeneration (Pixtral model)
- qwen2_vl β Qwen2VLForConditionalGeneration (Qwen2VL model)
- udop β UdopForConditionalGeneration (UDOP model)
- vipllava β VipLlavaForConditionalGeneration (VipLlava model)
- vision-encoder-decoder β VisionEncoderDecoderModel (Vision Encoder decoder model)
The model is set in evaluation mode by default using model.eval()
(so for instance, dropout modules are
deactivated). To train the model, you should first set it back in training mode with model.train()
Examples:
>>> from transformers import AutoConfig, AutoModelForImageTextToText
>>> # Download model and configuration from huggingface.co and cache.
>>> model = AutoModelForImageTextToText.from_pretrained("google-bert/bert-base-cased")
>>> # Update configuration during loading
>>> model = AutoModelForImageTextToText.from_pretrained("google-bert/bert-base-cased", output_attentions=True)
>>> model.config.output_attentions
True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
>>> config = AutoConfig.from_pretrained("./tf_model/bert_tf_model_config.json")
>>> model = AutoModelForImageTextToText.from_pretrained(
... "./tf_model/bert_tf_checkpoint.ckpt.index", from_tf=True, config=config
... )