# Chameleon

## 概述

Chameleon 模型由 META AI Chameleon Team 在 [Chameleon: Mixed-Modal Early-Fusion Foundation Models](https://huggingface.co/papers/2405.09818) 中提出。Chameleon 是一个视觉-语言模型，它使用向量量化对图像进行分词，从而使模型能够生成多模态输出。该模型以图像和文本作为输入（包括交错格式），并生成文本响应。图像生成模块尚未发布。

该论文的摘要如下：

*我们提出了 Chameleon，这是一个早期融合（early-fusion）的基于 token 的混合模态模型家族，能够理解和生成任意序列中的图像和文本。我们概述了一种从初始阶段就稳定的训练方法、一种对齐方案，以及一种专为早期融合、基于 token 的混合模态场景定制的架构参数化。这些模型在广泛的任务上进行了评估，包括视觉问答、图像描述、文本生成、图像生成以及长文本混合模态生成。Chameleon 展示了广泛且通用的能力，包括在图像描述任务上达到最先进的性能，在纯文本任务上优于 Llama-2，同时与 Mixtral 8x7B 和 Gemini-Pro 等模型具有竞争力，并且能够进行非平凡的图像生成，所有这些都由单个模型完成。此外，根据一项新的长文本混合模态生成评估中的人工判断，Chameleon 的性能与或超过了许多更大的模型，包括 Gemini Pro 和 GPT-4V，在该评估中，提示或输出包含图像和文本的混合序列。Chameleon 标志着全多模态文档统一建模的重要进步*

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/chameleon_arch.png"
alt="drawing" width="600"/>

 Chameleon 整合了一个向量量化器模块，将图像转换为离散 token。这也使得使用自回归 transformer 进行图像生成成为可能。摘自原始论文。

该模型由 [joaogante](https://huggingface.co/joaogante) 和 [RaushanTurganbay](https://huggingface.co/RaushanTurganbay) 贡献。原始代码可在[此处](https://github.com/facebookresearch/chameleon)找到。

## 使用技巧

- 我们建议用户在计算批量生成时使用 `padding_side="left"`，因为这能带来更准确的结果。只需在生成之前设置 `processor.tokenizer.padding_side = "left"` 即可。

- 请注意，Chameleon 经过了安全对齐方面的调优。如果模型拒绝回答，建议提出更具体的问题，而不是开放式问题。

- Chameleon 以聊天格式生成文本，这意味着生成的文本始终是“助手的回合”。在调用处理器时传入 `return_for_text_completion=True`，即可启用文本补全生成。

> [!NOTE]
> Transformers 中的 Chameleon 实现使用一个特殊的图像标记来指示在哪里合并图像嵌入。对于该特殊图像标记，我们没有新增一个，而是使用了其中一个保留标记：`<reserved08707>`。为了正确生成，您必须在提示中图像应被嵌入的位置添加 `<image>`。

## 使用示例

### 单图像推理

Chameleon 是一个门控模型，因此请确保您拥有访问权限，并使用令牌登录 Hugging Face Hub。以下是加载模型并以半精度（`torch.bfloat16`）执行推理的方法：

```python
import requests
from PIL import Image

from transformers import ChameleonForConditionalGeneration, ChameleonProcessor

processor = ChameleonProcessor.from_pretrained("facebook/chameleon-7b")
model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", device_map="auto")

# prepare image and text prompt
url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)
prompt = "What do you see in this image?<image>"

inputs = processor(images=image, text=prompt, return_tensors="pt").to(model.device)

# autoregressively complete prompt
output = model.generate(**inputs, max_new_tokens=50)
print(processor.decode(output[0], skip_special_tokens=True))
```

### 多图像推理

Chameleon 支持以多张图像作为输入进行推理，这些图像可以属于同一个提示，也可以属于不同的提示（在批量推理中）。以下是具体操作方法：

```python
import requests
from PIL import Image

from transformers import ChameleonForConditionalGeneration, ChameleonProcessor

processor = ChameleonProcessor.from_pretrained("facebook/chameleon-7b")

model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", device_map="auto")

# Get three different images
url = "https://www.ilankelman.org/stopsigns/australia.jpg"
image_stop = Image.open(requests.get(url, stream=True).raw)

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image_cats = Image.open(requests.get(url, stream=True).raw)

url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
image_snowman = Image.open(requests.get(url, stream=True).raw)

# Prepare a batched prompt, where the first one is a multi-image prompt and the second is not
prompts = [
    "What do these images have in common?<image><image>",
    "<image>What is shown in this image?"
]

# We can simply feed images in the order they have to be used in the text prompt
# Each "<image>" token uses one image leaving the next for the subsequent "<image>" tokens
inputs = processor(images=[image_stop, image_cats, image_snowman], text=prompts, padding=True, return_tensors="pt").to(device=model.device)

# Generate
generate_ids = model.generate(**inputs, max_new_tokens=50)
processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
```

## 模型优化

### 使用 Bitsandbytes 进行量化

该模型可以以 8 位或 4 位精度加载，在保持原始模型性能的同时大幅降低内存需求。首先，请确保已安装 bitsandbytes，`pip install bitsandbytes`，并且拥有该库支持的 GPU/加速器。

bitsandbytes 正在重构以支持 CUDA 之外的多种后端。目前，ROCm（AMD GPU）和 Intel CPU 的实现已趋于成熟，Intel XPU 正在开发中，预计将在第四季度/第一季度支持 Apple Silicon。有关安装说明和最新的后端更新，请访问 [此链接](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend)。

我们非常重视您的反馈，以便在正式发布前发现并修复问题！请查阅[这些文档](https://huggingface.co/docs/bitsandbytes/main/en/non_cuda_backends)以获取更多详情和反馈链接。

只需将上述代码片段更改为：

```python
from transformers import BitsAndBytesConfig, ChameleonForConditionalGeneration

# specify how to quantize the model
quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
)

model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", quantization_config=quantization_config, device_map="auto")
```

### 使用 Flash-Attention 2 和 SDPA 进一步加速生成

该模型同时支持 Flash-Attention 2 和 PyTorch 的 [`torch.nn.functional.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html)，两者均可用于优化。加载模型时，SDPA 是默认选项。如果希望切换到 Flash Attention 2，请先确保已安装 flash-attn。有关该包的安装，请参阅[原始仓库](https://github.com/Dao-AILab/flash-attention)。只需将上述代码片段更改为：

```python
from transformers import ChameleonForConditionalGeneration

model_id = "facebook/chameleon-7b"
model = ChameleonForConditionalGeneration.from_pretrained(
    model_id,
    attn_implementation="flash_attention_2"
).to(0, device_map="auto")
```

## ChameleonConfig[[transformers.ChameleonConfig]]

#### transformers.ChameleonConfig[[transformers.ChameleonConfig]]

```python
transformers.ChameleonConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vocab_size: int = 65536, hidden_size: int = 4096, intermediate_size: int = 11008, num_hidden_layers: int = 32, num_attention_heads: int = 32, num_key_value_heads: int | None = 32, hidden_act: str = 'silu', max_position_embeddings: int = 4096, initializer_range: float = 0.02, rms_norm_eps: float = 1e-05, use_cache: bool = True, pad_token_id: int | None = None, bos_token_id: int | None = 1, eos_token_id: int | list[int] | None = 2, tie_word_embeddings: bool = False, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, attention_bias: bool | None = False, attention_dropout: float | int | None = 0.0, model_parallel_size: int | None = 1, swin_norm: bool | None = False, vq_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, vocabulary_map: dict | None = None, mlp_bias: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/configuration_chameleon.py#L66)

**参数：**

vocab_size (`int`，*可选*，默认为 `65536`)：模型的词汇表大小。定义了 `input_ids` 可以表示的不同 token 数量。

hidden_size (`int`，*可选*，默认为 `4096`)：隐藏表示的维度。

intermediate_size (`int`，*可选*，默认为 `11008`)：MLP 表示的维度。

num_hidden_layers (`int`，*可选*，默认为 `32`)：Transformer 解码器中的隐藏层数。

num_attention_heads (`int`，*可选*，默认为 `32`)：Transformer 解码器中每个注意力层的注意力头数量。

num_key_value_heads (`int`, *可选*，默认为 `32`) : 这是用于实现 Grouped Query Attention 的 key_value 头数量。如果 `num_key_value_heads=num_attention_heads`，模型将使用 Multi Head Attention (MHA)；如果 `num_key_value_heads=1`，模型将使用 Multi Query Attention (MQA)；否则将使用 GQA。在将多头检查点转换为 GQA 检查点时，每个组的 key 和 value 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 [这篇论文](https://huggingface.co/papers/2305.13245)。如果未指定，则默认为 `num_attention_heads`。

hidden_act (`str`，*可选*，默认为 `silu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

max_position_embeddings (`int`，*可选*，默认值为 `4096`)：该模型可能使用的最大序列长度。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

rms_norm_eps (`float`，*可选*，默认值为 `1e-05`)：rms 归一化层中使用的 epsilon。

use_cache (`bool`，*可选*，默认为 `True`)：模型是否应返回最后的键/值注意力（并非所有模型都使用）。仅当 `config.is_decoder=True` 或模型为仅解码器生成模型时相关。

pad_token_id (`int`, *可选*) : 词表中用于填充的 Token id。

bos_token_id (`int`，*可选*，默认为 `1`)：词汇表中用于表示流开始的 Token id。

eos_token_id (`Union[int, list[int]]`，*可选*，默认为 `2`)：词汇表中用于表示流结束（end-of-stream）的 token id。

tie_word_embeddings (`bool`，*可选*，默认为 `False`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *可选*) : 包含 RoPE 嵌入配置参数的字典。该字典应包含 `rope_theta` 的值，并且如果希望使用更长的 `max_position_embeddings` 配合 RoPE，则可选地包含用于缩放的参数。

attention_bias (`bool`，*可选*，默认为 `False`)：在自注意力机制中，是否在查询、键、值和输出投影层中使用偏置。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

model_parallel_size (`int`，*可选*，默认为 1)：训练模型时使用的分片数量。由于原始的 Chameleon 推理在这些层中不执行归约操作，且每个 rank 拥有各自的偏置，因此该参数将用于 qk layernorm。

swin_norm (`bool`，*可选*，默认为 `False`)：使用 Swin Transformer 归一化。

vq_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *可选*) : 向量量化模块的配置字典。

vocabulary_map (`dict`, *可选*) : 包含分词器词汇映射的字典。用于从图像输入中获取标记。

mlp_bias (`bool`，*可选*，默认为 `False`)：是否在 MLP 层的 up_proj、down_proj 和 gate_proj 层中使用偏置。

这是用于存储 ChameleonModel 配置的类。它根据指定的参数实例化 Chameleon 模型，并定义模型架构。使用默认值实例化配置将生成与 [facebook/chameleon-7b](https://huggingface.co/facebook/chameleon-7b) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

```python
>>> from transformers import ChameleonModel, ChameleonConfig

>>> # Initializing a chameleon chameleon-7b style configuration
>>> configuration = ChameleonConfig()

>>> # Initializing a model from the chameleon-7b style configuration
>>> model = ChameleonModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## ChameleonVQVAEConfig[[transformers.ChameleonVQVAEConfig]]

#### transformers.ChameleonVQVAEConfig[[transformers.ChameleonVQVAEConfig]]

```python
transformers.ChameleonVQVAEConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, embed_dim: int = 256, num_embeddings: int = 8192, double_latent: bool = False, latent_channels: int = 256, resolution: int = 512, in_channels: int = 3, base_channels: int = 128, channel_multiplier: list[int] | tuple[int, ...] = (1, 1, 2, 2, 4), num_res_blocks: int = 2, attn_resolutions: list[int] | None = None, dropout: float | int = 0.0, attn_type: str = 'vanilla')
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/configuration_chameleon.py#L28)

**参数：**

embed_dim (`int`，*可选*，默认为 `256`)：嵌入和隐藏状态的维度。

num_embeddings (`int`，*可选*，默认为 `8192`)：码本嵌入的数量。

double_latent (`bool`, *可选*, 默认为 `False`) : 是否使用双 z 通道。

latent_channels (`int`，*可选*，默认为 `256`)：潜在空间的通道数。

resolution (`int`，*可选*，默认值为 512)：输入图像的分辨率。

in_channels (`int`，*可选*，默认为 `3`)：输入通道数。

base_channels (`int`，*可选*，默认为 128)：基础通道数。

channel_multiplier (`list[int]`，*可选*，默认为 `[1, 1, 2, 2, 4]`)：每个分辨率的通道乘数。

num_res_blocks (`int`，*可选*，默认为 2)：残差块的数量。

attn_resolutions (`list[int]`, *可选*) : 应用注意力的分辨率。

dropout (`float`, *可选*, 默认值为 0.0) : Dropout 比率。

attn_type (`str`，*可选*，默认为 `"vanilla"`)：VQ-GAN 编码器中使用的注意力类型。可以是 "vanilla" 或 None

这是用于存储 ChameleonModel 配置的类。它根据指定的参数实例化 Chameleon 模型，并定义模型架构。使用默认值实例化配置将生成与 [facebook/chameleon-7b](https://huggingface.co/facebook/chameleon-7b) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

## ChameleonProcessor[[transformers.ChameleonProcessor]]

#### transformers.ChameleonProcessor[[transformers.ChameleonProcessor]]

```python
transformers.ChameleonProcessor(image_processor, tokenizer, image_seq_length: int = 1024, image_token: str = '<image>')
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/processing_chameleon.py#L57)

**参数：**

image_processor (`ChameleonImageProcessor`)：图像处理器是必需的输入。

tokenizer (`tokenizer_class`)：分词器是必需的输入。

image_seq_length (`int`，*可选*，默认为 1024)：单个图像嵌入的序列长度。

image_token (`str`，*可选*，默认为 `"<image>"`)：用于在文本中标识图像的特殊标记。

构建一个 ChameleonProcessor，它将图像处理器和分词器封装为单一处理器。

[ChameleonProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonProcessor) 提供了 [ChameleonImageProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonImageProcessor) 和 `tokenizer_class` 的所有功能。有关更多信息，请参阅 [~ChameleonImageProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonImageProcessor) 和 `~tokenizer_class`。

#### __调用__[[transformers.ChameleonProcessor.__call__]]

```python
__call__(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, text: str | list[str] | list[list[str]] | None = None, **kwargs: *<class 'transformers.models.chameleon.processing_chameleon.ChameleonProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/processing_chameleon.py#L84)

**参数：**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *可选*) : 要预处理的图像。期望输入单张图像或一批图像，其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

text (`Union[str, list[str], list[list[str]]]`，*可选*)：要编码的序列或序列批次。每个序列可以是字符串或字符串列表（预分词字符串）。如果传入预分词输入，请设置 `is_split_into_words=True` 以避免与批量输入产生歧义。

return_for_text_completion (`bool`, *kwargs*, *可选*，默认为 `False`) : 处理后的文本是否用于文本补全任务。当为 `True` 时，处理器不会在提示词末尾添加分隔符标记（`sep_token`），该标记通常用于聊天模式。当为 `False` 时，会添加分隔符标记以实现正确的聊天格式。

return_tensors (`str` 或 [TensorType](/docs/transformers/main/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/main/zh/main_classes/processors#transformers.ProcessingKwargs), *可选*) : 针对每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 TypedDict 类。

**返回：** [BatchFeature](/docs/transformers/main/zh/main_classes/feature_extractor#transformers.BatchFeature)

一个包含以下字段的 [BatchFeature](/docs/transformers/main/zh/main_classes/feature_extractor#transformers.BatchFeature)：

- **input_ids** -- 要输入模型的 token id 列表。当 `text` 不为 `None` 时返回。
- **attention_mask** -- 指定模型应关注哪些 token 的索引列表（当 `return_attention_mask=True` 时，或当 *"attention_mask"* 位于 `self.model_input_names` 中且 `text` 不为 `None` 时）。
- **pixel_values** -- 输入模型的像素值。当 `images` 不为 `None` 时返回。

## ChameleonImageProcessor[[transformers.ChameleonImageProcessor]]

#### transformers.ChameleonImageProcessor[[transformers.ChameleonImageProcessor]]

```python
transformers.ChameleonImageProcessor(**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/image_processing_chameleon.py#L26)

**参数：**

do_convert_rgb (`bool`，*kwargs*，*可选*，默认为 `True`)：是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'shortest_edge' : 512}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 size 为整数时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 512, 'width': 512}`)：应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认为 `1`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.0078`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行重新缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[1.0, 1.0, 1.0]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[1.0, 1.0, 1.0]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 用于将图像填充到的尺寸，格式为 `{"height": int, "width" int}`。该尺寸必须大于预处理中提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*，默认为 `True`) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

构造一个 ChameleonImageProcessor 图像处理器。

#### preprocess[[transformers.ChameleonImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], *args, image_like_kwargs: dict[str, typing.Any] | None = None, **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/image_processing_utils.py#L382)

**参数：**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 要预处理的图像。期望输入单张或一批像素值在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

image_like_kwargs (`dict[str, Any]`，*可选*)：用于额外图像类输入的开发者标志，这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如，`preprocess(images, masks=masks)` 是首选方式，但对于某些模型会导致参数优先级问题。在这种情况下，可以改用 `preprocess(images, image_like_inputs={"masks": masks})`。

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`，*kwargs*，*可选*)：是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*)：描述模型的最大输入维度。

default_to_square (`bool`, *kwargs*, *可选*) : 当 size 为 int 时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*) : 是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`, *kwargs*, *可选*) : 是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`，*kwargs*，*可选*)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 用于将图像填充到的尺寸，格式为 `{"height": int, "width" int}`。该尺寸必须大于预处理中提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

## ChameleonImageProcessorPil[[transformers.ChameleonImageProcessorPil]]

#### transformers.ChameleonImageProcessorPil[[transformers.ChameleonImageProcessorPil]]

```python
transformers.ChameleonImageProcessorPil(**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/image_processing_pil_chameleon.py#L23)

**参数：**

do_convert_rgb (`bool`，*kwargs*，*可选*，默认为 `True`)：是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'shortest_edge' : 512}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 size 为整数时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'height' : 512, 'width': 512}`)：应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认为 `1`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.0078`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行重新缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[1.0, 1.0, 1.0]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[1.0, 1.0, 1.0]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 用于将图像填充到的尺寸，格式为 `{"height": int, "width" int}`。该尺寸必须大于预处理中提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*，默认为 `True`) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

构造一个 ChameleonImageProcessor 图像处理器。

#### preprocess[[transformers.ChameleonImageProcessorPil.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], *args, image_like_kwargs: dict[str, typing.Any] | None = None, **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/image_processing_utils.py#L382)

**参数：**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`) : 要预处理的图像。期望输入单张或一批像素值在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间，请设置 `do_rescale=False`。

image_like_kwargs (`dict[str, Any]`，*可选*)：用于额外图像类输入的开发者标志，这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如，`preprocess(images, masks=masks)` 是首选方式，但对于某些模型会导致参数优先级问题。在这种情况下，可以改用 `preprocess(images, image_like_inputs={"masks": masks})`。

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`，*kwargs*，*可选*)：是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*)：描述模型的最大输入维度。

default_to_square (`bool`, *kwargs*, *可选*) : 当 size 为 int 时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*) : 是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`, *kwargs*, *可选*) : 是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`，*kwargs*，*可选*)：用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 用于将图像填充到的尺寸，格式为 `{"height": int, "width" int}`。该尺寸必须大于预处理中提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

## ChameleonVQVAE[[transformers.ChameleonVQVAE]]

#### transformers.ChameleonVQVAE[[transformers.ChameleonVQVAE]]

```python
transformers.ChameleonVQVAE(config: ChameleonVQVAEConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/modeling_chameleon.py#L786)

**参数：**

config ([ChameleonVQVAEConfig](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonVQVAEConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

Chameleon 中用于将图像编码/解码为离散 token 的 VQ-VAE 模型。该模型遵循 [Oran Gafni、Adam Polyak、Oron Ashual、Shelly Sheynin、Devi Parikh 和 Yaniv Taigman](https://huggingface.co/papers/2203.13131) 的论文 “Make-a-scene: Scene-based text-to-image generation with human priors”。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.ChameleonVQVAE.forward]]

```python
forward(*args, **kwargs)
```

点分路径（例如 `torch.float32`）的模拟值：属性访问链和调用行为如同透传装饰器，`repr` 为点分路径，将其用作基类时会替换为普通的 `type` 基类（PEP 560 `__mro_entries__`），因此真实的子类保留正常的元类，且 `inspect.signature` 读取的是它们真实的 `__init__`，而非模拟对象的。

## ChameleonModel[[transformers.ChameleonModel]]

#### transformers.ChameleonModel[[transformers.ChameleonModel]]

```python
transformers.ChameleonModel(config: ChameleonConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/modeling_chameleon.py#L825)

**参数：**

config ([ChameleonConfig](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

未添加任何特定头部的裸 Chameleon 模型，直接输出原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.ChameleonModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.modeling_flash_attention_utils.FlashAttentionKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/modeling_chameleon.py#L902)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [ChameleonImageProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonImageProcessor) 获取像素值。有关详细信息，请参阅 [ChameleonImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[ChameleonProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonProcessor) 使用 [ChameleonImageProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonImageProcessor) 处理图像）。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** [BaseModelOutputWithPast](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPast](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPast) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[ChameleonConfig](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonConfig)）和输入。

[ChameleonModel](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonModel) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。

  如果使用了 `past_key_values`，则仅输出形状为 `(batch_size, 1, hidden_size)` 的序列的最后一个隐藏状态。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值，以及如果 `config.is_encoder_decoder=True` 则还包括交叉注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

#### get_image_features[[transformers.ChameleonModel.get_image_features]]

```python
get_image_features(pixel_values: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/modeling_chameleon.py#L861)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[ChameleonConfig](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonConfig)）和输入。

使用 VQGAN 模块将图像离散化为 token，并通过文本嵌入层对其进行嵌入。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

## ChameleonForConditionalGeneration[[transformers.ChameleonForConditionalGeneration]]

#### transformers.ChameleonForConditionalGeneration[[transformers.ChameleonForConditionalGeneration]]

```python
transformers.ChameleonForConditionalGeneration(config: ChameleonConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/modeling_chameleon.py#L985)

**参数：**

config ([ChameleonConfig](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

Chameleon 模型，其顶部添加了一个用于输出下一 token 预测 logits 的头部。

该模型继承自 [PreTrainedModel](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.ChameleonForConditionalGeneration.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, pixel_values: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, past_key_values: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/modeling_chameleon.py#L1006)

**参数：**

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中 token 在词汇表中的索引。默认情况下，填充（padding）将被忽略。可以使用 [AutoTokenizer](/docs/transformers/main/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [PreTrainedTokenizer.encode()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) 和 [PreTrainedTokenizer.__call__()](/docs/transformers/main/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。[什么是输入 ID？](../glossary#input-ids)

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*)：与输入图像对应的张量。可以使用 [ChameleonImageProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonImageProcessor) 获取像素值。有关详细信息，请参阅 [ChameleonImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[ChameleonProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonProcessor) 使用 [ChameleonImageProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonImageProcessor) 处理图像）。

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

position_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 `[0, config.n_positions - 1]`。[什么是位置 ID？](../glossary#position-ids)

past_key_values (`~cache_utils.Cache`，*可选*)：预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 `past_key_values` 组成，前提是 `use_cache=True` 或 `config.use_cache=True`。 仅允许 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例作为输入，请参阅我们的 [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache)。如果未传入 `past_key_values`，则默认初始化 [DynamicCache](/docs/transformers/main/zh/internal/generation_utils#transformers.DynamicCache)。 模型将输出与输入相同的缓存格式。 如果使用 `past_key_values`，则用户预期仅输入未处理的 `input_ids`（即未向此模型提供其过去键值状态的那些），其形状为 `(batch_size, unprocessed_length)`，而不是形状为 `(batch_size, sequence_length)` 的所有 `input_ids`。

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是传入 `input_ids`。如果你希望比模型内部的嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为对应的向量，这将非常有用。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引值应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引值设为 `-100` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

use_cache (`bool`，*可选*)：如果设置为 `True`，则会返回 `past_key_values` 键值状态，可用于加速解码（参见 `past_key_values`）。

logits_to_keep (`Union[int, torch.Tensor]`，*可选*，默认为 `0`)：如果为 `int`，则计算最后 `logits_to_keep` 个 token 的 logits。如果为 `0`，则计算所有 `input_ids` 的 logits（特殊情况）。生成过程只需要最后一个 token 的 logits，仅针对该 token 进行计算可以节省内存，对于长序列或大词汇量而言，这种节省相当可观。如果为 `torch.Tensor`，则必须是一维张量，对应于序列长度维度中需要保留的索引。这在使用打包张量格式（将批次和序列长度合并为单一维度）时非常有用。

mm_encoder_outputs (`dict[str, ~modeling_outputs.BaseModelOutputWithPooling]`, *可选*) : 一个字典，其中键为支持的模态，值为该模态的编码输出。每个编码输出是一个元组，由 (`pooler_output`, *可选*: `last_hidden_states`, *可选*: `hidden_states`, *可选*: `attentions`) 组成，其中 `pooler_output` 的形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)，表示编码器生成的多模态特征序列，并已融合到文本嵌入中。

**返回：** [CausalLMOutputWithPast](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) 或 `tuple(torch.Tensor)`

一个 [CausalLMOutputWithPast](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.CausalLMOutputWithPast) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[ChameleonConfig](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonConfig)）和输入。

[ChameleonForConditionalGeneration](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonForConditionalGeneration) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 语言建模损失（用于下一个 token 预测）。
- **logits**（形状为 `(batch_size, sequence_length, config.vocab_size)` 的 `torch.Tensor`）-- 语言建模头的预测分数（SoftMax 之前每个词汇表 token 的分数）。
- **past_key_values**（`Cache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回）—— 它是一个 [Cache](/docs/transformers/main/zh/internal/generation_utils#transformers.Cache) 实例。更多详情，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块中的键和值），可用于（参见 `past_key_values` 输入）加速顺序解码。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from transformers import ChameleonProcessor, ChameleonForConditionalGeneration
>>> import torch
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image

>>> model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b", dtype=torch.bfloat16)
>>> processor = ChameleonProcessor.from_pretrained("facebook/chameleon-7b")

>>> prompt = "I used to know a lot about constellations when I was younger, but as I grew older, I forgot most of what I knew. These are the only two constellations that I really remember now.<image><image>I would like for you to tell me about 3 more constellations and give me a little bit of history about the constellation."
>>> url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/big_dipper.jpg"
>>> with httpx.stream("GET", url) as response:
...     image1 = Image.open(BytesIO(response.read()))

>>> url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/orion.jpg"
>>> with httpx.stream("GET", url) as response:
...     image2 = Image.open(BytesIO(response.read()))

>>> inputs = processor(images=[image1, image2], text=prompt, return_tensors="pt").to(model.device, torch.bfloat16)

>>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
>>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
```

#### get_image_features[[transformers.ChameleonForConditionalGeneration.get_image_features]]

```python
get_image_features(pixel_values: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/chameleon/modeling_chameleon.py#L1000)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [ChameleonImageProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonImageProcessor) 获取像素值。有关详细信息，请参阅 [ChameleonImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[ChameleonProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonProcessor) 使用 [ChameleonImageProcessor](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonImageProcessor) 处理图像）。

**返回：** [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutputWithPooling](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[ChameleonConfig](/docs/transformers/main/zh/model_doc/chameleon#transformers.ChameleonConfig)）和输入。

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **pooler_output**（形状为 `(batch_size, hidden_size)` 的 `torch.Tensor`）-- 序列中第一个 token（分类 token）的最后一层隐藏状态，经过用于辅助预训练任务的层进一步处理后的结果。例如，对于 BERT 系列模型，这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重是在预训练期间通过下一句预测（分类）目标训练得到的。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from PIL import Image
>>> from transformers import AutoProcessor, ChameleonForConditionalGeneration

>>> model = ChameleonForConditionalGeneration.from_pretrained("facebook/chameleon-7b")
>>> processor = AutoProcessor.from_pretrained("facebook/chameleon-7b")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
```

