Buckets:
| import"../chunks/DsnmJJEf.js";import{i as ne,h as ae,C as re,H as s,a as d,D as n,E as le,s as ie}from"../chunks/D6eQvJIN.js";import{p as ce,o as de,s as e,f as p,a as i,b as pe,c as a,d as m,r,n as h}from"../chunks/D9TCMYxZ.js";import{T as L}from"../chunks/eoUhp3Ag.js";import{E as T}from"../chunks/D8azpo8f.js";const he='{"title":"FastVLM","local":"fastvlm","sections":[{"title":"Overview","local":"overview","sections":[],"depth":2},{"title":"Usage tips","local":"usage-tips","sections":[{"title":"Formatting Prompts with Chat Templates","local":"formatting-prompts-with-chat-templates","sections":[],"depth":3}],"depth":2},{"title":"Usage examples","local":"usage-examples","sections":[{"title":"Single input inference","local":"single-input-inference","sections":[],"depth":3},{"title":"Batched inference","local":"batched-inference","sections":[],"depth":3}],"depth":2},{"title":"Note regarding reproducing original implementation","local":"note-regarding-reproducing-original-implementation","sections":[{"title":"Using Flash Attention 2","local":"using-flash-attention-2","sections":[],"depth":3}],"depth":2},{"title":"FastVlmConfig","local":"transformers.FastVlmConfig","sections":[],"depth":2},{"title":"FastVlmModel","local":"transformers.FastVlmModel","sections":[],"depth":2},{"title":"FastVlmForConditionalGeneration","local":"transformers.FastVlmForConditionalGeneration","sections":[],"depth":2}],"depth":1}';var me=m('<meta name="hf:doc:metadata"/>'),b=m("<p>Example:</p> <!>",1),H=m(`<p>Although the recipe for forward pass needs to be defined within this function, one should call the <code>Module</code> instance afterwards instead of this since the former takes care of running the pre and post processing steps while | |
| the latter silently ignores them.</p>`),ue=m(`<p></p> <p><em>This model was published in HF papers on 2024-12-17 and contributed to Hugging Face Transformers on 2025-12-02.</em></p> <!> <!> <div class="flex flex-wrap space-x-1"><img alt="FlashAttention" src="https://img.shields.io/badge/%E2%9A%A1%EF%B8%8E%20FlashAttention-eae0c8?style=flat"/> <img alt="SDPA" src="https://img.shields.io/badge/SDPA-DE3412?style=flat&logo=pytorch&logoColor=white"/></div> <!> <p>FastVLM is an open-source vision-language model featuring a novel hybrid vision encoder, FastViTHD. Leveraging reparameterizable convolutional layers, scaled input resolution, and a reduced number of visual tokens, FastVLM delivers high accuracy with exceptional efficiency. Its optimized architecture enables deployment even on edge devices, achieving ultra-low TTFT (time to first token) without sacrificing performance.</p> <p>The model was proposed in <a href="https://huggingface.co/papers/2412.13303" rel="nofollow">FastVLM: Efficient Vision Encoding for Vision Language Models</a> by Pavan Kumar Anasosalu Vasu, Fartash Faghri, Chun-Liang Li, Cem Koc, Nate True, Albert Antony, Gokul Santhanam, James Gabriel, Peter Grasch, Oncel Tuzel and Hadi Pouransari.</p> <p>The abstract from the paper is the following:</p> <p><em>Scaling the input image resolution is essential for enhancing the performance of Vision Language Models (VLMs), particularly in text-rich image understanding tasks. However, popular visual encoders such as ViTs become inefficient at high resolutions due to the large number of tokens and high encoding latency. At different operational resolutions, the vision encoder of a VLM can be optimized along two axes: reducing encoding latency and minimizing the number of visual tokens passed to the LLM, thereby lowering overall latency. Based on a comprehensive efficiency analysis of the interplay between image resolution, vision latency, token count, and LLM size, we introduce FastVLM—a model that achieves an optimized trade-off between resolution, latency, and accuracy. FastVLM incorporates FastViTHD, a novel hybrid vision encoder designed to output fewer tokens and significantly reduce encoding time for high-resolution images. Unlike previous methods, FastVLM achieves the optimal balance between visual token count and image resolution solely by scaling the input image, eliminating the need for additional token pruning and simplifying the model design. In the LLaVA-1.5 setup, FastVLM achieves 3.2× improvement in time-to-first-token (TTFT) while maintaining similar performance on VLM benchmarks compared to prior works. Compared to LLaVa-OneVision at the highest resolution (1152×1152), FastVLM achieves better performance on key benchmarks like SeedBench, MMMU and DocVQA, using the same 0.5B LLM, but with 85× faster TTFT and a vision encoder that is 3.4× smaller.</em></p> <p>This model was contributed by <a href="https://github.com/kamila-chay" rel="nofollow">Kamila</a>. | |
| The original code can be found <a href="https://github.com/apple/ml-fastvlm" rel="nofollow">here</a>.</p> <!> <ul><li><p>We advise users to use <code>padding_side="left"</code> when computing batched generation as it leads to more accurate results. Simply make sure to call <code>processor.tokenizer.padding_side = "left"</code> before generating.</p></li> <li><p>Note the model has not been explicitly trained to process multiple images in the same prompt, although this is technically possible, you may experience inaccurate results.</p></li></ul> <p><strong>Important:</strong></p> <p>Hugging Face models use SDPA by default; however, this model’s visual backbone supports only eager attention, so it automatically falls back to <code>"eager"</code>.</p> <p>If you want to use a different attention implementation in the language decoder, make sure to set it explicitly, for example:</p> <p><code>model = FastVlmForConditionalGeneration.from_pretrained("KamilaMila/FastVLM-0.5B", attn_implementation={"text_config": "flash_attention_2"}, device_map="auto")</code></p> <p>Setting it for the entire model, e.g.</p> <p><code>model = FastVlmForConditionalGeneration.from_pretrained("KamilaMila/FastVLM-0.5B", attn_implementation="flash_attention_2", device_map="auto")</code></p> <p>will result in an error.</p> <!> <p>Each <strong>checkpoint</strong> is trained with a specific prompt format, depending on the underlying large language model backbone. To ensure correct formatting, use the processor’s <code>apply_chat_template</code> method.</p> <p><strong>Important:</strong></p> <ul><li>You must construct a conversation history — passing a plain string won’t work.</li> <li>Each message should be a dictionary with <code>"role"</code> and <code>"content"</code> keys.</li> <li>The <code>"content"</code> should be a list of dictionaries for different modalities like <code>"text"</code> and <code>"image"</code>.</li></ul> <!> <!> <!> <!> <p>FastVLM also supports batched inference. Here is how you can do it:</p> <!> <!> <p>In order to match the logits of the <a href="https://github.com/apple/ml-fastvlm" rel="nofollow">original implementation</a>, one needs to use float32. In half precision the logit difference is higher due to tiny differences in how some ops are implemented in timm.</p> <!> <p>Flash Attention 2 is an even faster, optimized version of the previous optimization, please refer to the <a href="https://huggingface.co/docs/transformers/perf_infer_gpu_one" rel="nofollow">Flash Attention 2 section of performance docs</a>.</p> <!> <div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"><!> <p>This is the configuration class to store the configuration of a FastVlmModel. It is used to instantiate a Fast Vlm | |
| model according to the specified arguments, defining the model architecture. Instantiating a configuration with the | |
| defaults will yield a similar configuration to that of the <a href="https://huggingface.co/KamilaMila/FastVLM-7B" rel="nofollow">KamilaMila/FastVLM-7B</a></p> <p>Configuration objects inherit from <a href="/docs/transformers/pr_45822/en/main_classes/configuration#transformers.PreTrainedConfig">PreTrainedConfig</a> and can be used to control the model outputs. Read the | |
| documentation from <a href="/docs/transformers/pr_45822/en/main_classes/configuration#transformers.PreTrainedConfig">PreTrainedConfig</a> for more information.</p> <!></div> <!> <div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"><!> <p>The FastVlm model which consists of a vision backbone and a language model, without a language modeling head.</p> <p>This model inherits from <a href="/docs/transformers/pr_45822/en/main_classes/model#transformers.PreTrainedModel">PreTrainedModel</a>. Check the superclass documentation for the generic methods the | |
| library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads | |
| etc.)</p> <p>This model is also a PyTorch <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Module" rel="nofollow">torch.nn.Module</a> subclass. | |
| Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage | |
| and behavior.</p> <div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"><!> <p>The <a href="/docs/transformers/pr_45822/en/model_doc/fast_vlm#transformers.FastVlmModel">FastVlmModel</a> forward method, overrides the <code>__call__</code> special method.</p> <!> <ul><li><p><strong>last_hidden_state</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, sequence_length, hidden_size)</code>) — Sequence of hidden-states at the output of the last layer of the model.</p> <p>If <code>past_key_values</code> is used only the last hidden-state of the sequences of shape <code>(batch_size, 1, hidden_size)</code> is output.</p></li> <li><p><strong>past_key_values</strong> (<code>Cache</code>, <em>optional</em>, returned when <code>use_cache=True</code> is passed or when <code>config.use_cache=True</code>) — It is a <a href="/docs/transformers/pr_45822/en/internal/generation_utils#transformers.Cache">Cache</a> instance. For more details, see our <a href="https://huggingface.co/docs/transformers/en/kv_cache" rel="nofollow">kv cache guide</a>.</p> <p>Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see <code>past_key_values</code> input) to speed up sequential decoding.</p></li> <li><p><strong>hidden_states</strong> (<code>tuple(torch.FloatTensor)</code>, <em>optional</em>, returned when <code>output_hidden_states=True</code> is passed or when <code>config.output_hidden_states=True</code>) — Tuple of <code>torch.FloatTensor</code> (one for the output of the embeddings, if the model has an embedding layer, + | |
| one for the output of each layer) of shape <code>(batch_size, sequence_length, hidden_size)</code>.</p> <p>Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.</p></li> <li><p><strong>attentions</strong> (<code>tuple(torch.FloatTensor)</code>, <em>optional</em>, returned when <code>output_attentions=True</code> is passed or when <code>config.output_attentions=True</code>) — Tuple of <code>torch.FloatTensor</code> (one for each layer) of shape <code>(batch_size, num_heads, sequence_length, sequence_length)</code>.</p> <p>Attentions weights after the attention softmax, used to compute the weighted average in the self-attention | |
| heads.</p></li> <li><p><strong>image_hidden_states</strong> (<code>torch.FloatTensor</code>, <em>optional</em>) — A <code>torch.FloatTensor</code> of size <code>(batch_size, num_images, sequence_length, hidden_size)</code>. | |
| image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.</p></li></ul></div> <div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"><!> <p>Obtains image last hidden states from the vision tower and apply multimodal projection.</p> <ul><li><p><strong>last_hidden_state</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, sequence_length, hidden_size)</code>) — Sequence of hidden-states at the output of the last layer of the model.</p></li> <li><p><strong>pooler_output</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, hidden_size)</code>) — Last layer hidden-state of the first token of the sequence (classification token) after further processing | |
| through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns | |
| the classification token after processing through a linear layer and a tanh activation function. The linear | |
| layer weights are trained from the next sentence prediction (classification) objective during pretraining.</p></li> <li><p><strong>hidden_states</strong> (<code>tuple(torch.FloatTensor)</code>, <em>optional</em>, returned when <code>output_hidden_states=True</code> is passed or when <code>config.output_hidden_states=True</code>) — Tuple of <code>torch.FloatTensor</code> (one for the output of the embeddings, if the model has an embedding layer, + | |
| one for the output of each layer) of shape <code>(batch_size, sequence_length, hidden_size)</code>.</p> <p>Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.</p></li> <li><p><strong>attentions</strong> (<code>tuple(torch.FloatTensor)</code>, <em>optional</em>, returned when <code>output_attentions=True</code> is passed or when <code>config.output_attentions=True</code>) — Tuple of <code>torch.FloatTensor</code> (one for each layer) of shape <code>(batch_size, num_heads, sequence_length, sequence_length)</code>.</p> <p>Attentions weights after the attention softmax, used to compute the weighted average in the self-attention | |
| heads.</p></li></ul></div> <div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"><!> <p>Obtains multimodal placeholder mask from <code>input_ids</code> or <code>inputs_embeds</code>, and checks that the placeholder token count is | |
| equal to the length of multimodal features. If the lengths are different, an error is raised.</p></div></div> <!> <div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"><!> <p>The FastVlm model which consists of a vision backbone and a language model.</p> <p>This model inherits from <a href="/docs/transformers/pr_45822/en/main_classes/model#transformers.PreTrainedModel">PreTrainedModel</a>. Check the superclass documentation for the generic methods the | |
| library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads | |
| etc.)</p> <p>This model is also a PyTorch <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Module" rel="nofollow">torch.nn.Module</a> subclass. | |
| Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage | |
| and behavior.</p> <div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"><!> <p>The <a href="/docs/transformers/pr_45822/en/model_doc/fast_vlm#transformers.FastVlmForConditionalGeneration">FastVlmForConditionalGeneration</a> forward method, overrides the <code>__call__</code> special method.</p> <!> <ul><li><p><strong>loss</strong> (<code>torch.FloatTensor</code> of shape <code>(1,)</code>, <em>optional</em>, returned when <code>labels</code> is provided) — Language modeling loss (for next-token prediction).</p></li> <li><p><strong>logits</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, sequence_length, config.vocab_size)</code>) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).</p></li> <li><p><strong>past_key_values</strong> (<code>Cache</code>, <em>optional</em>, returned when <code>use_cache=True</code> is passed or when <code>config.use_cache=True</code>) — It is a <a href="/docs/transformers/pr_45822/en/internal/generation_utils#transformers.Cache">Cache</a> instance. For more details, see our <a href="https://huggingface.co/docs/transformers/en/kv_cache" rel="nofollow">kv cache guide</a>.</p> <p>Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see <code>past_key_values</code> input) to speed up sequential decoding.</p></li> <li><p><strong>hidden_states</strong> (<code>tuple[torch.FloatTensor]</code>, <em>optional</em>, returned when <code>output_hidden_states=True</code> is passed or when <code>config.output_hidden_states=True</code>) — Tuple of <code>torch.FloatTensor</code> (one for the output of the embeddings, if the model has an embedding layer, + | |
| one for the output of each layer) of shape <code>(batch_size, sequence_length, hidden_size)</code>.</p> <p>Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.</p></li> <li><p><strong>attentions</strong> (<code>tuple[torch.FloatTensor]</code>, <em>optional</em>, returned when <code>output_attentions=True</code> is passed or when <code>config.output_attentions=True</code>) — Tuple of <code>torch.FloatTensor</code> (one for each layer) of shape <code>(batch_size, num_heads, sequence_length, sequence_length)</code>.</p> <p>Attentions weights after the attention softmax, used to compute the weighted average in the self-attention | |
| heads.</p></li> <li><p><strong>image_hidden_states</strong> (<code>torch.FloatTensor</code>, <em>optional</em>) — A <code>torch.FloatTensor</code> of size <code>(batch_size, num_images, sequence_length, hidden_size)</code>. | |
| image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.</p></li></ul> <!></div> <div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"><!> <ul><li><p><strong>last_hidden_state</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, sequence_length, hidden_size)</code>) — Sequence of hidden-states at the output of the last layer of the model.</p></li> <li><p><strong>pooler_output</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, hidden_size)</code>) — Last layer hidden-state of the first token of the sequence (classification token) after further processing | |
| through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns | |
| the classification token after processing through a linear layer and a tanh activation function. The linear | |
| layer weights are trained from the next sentence prediction (classification) objective during pretraining.</p></li> <li><p><strong>hidden_states</strong> (<code>tuple(torch.FloatTensor)</code>, <em>optional</em>, returned when <code>output_hidden_states=True</code> is passed or when <code>config.output_hidden_states=True</code>) — Tuple of <code>torch.FloatTensor</code> (one for the output of the embeddings, if the model has an embedding layer, + | |
| one for the output of each layer) of shape <code>(batch_size, sequence_length, hidden_size)</code>.</p> <p>Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.</p></li> <li><p><strong>attentions</strong> (<code>tuple(torch.FloatTensor)</code>, <em>optional</em>, returned when <code>output_attentions=True</code> is passed or when <code>config.output_attentions=True</code>) — Tuple of <code>torch.FloatTensor</code> (one for each layer) of shape <code>(batch_size, num_heads, sequence_length, sequence_length)</code>.</p> <p>Attentions weights after the attention softmax, used to compute the weighted average in the self-attention | |
| heads.</p></li></ul> <!></div></div> <!> <p></p>`,1);function Te(P,D){ce(D,!1),de(()=>{new URLSearchParams(window.location.search).get("fw")}),ne();var J=ue();ae("ftnxju",t=>{var l=me();ie(l,"content",he),i(t,l)});var v=e(p(J),4);re(v,{containerStyle:"float: right; margin-left: 10px; display: inline-flex; position: relative; z-index: 10;"});var w=e(v,2);s(w,{title:"FastVLM",local:"fastvlm",headingTag:"h1"});var j=e(w,4);s(j,{title:"Overview",local:"overview",headingTag:"h2"});var U=e(j,12);s(U,{title:"Usage tips",local:"usage-tips",headingTag:"h2"});var F=e(U,18);s(F,{title:"Formatting Prompts with Chat Templates",local:"formatting-prompts-with-chat-templates",headingTag:"h3"});var I=e(F,8);s(I,{title:"Usage examples",local:"usage-examples",headingTag:"h2"});var k=e(I,2);s(k,{title:"Single input inference",local:"single-input-inference",headingTag:"h3"});var C=e(k,2);d(C,{code:"aW1wb3J0JTIwdG9yY2glMEElMEFmcm9tJTIwdHJhbnNmb3JtZXJzJTIwaW1wb3J0JTIwQXV0b1Byb2Nlc3NvciUyQyUyMEZhc3RWbG1Gb3JDb25kaXRpb25hbEdlbmVyYXRpb24lMEElMEElMEElMjMlMjBMb2FkJTIwdGhlJTIwbW9kZWwlMjBpbiUyMGhhbGYtcHJlY2lzaW9uJTBBbW9kZWwlMjAlM0QlMjBGYXN0VmxtRm9yQ29uZGl0aW9uYWxHZW5lcmF0aW9uLmZyb21fcHJldHJhaW5lZCglMjJLYW1pbGFNaWxhJTJGRmFzdFZMTS0wLjVCJTIyJTJDJTIwZGV2aWNlX21hcCUzRCUyMmF1dG8lMjIpJTBBcHJvY2Vzc29yJTIwJTNEJTIwQXV0b1Byb2Nlc3Nvci5mcm9tX3ByZXRyYWluZWQoJTIyS2FtaWxhTWlsYSUyRkZhc3RWTE0tMC41QiUyMiklMEElMEFjb252ZXJzYXRpb24lMjAlM0QlMjAlNUIlMEElMjAlMjAlMjAlMjAlN0IlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjJyb2xlJTIyJTNBJTIwJTIydXNlciUyMiUyQyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMmNvbnRlbnQlMjIlM0ElMjAlNUIlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlN0IlMjJ0eXBlJTIyJTNBJTIwJTIyaW1hZ2UlMjIlMkMlMjAlMjJ1cmwlMjIlM0ElMjAlMjJodHRwcyUzQSUyRiUyRnd3dy5pbGFua2VsbWFuLm9yZyUyRnN0b3BzaWducyUyRmF1c3RyYWxpYS5qcGclMjIlN0QlMkMlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlN0IlMjJ0eXBlJTIyJTNBJTIwJTIydGV4dCUyMiUyQyUyMCUyMnRleHQlMjIlM0ElMjAlMjJXaGF0JTIwaXMlMjBzaG93biUyMGluJTIwdGhpcyUyMGltYWdlJTNGJTIyJTdEJTJDJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTVEJTJDJTBBJTIwJTIwJTIwJTIwJTdEJTJDJTBBJTVEJTBBJTBBaW5wdXRzJTIwJTNEJTIwcHJvY2Vzc29yLmFwcGx5X2NoYXRfdGVtcGxhdGUoJTBBJTIwJTIwJTIwJTIwY29udmVyc2F0aW9uJTJDJTBBJTIwJTIwJTIwJTIwYWRkX2dlbmVyYXRpb25fcHJvbXB0JTNEVHJ1ZSUyQyUwQSUyMCUyMCUyMCUyMHRva2VuaXplJTNEVHJ1ZSUyQyUwQSUyMCUyMCUyMCUyMHJldHVybl9kaWN0JTNEVHJ1ZSUyQyUwQSUyMCUyMCUyMCUyMHJldHVybl90ZW5zb3JzJTNEJTIycHQlMjIlMEEpLnRvKG1vZGVsLmRldmljZSUyQyUyMHRvcmNoLmJmbG9hdDE2KSUwQSUwQSUyMyUyMEdlbmVyYXRlJTBBZ2VuZXJhdGVfaWRzJTIwJTNEJTIwbW9kZWwuZ2VuZXJhdGUoKippbnB1dHMlMkMlMjBtYXhfbmV3X3Rva2VucyUzRDMwKSUwQXByb2Nlc3Nvci5iYXRjaF9kZWNvZGUoZ2VuZXJhdGVfaWRzJTJDJTIwc2tpcF9zcGVjaWFsX3Rva2VucyUzRFRydWUp",highlighted:`<span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoProcessor, FastVlmForConditionalGeneration | |
| <span class="hljs-comment"># Load the model in half-precision</span> | |
| model = FastVlmForConditionalGeneration.from_pretrained(<span class="hljs-string">"KamilaMila/FastVLM-0.5B"</span>, device_map=<span class="hljs-string">"auto"</span>) | |
| processor = AutoProcessor.from_pretrained(<span class="hljs-string">"KamilaMila/FastVLM-0.5B"</span>) | |
| conversation = [ | |
| { | |
| <span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, | |
| <span class="hljs-string">"content"</span>: [ | |
| {<span class="hljs-string">"type"</span>: <span class="hljs-string">"image"</span>, <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://www.ilankelman.org/stopsigns/australia.jpg"</span>}, | |
| {<span class="hljs-string">"type"</span>: <span class="hljs-string">"text"</span>, <span class="hljs-string">"text"</span>: <span class="hljs-string">"What is shown in this image?"</span>}, | |
| ], | |
| }, | |
| ] | |
| inputs = processor.apply_chat_template( | |
| conversation, | |
| add_generation_prompt=<span class="hljs-literal">True</span>, | |
| tokenize=<span class="hljs-literal">True</span>, | |
| return_dict=<span class="hljs-literal">True</span>, | |
| return_tensors=<span class="hljs-string">"pt"</span> | |
| ).to(model.device, torch.bfloat16) | |
| <span class="hljs-comment"># Generate</span> | |
| generate_ids = model.generate(**inputs, max_new_tokens=<span class="hljs-number">30</span>) | |
| processor.batch_decode(generate_ids, skip_special_tokens=<span class="hljs-literal">True</span>)`,lang:"python",wrap:!1});var V=e(C,2);s(V,{title:"Batched inference",local:"batched-inference",headingTag:"h3"});var B=e(V,4);d(B,{code:"aW1wb3J0JTIwdG9yY2glMEElMEFmcm9tJTIwdHJhbnNmb3JtZXJzJTIwaW1wb3J0JTIwQXV0b1Byb2Nlc3NvciUyQyUyMEZhc3RWbG1Gb3JDb25kaXRpb25hbEdlbmVyYXRpb24lMEElMEElMEElMjMlMjBMb2FkJTIwdGhlJTIwbW9kZWwlMjBpbiUyMGhhbGYtcHJlY2lzaW9uJTBBbW9kZWwlMjAlM0QlMjBGYXN0VmxtRm9yQ29uZGl0aW9uYWxHZW5lcmF0aW9uLmZyb21fcHJldHJhaW5lZCglMjJLYW1pbGFNaWxhJTJGRmFzdFZMTS0wLjVCJTIyJTJDJTIwZGV2aWNlX21hcCUzRCUyMmF1dG8lMjIpJTBBcHJvY2Vzc29yJTIwJTNEJTIwQXV0b1Byb2Nlc3Nvci5mcm9tX3ByZXRyYWluZWQoJTIyS2FtaWxhTWlsYSUyRkZhc3RWTE0tMC41QiUyMiklMEElMEElMEElMjMlMjBQcmVwYXJlJTIwYSUyMGJhdGNoJTIwb2YlMjB0d28lMjBwcm9tcHRzJTBBY29udmVyc2F0aW9uXzElMjAlM0QlMjAlNUIlMEElMjAlMjAlMjAlMjAlN0IlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjJyb2xlJTIyJTNBJTIwJTIydXNlciUyMiUyQyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMmNvbnRlbnQlMjIlM0ElMjAlNUIlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlN0IlMjJ0eXBlJTIyJTNBJTIwJTIyaW1hZ2UlMjIlMkMlMjAlMjJ1cmwlMjIlM0ElMjAlMjJodHRwcyUzQSUyRiUyRnd3dy5pbGFua2VsbWFuLm9yZyUyRnN0b3BzaWducyUyRmF1c3RyYWxpYS5qcGclMjIlN0QlMkMlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlN0IlMjJ0eXBlJTIyJTNBJTIwJTIydGV4dCUyMiUyQyUyMCUyMnRleHQlMjIlM0ElMjAlMjJXaGF0JTIwaXMlMjBzaG93biUyMGluJTIwdGhpcyUyMGltYWdlJTNGJTIyJTdEJTJDJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTVEJTJDJTBBJTIwJTIwJTIwJTIwJTdEJTJDJTBBJTVEJTBBJTBBY29udmVyc2F0aW9uXzIlMjAlM0QlMjAlNUIlMEElMjAlMjAlMjAlMjAlN0IlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjJyb2xlJTIyJTNBJTIwJTIydXNlciUyMiUyQyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMmNvbnRlbnQlMjIlM0ElMjAlNUIlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlN0IlMjJ0eXBlJTIyJTNBJTIwJTIyaW1hZ2UlMjIlMkMlMjAlMjJ1cmwlMjIlM0ElMjAlMjJodHRwJTNBJTJGJTJGaW1hZ2VzLmNvY29kYXRhc2V0Lm9yZyUyRnZhbDIwMTclMkYwMDAwMDAwMzk3NjkuanBnJTIyJTdEJTJDJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTdCJTIydHlwZSUyMiUzQSUyMCUyMnRleHQlMjIlMkMlMjAlMjJ0ZXh0JTIyJTNBJTIwJTIyV2hhdCUyMGlzJTIwc2hvd24lMjBpbiUyMHRoaXMlMjBpbWFnZSUzRiUyMiU3RCUyQyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCU1RCUyQyUwQSUyMCUyMCUyMCUyMCU3RCUyQyUwQSU1RCUwQSUwQWlucHV0cyUyMCUzRCUyMHByb2Nlc3Nvci5hcHBseV9jaGF0X3RlbXBsYXRlKCUwQSUyMCUyMCUyMCUyMCU1QmNvbnZlcnNhdGlvbl8xJTJDJTIwY29udmVyc2F0aW9uXzIlNUQlMkMlMEElMjAlMjAlMjAlMjBhZGRfZ2VuZXJhdGlvbl9wcm9tcHQlM0RUcnVlJTJDJTBBJTIwJTIwJTIwJTIwdG9rZW5pemUlM0RUcnVlJTJDJTBBJTIwJTIwJTIwJTIwcmV0dXJuX2RpY3QlM0RUcnVlJTJDJTBBJTIwJTIwJTIwJTIwcGFkZGluZyUzRFRydWUlMkMlMEElMjAlMjAlMjAlMjByZXR1cm5fdGVuc29ycyUzRCUyMnB0JTIyJTBBKS50byhtb2RlbC5kZXZpY2UlMkMlMjB0b3JjaC5iZmxvYXQxNiklMEElMEElMEElMjMlMjBHZW5lcmF0ZSUwQWdlbmVyYXRlX2lkcyUyMCUzRCUyMG1vZGVsLmdlbmVyYXRlKCoqaW5wdXRzJTJDJTIwbWF4X25ld190b2tlbnMlM0QzMCklMEFwcm9jZXNzb3IuYmF0Y2hfZGVjb2RlKGdlbmVyYXRlX2lkcyUyQyUyMHNraXBfc3BlY2lhbF90b2tlbnMlM0RUcnVlKQ==",highlighted:`<span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoProcessor, FastVlmForConditionalGeneration | |
| <span class="hljs-comment"># Load the model in half-precision</span> | |
| model = FastVlmForConditionalGeneration.from_pretrained(<span class="hljs-string">"KamilaMila/FastVLM-0.5B"</span>, device_map=<span class="hljs-string">"auto"</span>) | |
| processor = AutoProcessor.from_pretrained(<span class="hljs-string">"KamilaMila/FastVLM-0.5B"</span>) | |
| <span class="hljs-comment"># Prepare a batch of two prompts</span> | |
| conversation_1 = [ | |
| { | |
| <span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, | |
| <span class="hljs-string">"content"</span>: [ | |
| {<span class="hljs-string">"type"</span>: <span class="hljs-string">"image"</span>, <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://www.ilankelman.org/stopsigns/australia.jpg"</span>}, | |
| {<span class="hljs-string">"type"</span>: <span class="hljs-string">"text"</span>, <span class="hljs-string">"text"</span>: <span class="hljs-string">"What is shown in this image?"</span>}, | |
| ], | |
| }, | |
| ] | |
| conversation_2 = [ | |
| { | |
| <span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, | |
| <span class="hljs-string">"content"</span>: [ | |
| {<span class="hljs-string">"type"</span>: <span class="hljs-string">"image"</span>, <span class="hljs-string">"url"</span>: <span class="hljs-string">"http://images.cocodataset.org/val2017/000000039769.jpg"</span>}, | |
| {<span class="hljs-string">"type"</span>: <span class="hljs-string">"text"</span>, <span class="hljs-string">"text"</span>: <span class="hljs-string">"What is shown in this image?"</span>}, | |
| ], | |
| }, | |
| ] | |
| inputs = processor.apply_chat_template( | |
| [conversation_1, conversation_2], | |
| add_generation_prompt=<span class="hljs-literal">True</span>, | |
| tokenize=<span class="hljs-literal">True</span>, | |
| return_dict=<span class="hljs-literal">True</span>, | |
| padding=<span class="hljs-literal">True</span>, | |
| return_tensors=<span class="hljs-string">"pt"</span> | |
| ).to(model.device, torch.bfloat16) | |
| <span class="hljs-comment"># Generate</span> | |
| generate_ids = model.generate(**inputs, max_new_tokens=<span class="hljs-number">30</span>) | |
| processor.batch_decode(generate_ids, skip_special_tokens=<span class="hljs-literal">True</span>)`,lang:"python",wrap:!1});var W=e(B,2);s(W,{title:"Note regarding reproducing original implementation",local:"note-regarding-reproducing-original-implementation",headingTag:"h2"});var q=e(W,4);s(q,{title:"Using Flash Attention 2",local:"using-flash-attention-2",headingTag:"h3"});var G=e(q,4);s(G,{title:"FastVlmConfig",local:"transformers.FastVlmConfig",headingTag:"h2"});var u=e(G,2),x=a(u);n(x,{name:"class transformers.FastVlmConfig",anchor:"transformers.FastVlmConfig",source:"https://github.com/huggingface/transformers/blob/vr_45822/src/transformers/models/fast_vlm/configuration_fast_vlm.py#L31",parameters:[{name:"transformers_version",val:": str | None = None"},{name:"architectures",val:": list[str] | None = None"},{name:"output_hidden_states",val:": bool | None = False"},{name:"return_dict",val:": bool | None = True"},{name:"dtype",val:": str | torch.dtype | None = None"},{name:"chunk_size_feed_forward",val:": int = 0"},{name:"is_encoder_decoder",val:": bool = False"},{name:"id2label",val:": dict[int, str] | dict[str, str] | None = None"},{name:"label2id",val:": dict[str, int] | dict[str, str] | None = None"},{name:"problem_type",val:": Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None"},{name:"vision_config",val:": dict | transformers.configuration_utils.PreTrainedConfig | None = None"},{name:"text_config",val:": dict | transformers.configuration_utils.PreTrainedConfig | None = None"},{name:"image_token_index",val:": int = 151646"},{name:"image_seq_length",val:": int = 576"},{name:"projector_hidden_act",val:": str = 'gelu'"},{name:"vision_feature_select_strategy",val:": str = 'full'"},{name:"vision_feature_layer",val:": int | list[int] = -1"},{name:"multimodal_projector_bias",val:": bool = True"},{name:"tie_word_embeddings",val:": bool = False"}],parametersDescription:[{anchor:"transformers.FastVlmConfig.vision_config",description:`<strong>vision_config</strong> (<code>Union[dict, ~configuration_utils.PreTrainedConfig]</code>, <em>optional</em>) — | |
| The config object or dictionary of the vision backbone.`,name:"vision_config"},{anchor:"transformers.FastVlmConfig.text_config",description:`<strong>text_config</strong> (<code>Union[dict, ~configuration_utils.PreTrainedConfig]</code>, <em>optional</em>) — | |
| The config object or dictionary of the text backbone.`,name:"text_config"},{anchor:"transformers.FastVlmConfig.image_token_index",description:`<strong>image_token_index</strong> (<code>int</code>, <em>optional</em>, defaults to <code>151646</code>) — | |
| The image token index used as a placeholder for input images.`,name:"image_token_index"},{anchor:"transformers.FastVlmConfig.image_seq_length",description:`<strong>image_seq_length</strong> (<code>int</code>, <em>optional</em>, defaults to <code>576</code>) — | |
| Sequence length of one image embedding.`,name:"image_seq_length"},{anchor:"transformers.FastVlmConfig.projector_hidden_act",description:`<strong>projector_hidden_act</strong> (<code>str</code>, <em>optional</em>, defaults to <code>gelu</code>) — | |
| The activation function used by the multimodal projector.`,name:"projector_hidden_act"},{anchor:"transformers.FastVlmConfig.vision_feature_select_strategy",description:`<strong>vision_feature_select_strategy</strong> (<code>str</code>, <em>optional</em>, defaults to <code>full</code>) — | |
| The feature selection strategy used to select the vision feature from the vision backbone.`,name:"vision_feature_select_strategy"},{anchor:"transformers.FastVlmConfig.vision_feature_layer",description:`<strong>vision_feature_layer</strong> (<code>Union[int, list[int]]</code>, <em>optional</em>, defaults to <code>-1</code>) — | |
| The index of the layer to select the vision feature. If multiple indices are provided, | |
| the vision feature of the corresponding indices will be concatenated to form the | |
| vision features.`,name:"vision_feature_layer"},{anchor:"transformers.FastVlmConfig.multimodal_projector_bias",description:`<strong>multimodal_projector_bias</strong> (<code>bool</code>, <em>optional</em>, defaults to <code>True</code>) — | |
| Whether to use bias in the multimodal projector.`,name:"multimodal_projector_bias"},{anchor:"transformers.FastVlmConfig.tie_word_embeddings",description:`<strong>tie_word_embeddings</strong> (<code>bool</code>, <em>optional</em>, defaults to <code>False</code>) — | |
| Whether to tie weight embeddings according to model’s <code>tied_weights_keys</code> mapping.`,name:"tie_word_embeddings"}]});var O=e(x,6);T(O,{anchor:"transformers.FastVlmConfig.example",children:(t,l)=>{var o=b(),c=e(p(o),2);d(c,{code:"ZnJvbSUyMHRyYW5zZm9ybWVycyUyMGltcG9ydCUyMEZhc3RWbG1Gb3JDb25kaXRpb25hbEdlbmVyYXRpb24lMkMlMjBGYXN0VmxtQ29uZmlnJTBBJTBBJTIzJTIwSW5pdGlhbGl6aW5nJTIwYSUyMEZhc3RWTE0tN0IlMjBzdHlsZSUyMGNvbmZpZ3VyYXRpb24lMEFjb25maWd1cmF0aW9uJTIwJTNEJTIwRmFzdFZsbUNvbmZpZygpJTBBJTBBJTIzJTIwSW5pdGlhbGl6aW5nJTIwYSUyMG1vZGVsJTIwZnJvbSUyMHRoZSUyMEZhc3RWTE0tN0IlMjBzdHlsZSUyMGNvbmZpZ3VyYXRpb24lMEFtb2RlbCUyMCUzRCUyMEZhc3RWbG1Gb3JDb25kaXRpb25hbEdlbmVyYXRpb24oY29uZmlndXJhdGlvbiklMEElMEElMjMlMjBBY2Nlc3NpbmclMjB0aGUlMjBtb2RlbCUyMGNvbmZpZ3VyYXRpb24lMEFjb25maWd1cmF0aW9uJTIwJTNEJTIwbW9kZWwuY29uZmln",highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> FastVlmForConditionalGeneration, FastVlmConfig | |
| <span class="hljs-meta">>>> </span><span class="hljs-comment"># Initializing a FastVLM-7B style configuration</span> | |
| <span class="hljs-meta">>>> </span>configuration = FastVlmConfig() | |
| <span class="hljs-meta">>>> </span><span class="hljs-comment"># Initializing a model from the FastVLM-7B style configuration</span> | |
| <span class="hljs-meta">>>> </span>model = FastVlmForConditionalGeneration(configuration) | |
| <span class="hljs-meta">>>> </span><span class="hljs-comment"># Accessing the model configuration</span> | |
| <span class="hljs-meta">>>> </span>configuration = model.config`,lang:"python",wrap:!1}),i(t,o)},$$slots:{default:!0}}),r(u);var Z=e(u,2);s(Z,{title:"FastVlmModel",local:"transformers.FastVlmModel",headingTag:"h2"});var g=e(Z,2),z=a(g);n(z,{name:"class transformers.FastVlmModel",anchor:"transformers.FastVlmModel",source:"https://github.com/huggingface/transformers/blob/vr_45822/src/transformers/models/fast_vlm/modeling_fast_vlm.py#L101",parameters:[{name:"config",val:": FastVlmConfig"}],parametersDescription:[{anchor:"transformers.FastVlmModel.config",description:`<strong>config</strong> (<a href="/docs/transformers/pr_45822/en/model_doc/fast_vlm#transformers.FastVlmConfig">FastVlmConfig</a>) — | |
| Model configuration class with all the parameters of the model. Initializing with a config file does not | |
| load the weights associated with the model, only the configuration. Check out the | |
| <a href="/docs/transformers/pr_45822/en/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> method to load the model weights.`,name:"config"}]});var f=e(z,8),N=a(f);n(N,{name:"forward",anchor:"transformers.FastVlmModel.forward",source:"https://github.com/huggingface/transformers/blob/vr_45822/src/transformers/models/fast_vlm/modeling_fast_vlm.py#L164",parameters:[{name:"input_ids",val:": typing.Optional[torch.LongTensor] = None"},{name:"pixel_values",val:": typing.Optional[torch.FloatTensor] = None"},{name:"attention_mask",val:": typing.Optional[torch.Tensor] = None"},{name:"position_ids",val:": typing.Optional[torch.LongTensor] = None"},{name:"past_key_values",val:": transformers.cache_utils.Cache | None = None"},{name:"inputs_embeds",val:": typing.Optional[torch.FloatTensor] = None"},{name:"vision_feature_layer",val:": int | list[int] | None = None"},{name:"vision_feature_select_strategy",val:": str | None = None"},{name:"mm_encoder_outputs",val:": dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None"},{name:"**kwargs",val:": *<class 'transformers.utils.generic.TransformersKwargs'>"}],parametersDescription:[{anchor:"transformers.FastVlmModel.forward.input_ids",description:`<strong>input_ids</strong> (<code>torch.LongTensor</code> of shape <code>(batch_size, sequence_length)</code>, <em>optional</em>) — | |
| Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.</p> | |
| <p>Indices can be obtained using <a href="/docs/transformers/pr_45822/en/model_doc/auto#transformers.AutoTokenizer">AutoTokenizer</a>. See <a href="/docs/transformers/pr_45822/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode">PreTrainedTokenizer.encode()</a> and | |
| <a href="/docs/transformers/pr_45822/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__">PreTrainedTokenizer.<strong>call</strong>()</a> for details.</p> | |
| <p><a href="../glossary#input-ids">What are input IDs?</a>`,name:"input_ids"},{anchor:"transformers.FastVlmModel.forward.pixel_values",description:`<strong>pixel_values</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, num_channels, image_size, image_size)</code>, <em>optional</em>) — | |
| The tensors corresponding to the input images. Pixel values can be obtained using | |
| <code>image_processor_class</code>. See <code>image_processor_class.__call__</code> for details (<code>processor_class</code> uses | |
| <code>image_processor_class</code> for processing images).`,name:"pixel_values"},{anchor:"transformers.FastVlmModel.forward.attention_mask",description:`<strong>attention_mask</strong> (<code>torch.Tensor</code> of shape <code>(batch_size, sequence_length)</code>, <em>optional</em>) — | |
| Mask to avoid performing attention on padding token indices. Mask values selected in <code>[0, 1]</code>:</p> | |
| <ul> | |
| <li>1 for tokens that are <strong>not masked</strong>,</li> | |
| <li>0 for tokens that are <strong>masked</strong>.</li> | |
| </ul> | |
| <p><a href="../glossary#attention-mask">What are attention masks?</a>`,name:"attention_mask"},{anchor:"transformers.FastVlmModel.forward.position_ids",description:`<strong>position_ids</strong> (<code>torch.LongTensor</code> of shape <code>(batch_size, sequence_length)</code>, <em>optional</em>) — | |
| Indices of positions of each input sequence tokens in the position embeddings. Selected in the range <code>[0, config.n_positions - 1]</code>.</p> | |
| <p><a href="../glossary#position-ids">What are position IDs?</a>`,name:"position_ids"},{anchor:"transformers.FastVlmModel.forward.past_key_values",description:`<strong>past_key_values</strong> (<code>~cache_utils.Cache</code>, <em>optional</em>) — | |
| Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention | |
| blocks) that can be used to speed up sequential decoding. This typically consists in the <code>past_key_values</code> | |
| returned by the model at a previous stage of decoding, when <code>use_cache=True</code> or <code>config.use_cache=True</code>.</p> | |
| <p>Only <a href="/docs/transformers/pr_45822/en/internal/generation_utils#transformers.Cache">Cache</a> instance is allowed as input, see our <a href="https://huggingface.co/docs/transformers/en/kv_cache" rel="nofollow">kv cache guide</a>. | |
| If no <code>past_key_values</code> are passed, <a href="/docs/transformers/pr_45822/en/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> will be initialized by default.</p> | |
| <p>The model will output the same cache format that is fed as input.</p> | |
| <p>If <code>past_key_values</code> are used, the user is expected to input only unprocessed <code>input_ids</code> (those that don’t | |
| have their past key value states given to this model) of shape <code>(batch_size, unprocessed_length)</code> instead of all <code>input_ids</code> | |
| of shape <code>(batch_size, sequence_length)</code>.`,name:"past_key_values"},{anchor:"transformers.FastVlmModel.forward.inputs_embeds",description:`<strong>inputs_embeds</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, sequence_length, hidden_size)</code>, <em>optional</em>) — | |
| Optionally, instead of passing <code>input_ids</code> you can choose to directly pass an embedded representation. This | |
| is useful if you want more control over how to convert <code>input_ids</code> indices into associated vectors than the | |
| model’s internal embedding lookup matrix.`,name:"inputs_embeds"},{anchor:"transformers.FastVlmModel.forward.vision_feature_layer",description:`<strong>vision_feature_layer</strong> (<code>Union[int, list[int], NoneType]</code>, <em>optional</em>) — | |
| The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the | |
| corresponding indices will be concatenated to form the vision features. Only -1 supported.`,name:"vision_feature_layer"},{anchor:"transformers.FastVlmModel.forward.vision_feature_select_strategy",description:`<strong>vision_feature_select_strategy</strong> (<code>str</code>, <em>optional</em>) — | |
| The feature selection strategy used to select the vision feature from the vision backbone. Only “full” supported.`,name:"vision_feature_select_strategy"},{anchor:"transformers.FastVlmModel.forward.mm_encoder_outputs",description:`<strong>mm_encoder_outputs</strong> (<code>dict[str, ~modeling_outputs.BaseModelOutputWithPooling]</code>, <em>optional</em>) — | |
| Dict where keys are supported modalities and values are encoded outputs for that modality. Each encoded output is a tuple | |
| that consists of (<code>pooler_output</code>, <em>optional</em>: <code>last_hidden_states</code>, <em>optional</em>: <code>hidden_states</code>, <em>optional</em>: <code>attentions</code>) | |
| <code>pooler_output</code> of shape <code>(batch_size, sequence_length, hidden_size)</code>, <em>optional</em>) is a sequence of | |
| multimmodal features of the encoder merged into text embeddings.`,name:"mm_encoder_outputs"}],returnDescription:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p>A <code>FastVlmModelOutputWithPast</code> or a tuple of | |
| <code>torch.FloatTensor</code> (if <code>return_dict=False</code> is passed or when <code>config.return_dict=False</code>) comprising various | |
| elements depending on the configuration (<a | |
| href="/docs/transformers/pr_45822/en/model_doc/fast_vlm#transformers.FastVlmConfig" | |
| >FastVlmConfig</a>) and inputs.</p> | |
| `,returnType:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p><code>FastVlmModelOutputWithPast</code> or <code>tuple(torch.FloatTensor)</code></p> | |
| `});var K=e(N,4);L(K,{children:(t,l)=>{var o=H();i(t,o)},$$slots:{default:!0}}),h(2),r(f);var _=e(f,2),$=a(_);n($,{name:"get_image_features",anchor:"transformers.FastVlmModel.get_image_features",source:"https://github.com/huggingface/transformers/blob/vr_45822/src/transformers/models/fast_vlm/modeling_fast_vlm.py#L110",parameters:[{name:"pixel_values",val:": FloatTensor"},{name:"vision_feature_layer",val:": int | list[int] | None = None"},{name:"vision_feature_select_strategy",val:": str | None = None"},{name:"**kwargs",val:": *<class 'transformers.utils.generic.TransformersKwargs'>"}],parametersDescription:[{anchor:"transformers.FastVlmModel.get_image_features.pixel_values",description:`<strong>pixel_values</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, channels, height, width)</code>) — | |
| The tensors corresponding to the input images.`,name:"pixel_values"},{anchor:"transformers.FastVlmModel.get_image_features.vision_feature_layer",description:`<strong>vision_feature_layer</strong> (<code>Union[int, list[int]]</code>, <em>optional</em>) — | |
| The index/indices of the layer to select the vision feature. Only -1 supported.`,name:"vision_feature_layer"},{anchor:"transformers.FastVlmModel.get_image_features.vision_feature_select_strategy",description:`<strong>vision_feature_select_strategy</strong> (<code>str</code>, <em>optional</em>) — | |
| The feature selection strategy used to select the vision feature from the vision backbone. | |
| Only “full” supported.`,name:"vision_feature_select_strategy"}],returnDescription:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p>A <a | |
| href="/docs/transformers/pr_45822/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling" | |
| >BaseModelOutputWithPooling</a> or a tuple of | |
| <code>torch.FloatTensor</code> (if <code>return_dict=False</code> is passed or when <code>config.return_dict=False</code>) comprising various | |
| elements depending on the configuration (<a | |
| href="/docs/transformers/pr_45822/en/model_doc/fast_vlm#transformers.FastVlmConfig" | |
| >FastVlmConfig</a>) and inputs.</p> | |
| `,returnType:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p><a | |
| href="/docs/transformers/pr_45822/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling" | |
| >BaseModelOutputWithPooling</a> or <code>tuple(torch.FloatTensor)</code></p> | |
| `}),h(4),r(_);var A=e(_,2),ee=a(A);n(ee,{name:"get_placeholder_mask",anchor:"transformers.FastVlmModel.get_placeholder_mask",source:"https://github.com/huggingface/transformers/blob/vr_45822/src/transformers/models/fast_vlm/modeling_fast_vlm.py#L140",parameters:[{name:"input_ids",val:": LongTensor"},{name:"inputs_embeds",val:": FloatTensor"},{name:"image_features",val:": FloatTensor"}]}),h(2),r(A),r(g);var E=e(g,2);s(E,{title:"FastVlmForConditionalGeneration",local:"transformers.FastVlmForConditionalGeneration",headingTag:"h2"});var y=e(E,2),R=a(y);n(R,{name:"class transformers.FastVlmForConditionalGeneration",anchor:"transformers.FastVlmForConditionalGeneration",source:"https://github.com/huggingface/transformers/blob/vr_45822/src/transformers/models/fast_vlm/modeling_fast_vlm.py#L263",parameters:[{name:"config",val:": FastVlmConfig"}],parametersDescription:[{anchor:"transformers.FastVlmForConditionalGeneration.config",description:`<strong>config</strong> (<a href="/docs/transformers/pr_45822/en/model_doc/fast_vlm#transformers.FastVlmConfig">FastVlmConfig</a>) — | |
| Model configuration class with all the parameters of the model. Initializing with a config file does not | |
| load the weights associated with the model, only the configuration. Check out the | |
| <a href="/docs/transformers/pr_45822/en/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> method to load the model weights.`,name:"config"}]});var M=e(R,8),X=a(M);n(X,{name:"forward",anchor:"transformers.FastVlmForConditionalGeneration.forward",source:"https://github.com/huggingface/transformers/blob/vr_45822/src/transformers/models/fast_vlm/modeling_fast_vlm.py#L291",parameters:[{name:"input_ids",val:": typing.Optional[torch.LongTensor] = None"},{name:"pixel_values",val:": typing.Optional[torch.FloatTensor] = None"},{name:"attention_mask",val:": typing.Optional[torch.Tensor] = None"},{name:"position_ids",val:": typing.Optional[torch.LongTensor] = None"},{name:"past_key_values",val:": transformers.cache_utils.Cache | None = None"},{name:"inputs_embeds",val:": typing.Optional[torch.FloatTensor] = None"},{name:"vision_feature_layer",val:": int | list[int] | None = None"},{name:"vision_feature_select_strategy",val:": str | None = None"},{name:"labels",val:": typing.Optional[torch.LongTensor] = None"},{name:"logits_to_keep",val:": typing.Union[int, torch.Tensor] = 0"},{name:"mm_encoder_outputs",val:": dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None"},{name:"**kwargs",val:": *<class 'transformers.utils.generic.TransformersKwargs'>"}],parametersDescription:[{anchor:"transformers.FastVlmForConditionalGeneration.forward.input_ids",description:`<strong>input_ids</strong> (<code>torch.LongTensor</code> of shape <code>(batch_size, sequence_length)</code>, <em>optional</em>) — | |
| Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.</p> | |
| <p>Indices can be obtained using <a href="/docs/transformers/pr_45822/en/model_doc/auto#transformers.AutoTokenizer">AutoTokenizer</a>. See <a href="/docs/transformers/pr_45822/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode">PreTrainedTokenizer.encode()</a> and | |
| <a href="/docs/transformers/pr_45822/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__">PreTrainedTokenizer.<strong>call</strong>()</a> for details.</p> | |
| <p><a href="../glossary#input-ids">What are input IDs?</a>`,name:"input_ids"},{anchor:"transformers.FastVlmForConditionalGeneration.forward.pixel_values",description:`<strong>pixel_values</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, num_channels, image_size, image_size)</code>, <em>optional</em>) — | |
| The tensors corresponding to the input images. Pixel values can be obtained using | |
| <code>image_processor_class</code>. See <code>image_processor_class.__call__</code> for details (<code>processor_class</code> uses | |
| <code>image_processor_class</code> for processing images).`,name:"pixel_values"},{anchor:"transformers.FastVlmForConditionalGeneration.forward.attention_mask",description:`<strong>attention_mask</strong> (<code>torch.Tensor</code> of shape <code>(batch_size, sequence_length)</code>, <em>optional</em>) — | |
| Mask to avoid performing attention on padding token indices. Mask values selected in <code>[0, 1]</code>:</p> | |
| <ul> | |
| <li>1 for tokens that are <strong>not masked</strong>,</li> | |
| <li>0 for tokens that are <strong>masked</strong>.</li> | |
| </ul> | |
| <p><a href="../glossary#attention-mask">What are attention masks?</a>`,name:"attention_mask"},{anchor:"transformers.FastVlmForConditionalGeneration.forward.position_ids",description:`<strong>position_ids</strong> (<code>torch.LongTensor</code> of shape <code>(batch_size, sequence_length)</code>, <em>optional</em>) — | |
| Indices of positions of each input sequence tokens in the position embeddings. Selected in the range <code>[0, config.n_positions - 1]</code>.</p> | |
| <p><a href="../glossary#position-ids">What are position IDs?</a>`,name:"position_ids"},{anchor:"transformers.FastVlmForConditionalGeneration.forward.past_key_values",description:`<strong>past_key_values</strong> (<code>~cache_utils.Cache</code>, <em>optional</em>) — | |
| Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention | |
| blocks) that can be used to speed up sequential decoding. This typically consists in the <code>past_key_values</code> | |
| returned by the model at a previous stage of decoding, when <code>use_cache=True</code> or <code>config.use_cache=True</code>.</p> | |
| <p>Only <a href="/docs/transformers/pr_45822/en/internal/generation_utils#transformers.Cache">Cache</a> instance is allowed as input, see our <a href="https://huggingface.co/docs/transformers/en/kv_cache" rel="nofollow">kv cache guide</a>. | |
| If no <code>past_key_values</code> are passed, <a href="/docs/transformers/pr_45822/en/internal/generation_utils#transformers.DynamicCache">DynamicCache</a> will be initialized by default.</p> | |
| <p>The model will output the same cache format that is fed as input.</p> | |
| <p>If <code>past_key_values</code> are used, the user is expected to input only unprocessed <code>input_ids</code> (those that don’t | |
| have their past key value states given to this model) of shape <code>(batch_size, unprocessed_length)</code> instead of all <code>input_ids</code> | |
| of shape <code>(batch_size, sequence_length)</code>.`,name:"past_key_values"},{anchor:"transformers.FastVlmForConditionalGeneration.forward.inputs_embeds",description:`<strong>inputs_embeds</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, sequence_length, hidden_size)</code>, <em>optional</em>) — | |
| Optionally, instead of passing <code>input_ids</code> you can choose to directly pass an embedded representation. This | |
| is useful if you want more control over how to convert <code>input_ids</code> indices into associated vectors than the | |
| model’s internal embedding lookup matrix.`,name:"inputs_embeds"},{anchor:"transformers.FastVlmForConditionalGeneration.forward.vision_feature_layer",description:`<strong>vision_feature_layer</strong> (<code>Union[int, list[int], NoneType]</code>, <em>optional</em>) — | |
| The index of the layer to select the vision feature. If multiple indices are provided, the vision feature of the | |
| corresponding indices will be concatenated to form the vision features. Only -1 supported.`,name:"vision_feature_layer"},{anchor:"transformers.FastVlmForConditionalGeneration.forward.vision_feature_select_strategy",description:`<strong>vision_feature_select_strategy</strong> (<code>str</code>, <em>optional</em>) — | |
| The feature selection strategy used to select the vision feature from the vision backbone. Only “full” supported.`,name:"vision_feature_select_strategy"},{anchor:"transformers.FastVlmForConditionalGeneration.forward.labels",description:`<strong>labels</strong> (<code>torch.LongTensor</code> of shape <code>(batch_size, sequence_length)</code>, <em>optional</em>) — | |
| Labels for computing the masked language modeling loss. Indices should either be in <code>[0, ..., config.vocab_size]</code> or -100 (see <code>input_ids</code> docstring). Tokens with indices set to <code>-100</code> are ignored | |
| (masked), the loss is only computed for the tokens with labels in <code>[0, ..., config.vocab_size]</code>.`,name:"labels"},{anchor:"transformers.FastVlmForConditionalGeneration.forward.logits_to_keep",description:`<strong>logits_to_keep</strong> (<code>Union[int, torch.Tensor]</code>, <em>optional</em>, defaults to <code>0</code>) — | |
| If an <code>int</code>, compute logits for the last <code>logits_to_keep</code> tokens. If <code>0</code>, calculate logits for all | |
| <code>input_ids</code> (special case). Only last token logits are needed for generation, and calculating them only for that | |
| token can save memory, which becomes pretty significant for long sequences or large vocabulary size. | |
| If a <code>torch.Tensor</code>, must be 1D corresponding to the indices to keep in the sequence length dimension. | |
| This is useful when using packed tensor format (single dimension for batch and sequence length).`,name:"logits_to_keep"},{anchor:"transformers.FastVlmForConditionalGeneration.forward.mm_encoder_outputs",description:`<strong>mm_encoder_outputs</strong> (<code>dict[str, ~modeling_outputs.BaseModelOutputWithPooling]</code>, <em>optional</em>) — | |
| Dict where keys are supported modalities and values are encoded outputs for that modality. Each encoded output is a tuple | |
| that consists of (<code>pooler_output</code>, <em>optional</em>: <code>last_hidden_states</code>, <em>optional</em>: <code>hidden_states</code>, <em>optional</em>: <code>attentions</code>) | |
| <code>pooler_output</code> of shape <code>(batch_size, sequence_length, hidden_size)</code>, <em>optional</em>) is a sequence of | |
| multimmodal features of the encoder merged into text embeddings.`,name:"mm_encoder_outputs"}],returnDescription:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p>A <code>FastVlmCausalLMOutputWithPast</code> or a tuple of | |
| <code>torch.FloatTensor</code> (if <code>return_dict=False</code> is passed or when <code>config.return_dict=False</code>) comprising various | |
| elements depending on the configuration (<a | |
| href="/docs/transformers/pr_45822/en/model_doc/fast_vlm#transformers.FastVlmConfig" | |
| >FastVlmConfig</a>) and inputs.</p> | |
| `,returnType:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p><code>FastVlmCausalLMOutputWithPast</code> or <code>tuple(torch.FloatTensor)</code></p> | |
| `});var Y=e(X,4);L(Y,{children:(t,l)=>{var o=H();i(t,o)},$$slots:{default:!0}});var te=e(Y,4);T(te,{anchor:"transformers.FastVlmForConditionalGeneration.forward.example",children:(t,l)=>{var o=b(),c=e(p(o),2);d(c,{code:"ZnJvbSUyMFBJTCUyMGltcG9ydCUyMEltYWdlJTBBZnJvbSUyMGh1Z2dpbmdmYWNlX2h1Yi51dGlscyUyMGltcG9ydCUyMGh0dHB4JTBBZnJvbSUyMGlvJTIwaW1wb3J0JTIwQnl0ZXNJTyUwQWZyb20lMjB0cmFuc2Zvcm1lcnMlMjBpbXBvcnQlMjBBdXRvUHJvY2Vzc29yJTJDJTIwQXV0b01vZGVsRm9ySW1hZ2VUZXh0VG9UZXh0JTBBaW1wb3J0JTIwdG9yY2glMEElMEFkZXZpY2UlMjAlM0QlMjAlMjJjdWRhJTIyJTIwaWYlMjB0b3JjaC5jdWRhLmlzX2F2YWlsYWJsZSgpJTIwZWxzZSUyMCUyMmNwdSUyMiUwQSUwQW1vZGVsJTIwJTNEJTIwQXV0b01vZGVsRm9ySW1hZ2VUZXh0VG9UZXh0LmZyb21fcHJldHJhaW5lZCglMjJLYW1pbGFNaWxhJTJGRmFzdFZMTS0wLjVCJTIyKS50byhkZXZpY2UpJTBBcHJvY2Vzc29yJTIwJTNEJTIwQXV0b1Byb2Nlc3Nvci5mcm9tX3ByZXRyYWluZWQoJTIyS2FtaWxhTWlsYSUyRkZhc3RWTE0tMC41QiUyMiklMEElMEFjb252ZXJzYXRpb24lMjAlM0QlMjAlNUIlMEElMEFwcm9tcHQlMjAlM0QlMjBwcm9jZXNzb3IuYXBwbHlfY2hhdF90ZW1wbGF0ZShjb252ZXJzYXRpb24lMkMlMjBhZGRfZ2VuZXJhdGlvbl9wcm9tcHQlM0RUcnVlKSUwQXVybCUyMCUzRCUyMCUyMmh0dHBzJTNBJTJGJTJGd3d3LmlsYW5rZWxtYW4ub3JnJTJGc3RvcHNpZ25zJTJGYXVzdHJhbGlhLmpwZyUyMiUwQXdpdGglMjBodHRweC5zdHJlYW0oJTIyR0VUJTIyJTJDJTIwdXJsKSUyMGFzJTIwcmVzcG9uc2UlM0ElMEElMjAlMjAlMjAlMjBpbWFnZSUyMCUzRCUyMEltYWdlLm9wZW4oQnl0ZXNJTyhyZXNwb25zZS5yZWFkKCkpKSUwQSUwQWlucHV0cyUyMCUzRCUyMHByb2Nlc3NvcihpbWFnZXMlM0RpbWFnZSUyQyUyMHRleHQlM0Rwcm9tcHQlMkMlMjByZXR1cm5fdGVuc29ycyUzRCUyMnB0JTIyKS50byhkZXZpY2UpJTBBJTBBJTIzJTIwR2VuZXJhdGUlMEFnZW5lcmF0ZWRfaWRzJTIwJTNEJTIwbW9kZWwuZ2VuZXJhdGUoKippbnB1dHMlMkMlMjBtYXhfbmV3X3Rva2VucyUzRDE1KSUwQXByaW50KHByb2Nlc3Nvci5iYXRjaF9kZWNvZGUoZ2VuZXJhdGVkX2lkcyUyQyUyMHNraXBfc3BlY2lhbF90b2tlbnMlM0RUcnVlJTJDJTIwY2xlYW5fdXBfdG9rZW5pemF0aW9uX3NwYWNlcyUzREZhbHNlKSU1QjAlNUQp",highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> huggingface_hub.utils <span class="hljs-keyword">import</span> httpx | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> io <span class="hljs-keyword">import</span> BytesIO | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoProcessor, AutoModelForImageTextToText | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-meta">>>> </span>device = <span class="hljs-string">"cuda"</span> <span class="hljs-keyword">if</span> torch.cuda.is_available() <span class="hljs-keyword">else</span> <span class="hljs-string">"cpu"</span> | |
| <span class="hljs-meta">>>> </span>model = AutoModelForImageTextToText.from_pretrained(<span class="hljs-string">"KamilaMila/FastVLM-0.5B"</span>).to(device) | |
| <span class="hljs-meta">>>> </span>processor = AutoProcessor.from_pretrained(<span class="hljs-string">"KamilaMila/FastVLM-0.5B"</span>) | |
| <span class="hljs-meta">>>> </span>conversation = [ | |
| { | |
| <span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, | |
| <span class="hljs-string">"content"</span>: [ | |
| {<span class="hljs-string">"type"</span>: <span class="hljs-string">"text"</span>, <span class="hljs-string">"text"</span>: <span class="hljs-string">"What are these?"</span>}, | |
| {<span class="hljs-string">"type"</span>: <span class="hljs-string">"image"</span>} | |
| ] | |
| } | |
| ] | |
| <span class="hljs-meta">>>> </span>prompt = processor.apply_chat_template(conversation, add_generation_prompt=<span class="hljs-literal">True</span>) | |
| <span class="hljs-meta">>>> </span>url = <span class="hljs-string">"https://www.ilankelman.org/stopsigns/australia.jpg"</span> | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">with</span> httpx.stream(<span class="hljs-string">"GET"</span>, url) <span class="hljs-keyword">as</span> response: | |
| <span class="hljs-meta">... </span> image = Image.<span class="hljs-built_in">open</span>(BytesIO(response.read())) | |
| <span class="hljs-meta">>>> </span>inputs = processor(images=image, text=prompt, return_tensors=<span class="hljs-string">"pt"</span>).to(device) | |
| <span class="hljs-meta">>>> </span><span class="hljs-comment"># Generate</span> | |
| <span class="hljs-meta">>>> </span>generated_ids = model.generate(**inputs, max_new_tokens=<span class="hljs-number">15</span>) | |
| <span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(processor.batch_decode(generated_ids, skip_special_tokens=<span class="hljs-literal">True</span>, clean_up_tokenization_spaces=<span class="hljs-literal">False</span>)[<span class="hljs-number">0</span>]) | |
| system\\n You are a helpful assistant.\\n user\\n What are these?\\n assistant\\n The image depicts a traditional Chinese street...`,lang:"python",wrap:!1}),i(t,o)},$$slots:{default:!0}}),r(M);var Q=e(M,2),S=a(Q);n(S,{name:"get_image_features",anchor:"transformers.FastVlmForConditionalGeneration.get_image_features",source:"https://github.com/huggingface/transformers/blob/vr_45822/src/transformers/models/fast_vlm/modeling_fast_vlm.py#L276",parameters:[{name:"pixel_values",val:": FloatTensor"},{name:"vision_feature_layer",val:": int | list[int] | None = None"},{name:"vision_feature_select_strategy",val:": str | None = None"},{name:"**kwargs",val:": *<class 'transformers.utils.generic.TransformersKwargs'>"}],parametersDescription:[{anchor:"transformers.FastVlmForConditionalGeneration.get_image_features.pixel_values",description:`<strong>pixel_values</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, num_channels, image_size, image_size)</code>) — | |
| The tensors corresponding to the input images. Pixel values can be obtained using | |
| <code>image_processor_class</code>. See <code>image_processor_class.__call__</code> for details (<code>processor_class</code> uses | |
| <code>image_processor_class</code> for processing images).`,name:"pixel_values"},{anchor:"transformers.FastVlmForConditionalGeneration.get_image_features.vision_feature_layer",description:`<strong>vision_feature_layer</strong> (<code>Union[int, list[int]]</code>, <em>optional</em>) — | |
| The index of the layer to select the vision feature. If multiple indices are provided, | |
| the vision feature of the corresponding indices will be concatenated to form the | |
| vision features.`,name:"vision_feature_layer"},{anchor:"transformers.FastVlmForConditionalGeneration.get_image_features.vision_feature_select_strategy",description:`<strong>vision_feature_select_strategy</strong> (<code>str</code>, <em>optional</em>) — | |
| The feature selection strategy used to select the vision feature from the vision backbone. | |
| Can be one of <code>"default"</code> or <code>"full"</code>.`,name:"vision_feature_select_strategy"}],returnDescription:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p>A <a | |
| href="/docs/transformers/pr_45822/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling" | |
| >BaseModelOutputWithPooling</a> or a tuple of | |
| <code>torch.FloatTensor</code> (if <code>return_dict=False</code> is passed or when <code>config.return_dict=False</code>) comprising various | |
| elements depending on the configuration (<a | |
| href="/docs/transformers/pr_45822/en/model_doc/fast_vlm#transformers.FastVlmConfig" | |
| >FastVlmConfig</a>) and inputs.</p> | |
| `,returnType:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p><a | |
| href="/docs/transformers/pr_45822/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling" | |
| >BaseModelOutputWithPooling</a> or <code>tuple(torch.FloatTensor)</code></p> | |
| `});var oe=e(S,4);T(oe,{anchor:"transformers.FastVlmForConditionalGeneration.get_image_features.example",children:(t,l)=>{var o=b(),c=e(p(o),2);d(c,{code:"ZnJvbSUyMFBJTCUyMGltcG9ydCUyMEltYWdlJTBBZnJvbSUyMHRyYW5zZm9ybWVycyUyMGltcG9ydCUyMEF1dG9Qcm9jZXNzb3IlMkMlMjBGYXN0VmxtRm9yQ29uZGl0aW9uYWxHZW5lcmF0aW9uJTBBJTBBbW9kZWwlMjAlM0QlMjBGYXN0VmxtRm9yQ29uZGl0aW9uYWxHZW5lcmF0aW9uLmZyb21fcHJldHJhaW5lZCglMjJLYW1pbGFNaWxhJTJGRmFzdFZMTS03QiUyMiklMEFwcm9jZXNzb3IlMjAlM0QlMjBBdXRvUHJvY2Vzc29yLmZyb21fcHJldHJhaW5lZCglMjJLYW1pbGFNaWxhJTJGRmFzdFZMTS03QiUyMiklMEElMEFtZXNzYWdlcyUyMCUzRCUyMCU1QiUwQSUyMCUyMCUyMCUyMCU3QiUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMnJvbGUlMjIlM0ElMjAlMjJ1c2VyJTIyJTJDJTIwJTIyY29udGVudCUyMiUzQSUyMCU1QiUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCU3QiUyMnR5cGUlMjIlM0ElMjAlMjJpbWFnZSUyMiUyQyUyMCUyMnVybCUyMiUzQSUyMCUyMmh0dHBzJTNBJTJGJTJGaHVnZ2luZ2ZhY2UuY28lMkZkYXRhc2V0cyUyRmh1Z2dpbmdmYWNlJTJGZG9jdW1lbnRhdGlvbi1pbWFnZXMlMkZyZXNvbHZlJTJGbWFpbiUyRnBpcGVsaW5lLWNhdC1jaG9uay5qcGVnJTIyJTdEJTJDJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTdCJTIydHlwZSUyMiUzQSUyMCUyMnRleHQlMjIlMkMlMjAlMjJ0ZXh0JTIyJTNBJTIwJTIyV2hlcmUlMjBpcyUyMHRoZSUyMGNhdCUyMHN0YW5kaW5nJTNGJTIyJTdEJTJDJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTVEJTBBJTIwJTIwJTIwJTIwJTdEJTJDJTBBJTVEJTBBJTBBaW5wdXRzJTIwJTNEJTIwcHJvY2Vzc29yLmFwcGx5X2NoYXRfdGVtcGxhdGUoJTBBJTIwJTIwJTIwJTIwbWVzc2FnZXMlMkMlMEElMjAlMjAlMjAlMjB0b2tlbml6ZSUzRFRydWUlMkMlMEElMjAlMjAlMjAlMjByZXR1cm5fZGljdCUzRFRydWUlMkMlMEElMjAlMjAlMjAlMjByZXR1cm5fdGVuc29ycyUzRCUyMnB0JTIyJTJDJTBBJTIwJTIwJTIwJTIwYWRkX2dlbmVyYXRpb25fcHJvbXB0JTNEVHJ1ZSUwQSklMEElMjMlMjBHZW5lcmF0ZSUwQWdlbmVyYXRlX2lkcyUyMCUzRCUyMG1vZGVsLmdlbmVyYXRlKCoqaW5wdXRzKSUwQXByb2Nlc3Nvci5iYXRjaF9kZWNvZGUoZ2VuZXJhdGVfaWRzJTJDJTIwc2tpcF9zcGVjaWFsX3Rva2VucyUzRFRydWUpJTVCMCU1RA==",highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoProcessor, FastVlmForConditionalGeneration | |
| <span class="hljs-meta">>>> </span>model = FastVlmForConditionalGeneration.from_pretrained(<span class="hljs-string">"KamilaMila/FastVLM-7B"</span>) | |
| <span class="hljs-meta">>>> </span>processor = AutoProcessor.from_pretrained(<span class="hljs-string">"KamilaMila/FastVLM-7B"</span>) | |
| <span class="hljs-meta">>>> </span>messages = [ | |
| <span class="hljs-meta">... </span> { | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: [ | |
| <span class="hljs-meta">... </span> {<span class="hljs-string">"type"</span>: <span class="hljs-string">"image"</span>, <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"</span>}, | |
| <span class="hljs-meta">... </span> {<span class="hljs-string">"type"</span>: <span class="hljs-string">"text"</span>, <span class="hljs-string">"text"</span>: <span class="hljs-string">"Where is the cat standing?"</span>}, | |
| <span class="hljs-meta">... </span> ] | |
| <span class="hljs-meta">... </span> }, | |
| <span class="hljs-meta">... </span>] | |
| <span class="hljs-meta">>>> </span>inputs = processor.apply_chat_template( | |
| <span class="hljs-meta">... </span> messages, | |
| <span class="hljs-meta">... </span> tokenize=<span class="hljs-literal">True</span>, | |
| <span class="hljs-meta">... </span> return_dict=<span class="hljs-literal">True</span>, | |
| <span class="hljs-meta">... </span> return_tensors=<span class="hljs-string">"pt"</span>, | |
| <span class="hljs-meta">... </span> add_generation_prompt=<span class="hljs-literal">True</span> | |
| <span class="hljs-meta">... </span>) | |
| <span class="hljs-meta">>>> </span><span class="hljs-comment"># Generate</span> | |
| <span class="hljs-meta">>>> </span>generate_ids = model.generate(**inputs) | |
| <span class="hljs-meta">>>> </span>processor.batch_decode(generate_ids, skip_special_tokens=<span class="hljs-literal">True</span>)[<span class="hljs-number">0</span>]`,lang:"python",wrap:!1}),i(t,o)},$$slots:{default:!0}}),r(Q),r(y);var se=e(y,2);le(se,{source:"https://github.com/huggingface/transformers/blob/main/docs/source/en/model_doc/fast_vlm.md"}),h(2),i(P,J),pe()}export{Te as component}; | |
Xet Storage Details
- Size:
- 69.7 kB
- Xet hash:
- 871af06fe198d2d2240ff884acfdc2c11e5bea45b7383d74460d90eadbfa2470
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.