Buckets:
| import"../chunks/DsnmJJEf.js";import{i as N,h as q,C as X,H as t,b as Y,a as d,D as n,E as S,s as E}from"../chunks/B89P_j9O.js";import{p as H,o as A,s as e,f as u,a as r,b as D,c as l,d as c,r as i,n as I}from"../chunks/v-ay6ctG.js";import{T as L}from"../chunks/DTuqSbyr.js";import{E as K}from"../chunks/opS7o4Lw.js";import{H as $}from"../chunks/CJWayN8L.js";const O='{"title":"ColPali","local":"colpali","sections":[{"title":"Notes","local":"notes","sections":[],"depth":2},{"title":"ColPaliConfig","local":"transformers.ColPaliConfig","sections":[],"depth":2},{"title":"ColPaliProcessor","local":"transformers.ColPaliProcessor","sections":[],"depth":2},{"title":"ColPaliForRetrieval","local":"transformers.ColPaliForRetrieval","sections":[],"depth":2}],"depth":1}';var ee=c('<meta name="hf:doc:metadata"/>'),oe=c("<!> <p>If you have issue with loading the images with PIL, you can use the following code to create dummy images:</p> <!>",1),se=c("<p>Example:</p> <!>",1),ae=c(`<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>`),te=c(`<p></p> <p><em>This model was published in HF papers on 2024-06-27 and contributed to Hugging Face Transformers on 2024-12-17.</em></p> <!> <!> <p><a href="https://huggingface.co/papers/2407.01449" rel="nofollow">ColPali</a> is a model designed to retrieve documents by analyzing their visual features. Unlike traditional systems that rely heavily on text extraction and OCR, ColPali treats each page as an image. It uses <a href="./paligemma">Paligemma-3B</a> to capture not only text, but also the layout, tables, charts, and other visual elements to create detailed multi-vector embeddings that can be used for retrieval by computing pairwise late interaction similarity scores. This offers a more comprehensive understanding of documents and enables more efficient and accurate retrieval.</p> <p>This model was contributed by <a href="https://huggingface.co/tonywu71" rel="nofollow">@tonywu71</a> (ILLUIN Technology) and <a href="https://huggingface.co/yonigozlan" rel="nofollow">@yonigozlan</a> (HuggingFace).</p> <p>You can find all the original ColPali checkpoints under Vidore’s <a href="https://huggingface.co/collections/vidore/hf-native-colvision-models-6755d68fc60a8553acaa96f7" rel="nofollow">Hf-native ColVision Models</a> collection.</p> <blockquote class="tip"><p>Click on the ColPali models in the right sidebar for more examples of how to use ColPali for image retrieval.</p></blockquote> <!> <p>Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the <a href="../quantization/overview">Quantization</a> overview for more available quantization backends.</p> <p>The example below uses <a href="../quantization/bitsandbytes">bitsandbytes</a> to quantize the weights to int4.</p> <!> <!> <ul><li><code>score_retrieval()</code> returns a 2D tensor where the first dimension is the number of queries and the second dimension is the number of images. A higher score indicates more similarity between the query and image.</li></ul> <!> <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 ColpaliModel. It is used to instantiate a Colpali | |
| 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/vidore/colpali-v1.2" rel="nofollow">vidore/colpali-v1.2</a></p> <p>Configuration objects inherit from <a href="/docs/transformers/pr_48873/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_48873/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>Constructs a ColPaliProcessor which wraps a image processor and a tokenizer into a single processor.</p> <p><a href="/docs/transformers/pr_48873/en/model_doc/colpali#transformers.ColPaliProcessor">ColPaliProcessor</a> offers all the functionalities of <a href="/docs/transformers/pr_48873/en/model_doc/siglip#transformers.SiglipImageProcessor">SiglipImageProcessor</a> and <code>tokenizer_class</code>. See the <a href="/docs/transformers/pr_48873/en/model_doc/siglip#transformers.SiglipImageProcessor">~SiglipImageProcessor</a> and <code>~tokenizer_class</code> for more information.</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"><!></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 ColPali architecture leverages VLMs to construct efficient multi-vector embeddings directly | |
| from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity | |
| between these document embeddings and the corresponding query embeddings, using the late interaction method | |
| introduced in ColBERT.</p> <p>Using ColPali removes the need for potentially complex and brittle layout recognition and OCR pipelines with a | |
| single model that can take into account both the textual and visual content (layout, charts, etc.) of a document.</p> <p>ColPali is part of the ColVision model family, which was first introduced in the following paper: <a href="https://huggingface.co/papers/2407.01449" rel="nofollow"><em>ColPali: Efficient Document Retrieval with Vision Language Models</em></a>.</p> <p>This model inherits from <a href="/docs/transformers/pr_48873/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_48873/en/model_doc/colpali#transformers.ColPaliForRetrieval">ColPaliForRetrieval</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>embeddings</strong> (<code>torch.FloatTensor</code> of shape <code>(batch_size, sequence_length, hidden_size)</code>) — The embeddings of the model.</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_48873/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 after projecting last hidden state.</p></li></ul></div></div> <!> <p></p>`,1);function pe(P,x){H(x,!1),A(()=>{new URLSearchParams(window.location.search).get("fw")}),N();var g=te();q("1femb22",o=>{var a=ee();E(a,"content",O),r(o,a)});var f=e(u(g),4);X(f,{containerStyle:"float: right; margin-left: 10px; display: inline-flex; position: relative; z-index: 10;"});var y=e(f,2);t(y,{title:"ColPali",local:"colpali",headingTag:"h1"});var M=e(y,10);Y(M,{id:"usage",options:["image retrieval"],children:(o,a)=>{$(o,{id:"usage",option:"image retrieval",children:(s,k)=>{var B=oe(),R=u(B);d(R,{code:"aW1wb3J0JTIwcmVxdWVzdHM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ZW1iZWRkaW5ncyUyMCUzRCUyMG1vZGVsKCoqaW5wdXRzX2ltYWdlcykuZW1iZWRkaW5ncyUwQSUyMCUyMCUyMCUyMHF1ZXJ5X2VtYmVkZGluZ3MlMjAlM0QlMjBtb2RlbCgqKmlucHV0c190ZXh0KS5lbWJlZGRpbmdzJTBBJTBBJTIzJTIwU2NvcmUlMjB0aGUlMjBxdWVyaWVzJTIwYWdhaW5zdCUyMHRoZSUyMGltYWdlcyUwQXNjb3JlcyUyMCUzRCUyMHByb2Nlc3Nvci5zY29yZV9yZXRyaWV2YWwocXVlcnlfZW1iZWRkaW5ncyUyQyUyMGltYWdlX2VtYmVkZGluZ3MpJTBBJTBBcHJpbnQoJTIyUmV0cmlldmFsJTIwc2NvcmVzJTIwKHF1ZXJ5JTIweCUyMGltYWdlKSUzQSUyMiklMEFwcmludChzY29yZXMp",highlighted:`<span class="hljs-keyword">import</span> requests | |
| <span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> ColPaliForRetrieval, ColPaliProcessor | |
| <span class="hljs-comment"># Load the model and the processor</span> | |
| model_name = <span class="hljs-string">"vidore/colpali-v1.3-hf"</span> | |
| model = ColPaliForRetrieval.from_pretrained( | |
| model_name, | |
| device_map=<span class="hljs-string">"auto"</span>, <span class="hljs-comment"># "cpu", "cuda", "xpu", or "mps" for Apple Silicon</span> | |
| ) | |
| processor = ColPaliProcessor.from_pretrained(model_name) | |
| <span class="hljs-comment"># The document page screenshots from your corpus</span> | |
| url1 = <span class="hljs-string">"https://upload.wikimedia.org/wikipedia/commons/8/89/US-original-Declaration-1776.jpg"</span> | |
| url2 = <span class="hljs-string">"https://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Romeoandjuliet1597.jpg/500px-Romeoandjuliet1597.jpg"</span> | |
| images = [ | |
| Image.<span class="hljs-built_in">open</span>(requests.get(url1, stream=<span class="hljs-literal">True</span>).raw), | |
| Image.<span class="hljs-built_in">open</span>(requests.get(url2, stream=<span class="hljs-literal">True</span>).raw), | |
| ] | |
| <span class="hljs-comment"># The queries you want to retrieve documents for</span> | |
| queries = [ | |
| <span class="hljs-string">"When was the United States Declaration of Independence proclaimed?"</span>, | |
| <span class="hljs-string">"Who printed the edition of Romeo and Juliet?"</span>, | |
| ] | |
| <span class="hljs-comment"># Process the inputs</span> | |
| inputs_images = processor(images=images).to(model.device) | |
| inputs_text = processor(text=queries).to(model.device) | |
| <span class="hljs-comment"># Forward pass</span> | |
| <span class="hljs-keyword">with</span> torch.no_grad(): | |
| image_embeddings = model(**inputs_images).embeddings | |
| query_embeddings = model(**inputs_text).embeddings | |
| <span class="hljs-comment"># Score the queries against the images</span> | |
| scores = processor.score_retrieval(query_embeddings, image_embeddings) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">"Retrieval scores (query x image):"</span>) | |
| <span class="hljs-built_in">print</span>(scores)`,lang:"python",wrap:!1});var Q=e(R,4);d(Q,{code:"aW1hZ2VzJTIwJTNEJTIwJTVCJTBBJTIwJTIwJTIwJTIwSW1hZ2UubmV3KCUyMlJHQiUyMiUyQyUyMCgxMjglMkMlMjAxMjgpJTJDJTIwY29sb3IlM0QlMjJ3aGl0ZSUyMiklMkMlMEElMjAlMjAlMjAlMjBJbWFnZS5uZXcoJTIyUkdCJTIyJTJDJTIwKDY0JTJDJTIwMzIpJTJDJTIwY29sb3IlM0QlMjJibGFjayUyMiklMkMlMEElNUQ=",highlighted:`images = [ | |
| Image.new(<span class="hljs-string">"RGB"</span>, (<span class="hljs-number">128</span>, <span class="hljs-number">128</span>), color=<span class="hljs-string">"white"</span>), | |
| Image.new(<span class="hljs-string">"RGB"</span>, (<span class="hljs-number">64</span>, <span class="hljs-number">32</span>), color=<span class="hljs-string">"black"</span>), | |
| ]`,lang:"python",wrap:!1}),r(s,B)},$$slots:{default:!0}})},$$slots:{default:!0}});var b=e(M,6);d(b,{code:"aW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cm9jZXNzb3IodGV4dCUzRHF1ZXJpZXMlMkMlMjByZXR1cm5fdGVuc29ycyUzRCUyMnB0JTIyKS50byhtb2RlbC5kZXZpY2UpJTBBJTBBJTIzJTIwRm9yd2FyZCUyMHBhc3MlMEF3aXRoJTIwdG9yY2gubm9fZ3JhZCgpJTNBJTBBJTIwJTIwJTIwJTIwaW1hZ2VfZW1iZWRkaW5ncyUyMCUzRCUyMG1vZGVsKCoqaW5wdXRzX2ltYWdlcykuZW1iZWRkaW5ncyUwQSUyMCUyMCUyMCUyMHF1ZXJ5X2VtYmVkZGluZ3MlMjAlM0QlMjBtb2RlbCgqKmlucHV0c190ZXh0KS5lbWJlZGRpbmdzJTBBJTBBJTIzJTIwU2NvcmUlMjB0aGUlMjBxdWVyaWVzJTIwYWdhaW5zdCUyMHRoZSUyMGltYWdlcyUwQXNjb3JlcyUyMCUzRCUyMHByb2Nlc3Nvci5zY29yZV9yZXRyaWV2YWwocXVlcnlfZW1iZWRkaW5ncyUyQyUyMGltYWdlX2VtYmVkZGluZ3MpJTBBJTBBcHJpbnQoJTIyUmV0cmlldmFsJTIwc2NvcmVzJTIwKHF1ZXJ5JTIweCUyMGltYWdlKSUzQSUyMiklMEFwcmludChzY29yZXMp",highlighted:`<span class="hljs-keyword">import</span> requests | |
| <span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> BitsAndBytesConfig, ColPaliForRetrieval, ColPaliProcessor | |
| model_name = <span class="hljs-string">"vidore/colpali-v1.3-hf"</span> | |
| <span class="hljs-comment"># 4-bit quantization configuration</span> | |
| bnb_config = BitsAndBytesConfig( | |
| load_in_4bit=<span class="hljs-literal">True</span>, | |
| bnb_4bit_use_double_quant=<span class="hljs-literal">True</span>, | |
| bnb_4bit_quant_type=<span class="hljs-string">"nf4"</span>, | |
| bnb_4bit_compute_dtype=torch.float16, | |
| ) | |
| model = ColPaliForRetrieval.from_pretrained( | |
| model_name, | |
| quantization_config=bnb_config, | |
| device_map=<span class="hljs-string">"auto"</span>, | |
| ) | |
| processor = ColPaliProcessor.from_pretrained(model_name) | |
| url1 = <span class="hljs-string">"https://upload.wikimedia.org/wikipedia/commons/8/89/US-original-Declaration-1776.jpg"</span> | |
| url2 = <span class="hljs-string">"https://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Romeoandjuliet1597.jpg/500px-Romeoandjuliet1597.jpg"</span> | |
| images = [ | |
| Image.<span class="hljs-built_in">open</span>(requests.get(url1, stream=<span class="hljs-literal">True</span>).raw), | |
| Image.<span class="hljs-built_in">open</span>(requests.get(url2, stream=<span class="hljs-literal">True</span>).raw), | |
| ] | |
| queries = [ | |
| <span class="hljs-string">"When was the United States Declaration of Independence proclaimed?"</span>, | |
| <span class="hljs-string">"Who printed the edition of Romeo and Juliet?"</span>, | |
| ] | |
| <span class="hljs-comment"># Process the inputs</span> | |
| inputs_images = processor(images=images, return_tensors=<span class="hljs-string">"pt"</span>).to(model.device) | |
| inputs_text = processor(text=queries, return_tensors=<span class="hljs-string">"pt"</span>).to(model.device) | |
| <span class="hljs-comment"># Forward pass</span> | |
| <span class="hljs-keyword">with</span> torch.no_grad(): | |
| image_embeddings = model(**inputs_images).embeddings | |
| query_embeddings = model(**inputs_text).embeddings | |
| <span class="hljs-comment"># Score the queries against the images</span> | |
| scores = processor.score_retrieval(query_embeddings, image_embeddings) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">"Retrieval scores (query x image):"</span>) | |
| <span class="hljs-built_in">print</span>(scores)`,lang:"python",wrap:!1});var _=e(b,2);t(_,{title:"Notes",local:"notes",headingTag:"h2"});var w=e(_,4);t(w,{title:"ColPaliConfig",local:"transformers.ColPaliConfig",headingTag:"h2"});var p=e(w,2),U=l(p);n(U,{name:"class transformers.ColPaliConfig",anchor:"transformers.ColPaliConfig",source:"https://github.com/huggingface/transformers/blob/vr_48873/src/transformers/models/colpali/configuration_colpali.py#L28",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:"vlm_config",val:": dict | transformers.configuration_utils.PreTrainedConfig | None = None"},{name:"text_config",val:": dict | transformers.configuration_utils.PreTrainedConfig | None = None"},{name:"embedding_dim",val:": int = 128"}],parametersDescription:[{anchor:"transformers.ColPaliConfig.vlm_config",description:`<strong>vlm_config</strong> (<code>Union[dict, ~configuration_utils.PreTrainedConfig]</code>, <em>optional</em>) — | |
| The config object or dictionary of the vision-language backbone.`,name:"vlm_config"},{anchor:"transformers.ColPaliConfig.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.ColPaliConfig.embedding_dim",description:`<strong>embedding_dim</strong> (<code>int</code>, <em>optional</em>, defaults to <code>128</code>) — | |
| Dimensionality of the embeddings and hidden states.`,name:"embedding_dim"}]});var F=e(U,6);K(F,{anchor:"transformers.ColPaliConfig.example",children:(o,a)=>{var s=se(),k=e(u(s),2);d(k,{code:"ZnJvbSUyMHRyYW5zZm9ybWVycy5tb2RlbHMuY29scGFsaSUyMGltcG9ydCUyMENvbFBhbGlDb25maWclMkMlMjBDb2xQYWxpRm9yUmV0cmlldmFsJTBBJTBBY29uZmlnJTIwJTNEJTIwQ29sUGFsaUNvbmZpZygpJTBBbW9kZWwlMjAlM0QlMjBDb2xQYWxpRm9yUmV0cmlldmFsKGNvbmZpZyk=",highlighted:`<span class="hljs-keyword">from</span> transformers.models.colpali <span class="hljs-keyword">import</span> ColPaliConfig, ColPaliForRetrieval | |
| config = ColPaliConfig() | |
| model = ColPaliForRetrieval(config)`,lang:"python",wrap:!1}),r(o,s)},$$slots:{default:!0}}),i(p);var T=e(p,2);t(T,{title:"ColPaliProcessor",local:"transformers.ColPaliProcessor",headingTag:"h2"});var m=e(T,2),v=l(m);n(v,{name:"class transformers.ColPaliProcessor",anchor:"transformers.ColPaliProcessor",source:"https://github.com/huggingface/transformers/blob/vr_48873/src/transformers/models/colpali/processing_colpali.py#L54",parameters:[{name:"image_processor",val:" = None"},{name:"tokenizer",val:" = None"},{name:"chat_template",val:" = None"},{name:"visual_prompt_prefix",val:": str = 'Describe the image.'"},{name:"query_prefix",val:": str = 'Question: '"}],parametersDescription:[{anchor:"transformers.ColPaliProcessor.image_processor",description:`<strong>image_processor</strong> (<code>SiglipImageProcessor</code>) — | |
| The image processor is a required input.`,name:"image_processor"},{anchor:"transformers.ColPaliProcessor.tokenizer",description:`<strong>tokenizer</strong> (<code>tokenizer_class</code>) — | |
| The tokenizer is a required input.`,name:"tokenizer"},{anchor:"transformers.ColPaliProcessor.chat_template",description:`<strong>chat_template</strong> (<code>str</code>) — | |
| A Jinja template to convert lists of messages in a chat into a tokenizable string.`,name:"chat_template"},{anchor:"transformers.ColPaliProcessor.visual_prompt_prefix",description:`<strong>visual_prompt_prefix</strong> (<code>str</code>, <em>optional</em>, defaults to <code>"Describe the image."</code>) — | |
| A string that gets tokenized and prepended to the image tokens.`,name:"visual_prompt_prefix"},{anchor:"transformers.ColPaliProcessor.query_prefix",description:`<strong>query_prefix</strong> (<code>str</code>, <em>optional</em>, defaults to <code>"Question -- "</code>): | |
| A prefix to be used for the query.`,name:"query_prefix"}]});var J=e(v,6),G=l(J);n(G,{name:"__call__",anchor:"transformers.ColPaliProcessor.__call__",source:"https://github.com/huggingface/transformers/blob/vr_48873/src/transformers/models/colpali/processing_colpali.py#L94",parameters:[{name:"images",val:": typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None"},{name:"text",val:": str | list[str] | list[list[str]] = None"},{name:"**kwargs",val:": Unpack"}],parametersDescription:[{anchor:"transformers.ColPaliProcessor.__call__.images",description:`<strong>images</strong> (<code>Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]</code>, <em>optional</em>) — | |
| Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If | |
| passing in images with pixel values between 0 and 1, set <code>do_rescale=False</code>.`,name:"images"},{anchor:"transformers.ColPaliProcessor.__call__.text",description:`<strong>text</strong> (<code>Union[str, list[str], list[list[str]]]</code>, <em>optional</em>) — | |
| The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings | |
| (pretokenized string). If you pass a pretokenized input, set <code>is_split_into_words=True</code> to avoid ambiguity with batched inputs.`,name:"text"},{anchor:"transformers.ColPaliProcessor.__call__.return_tensors",description:`<strong>return_tensors</strong> (<code>str</code> or <a href="/docs/transformers/pr_48873/en/internal/file_utils#transformers.TensorType">TensorType</a>, <em>optional</em>) — | |
| If set, will return tensors of a particular framework. Acceptable values are:</p> | |
| <ul> | |
| <li><code>'pt'</code>: Return PyTorch <code>torch.Tensor</code> objects.</li> | |
| <li><code>'np'</code>: Return NumPy <code>np.ndarray</code> objects.</li> | |
| </ul>`,name:"return_tensors"},{anchor:"transformers.ColPaliProcessor.__call__.*kwargs",description:`*<strong>*kwargs</strong> (<a href="/docs/transformers/pr_48873/en/main_classes/processors#transformers.ProcessingKwargs">ProcessingKwargs</a>, <em>optional</em>) — | |
| Additional processing options for each modality (text, images, videos, audio). Model-specific parameters | |
| are listed above; see the TypedDict class for the complete list of supported arguments.`,name:"*kwargs"}],returnDescription:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p>A <a | |
| href="/docs/transformers/pr_48873/en/main_classes/image_processor#transformers.BatchFeature" | |
| >BatchFeature</a> with the following fields:</p> | |
| <ul> | |
| <li><strong>input_ids</strong> — List of token ids to be fed to a model. Returned when <code>text</code> is not <code>None</code>. If <code>suffix</code> | |
| is provided, the <code>input_ids</code> will also contain the suffix input ids.</li> | |
| <li><strong>attention_mask</strong> — List of indices specifying which tokens should be attended to by the model (when | |
| <code>return_attention_mask=True</code> or if <em>“attention_mask”</em> is in <code>self.model_input_names</code> and if <code>text</code> is not | |
| <code>None</code>).</li> | |
| <li><strong>pixel_values</strong> — Pixel values to be fed to a model. Returned when <code>images</code> is not <code>None</code>.</li> | |
| <li><strong>labels</strong> — Labels compatible with training if <code>suffix</code> is not None</li> | |
| </ul> | |
| `,returnType:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p><a | |
| href="/docs/transformers/pr_48873/en/main_classes/image_processor#transformers.BatchFeature" | |
| >BatchFeature</a></p> | |
| `}),i(J),i(m);var j=e(m,2);t(j,{title:"ColPaliForRetrieval",local:"transformers.ColPaliForRetrieval",headingTag:"h2"});var h=e(j,2),C=l(h);n(C,{name:"class transformers.ColPaliForRetrieval",anchor:"transformers.ColPaliForRetrieval",source:"https://github.com/huggingface/transformers/blob/vr_48873/src/transformers/models/colpali/modeling_colpali.py#L90",parameters:[{name:"config",val:": ColPaliConfig"}],parametersDescription:[{anchor:"transformers.ColPaliForRetrieval.config",description:`<strong>config</strong> (<a href="/docs/transformers/pr_48873/en/model_doc/colpali#transformers.ColPaliConfig">ColPaliConfig</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_48873/en/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a> method to load the model weights.`,name:"config"}]});var Z=e(C,12),W=l(Z);n(W,{name:"forward",anchor:"transformers.ColPaliForRetrieval.forward",source:"https://github.com/huggingface/transformers/blob/vr_48873/src/transformers/models/colpali/modeling_colpali.py#L108",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:"**kwargs",val:": Unpack"}],parametersDescription:[{anchor:"transformers.ColPaliForRetrieval.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_48873/en/model_doc/auto#transformers.AutoTokenizer">AutoTokenizer</a>. See <a href="/docs/transformers/pr_48873/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode">PreTrainedTokenizer.encode()</a> and | |
| <a href="/docs/transformers/pr_48873/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.ColPaliForRetrieval.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.ColPaliForRetrieval.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"}],returnDescription:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p>A <code>ColPaliForRetrievalOutput</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 (<code>None</code>) and inputs.</p> | |
| `,returnType:`<script context="module">export const metadata = 'undefined';<\/script> | |
| <p><code>ColPaliForRetrievalOutput</code> or <code>tuple(torch.FloatTensor)</code></p> | |
| `});var V=e(W,4);L(V,{children:(o,a)=>{var s=ae();r(o,s)},$$slots:{default:!0}}),I(2),i(Z),i(h);var z=e(h,2);S(z,{source:"https://github.com/huggingface/transformers/blob/main/docs/source/en/model_doc/colpali.md"}),I(2),r(P,g),D()}export{pe as component}; | |
Xet Storage Details
- Size:
- 33.3 kB
- Xet hash:
- 1444371b862135e680bc998149e994f8c96fa3b200aef7b8a3e869e7b36ccd99
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.