Transformers 文档

Janus

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Janus

概述

Janus 模型最初由 DeepSeek AI 团队在 Janus: Decoupling Visual Encoding for Unified Multimodal Understanding and Generation 中提出,后在 Janus-Pro: Unified Multimodal Understanding and Generation with Data and Model Scaling 中进行了改进。Janus 是一种视觉-语言模型,可以生成图像和文本输出,也可以将图像和文本作为输入。

[!NOTE] 该模型不会以交错格式同时生成图像和文本。用户必须传递一个参数来指示是生成文本还是图像。

原始论文的摘要如下:

在本文中,我们介绍了 Janus,一个统一多模态理解和生成的自回归框架。之前的研究通常依赖于一个单一的视觉编码器来完成这两项任务,例如 Chameleon。然而,由于多模态理解和生成所需的细粒度信息水平不同,这种方法可能会导致次优性能,尤其是在多模态理解方面。为了解决这个问题,我们将视觉编码解耦为单独的路径,同时仍然利用单一的统一 Transformer 架构进行处理。这种解耦不仅缓解了视觉编码器在理解和生成中的角色冲突,而且增强了框架的灵活性。例如,多模态理解和生成组件都可以独立选择最适合它们的编码方法。实验表明,Janus 超越了之前的统一模型,并达到或超过了特定任务模型的性能。Janus 的简单性、高灵活性和有效性使其成为下一代统一多模态模型的有力候选。

上述 Janus-Pro 论文的摘要(发布于之后)如下:

在这项工作中,我们介绍了 Janus-Pro,它是先前工作 Janus 的高级版本。具体来说,Janus-Pro 整合了 (1) 优化的训练策略,(2) 扩展的训练数据,以及 (3) 扩展到更大的模型尺寸。通过这些改进,Janus-Pro 在多模态理解和文本到图像指令遵循能力方面取得了显著进展,同时还增强了文本到图像生成的稳定性。我们希望这项工作能启发该领域的进一步探索。代码和模型已公开提供。

此模型由 Yaswanth GaliHugo Silva 贡献。原始代码可在此处找到。

使用示例

单图像推理

以下是使用单图像进行视觉理解的示例。

[!NOTE] 请注意,该模型已针对特定的聊天提示格式进行训练。请使用 processor.apply_chat_template(my_conversation_dict) 来正确格式化您的提示。

import torch  
from PIL import Image  
import requests  

from transformers import JanusForConditionalGeneration, JanusProcessor  

model_id = "deepseek-community/Janus-Pro-1B"
# Prepare Input for generation.
messages = [
    {
        "role": "user",
        "content": [
            {'type':'image', 'url': 'http://images.cocodataset.org/val2017/000000039769.jpg'},
            {'type':"text", "text":"What do you see in this image?."}
        ]
    },
]

# Set generation mode to `text` to perform text generation.
processor = JanusProcessor.from_pretrained(model_id)
model = JanusForConditionalGeneration.from_pretrained(model_id,     
        torch_dtype=torch.bfloat16,
        device_map="auto")

inputs = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    generation_mode="text",
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
).to(model.device, dtype=torch.bfloat16)

output = model.generate(**inputs, max_new_tokens=40,generation_mode='text',do_sample=True)
text = processor.decode(output[0], skip_special_tokens=True)
print(text)

多图像推理

Janus 可以对多个图像作为输入进行推理,其中图像可以属于相同的提示,也可以属于批处理推理中不同的提示,模型同时处理多个对话。以下是操作方法:

import torch
from PIL import Image
import requests

from transformers import JanusForConditionalGeneration, JanusProcessor

model_id = "deepseek-community/Janus-Pro-1B"

image_urls = [
    "http://images.cocodataset.org/val2017/000000039769.jpg",
    "https://www.ilankelman.org/stopsigns/australia.jpg",
    "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
]

messages = [
    [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What’s the difference between"},
                {"type": "image", "url": image_urls[0]},
                {"type": "text", "text": " and "},
                {"type": "image", "url": image_urls[1]}
            ]
        }
    ],
    [
        {
            "role": "user",
            "content": [
                {"type": "image", "url": image_urls[2]},
                {"type": "text", "text": "What do you see in this image?"}
            ]
        }
    ]
]

# Load model and processor
processor = JanusProcessor.from_pretrained(model_id)
model = JanusForConditionalGeneration.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto"
)

inputs = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    generation_mode="text",
    tokenize=True,
    padding=True,
    return_dict=True,
    return_tensors="pt"
).to(model.device, dtype=torch.bfloat16)

# Generate response
output = model.generate(**inputs, max_new_tokens=40, generation_mode='text', do_sample=False)
text = processor.batch_decode(output, skip_special_tokens=True)
print(text)

文本到图像生成

Janus 也可以根据提示生成图像。

import torch
from transformers import JanusForConditionalGeneration, JanusProcessor

# Set generation mode to `image` to prepare inputs for image generation..

model_id = "deepseek-community/Janus-Pro-1B"
processor = JanusProcessor.from_pretrained(model_id)
model = JanusForConditionalGeneration.from_pretrained(model_id,
        torch_dtype=torch.bfloat16,
        device_map="auto")

messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "A dog running under the rain."},
        ],
     }
]

prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(text=prompt,generation_mode="image",return_tensors="pt").to(model.device, dtype=torch.bfloat16)

# Set num_return_sequence parameter to generate multiple images per prompt.
model.generation_config.num_return_sequences = 2
outputs = model.generate(**inputs,
                         generation_mode="image",
                         do_sample=True,
                         use_cache=True,
                         )
# Perform post-processing on the generated token ids.
decoded_image = model.decode_image_tokens(outputs)
images = processor.postprocess(list(decoded_image.float()),return_tensors="PIL.Image.Image")
# Save the image
for i, image in enumerate(images['pixel_values']):
    image.save(f"result{i}.png")

JanusConfig

class transformers.JanusConfig

< >

( text_config = None vision_config = None vq_config = None image_token_id = 100581 **kwargs )

参数

  • text_config (Union[AutoConfig, dict], 可选, 默认为 LlamaConfig) — 文本骨干的配置对象或字典。
  • vision_config (Union[AutoConfig, dict], 可选, 默认为 JanusVisionConfig) — 视觉骨干的配置对象或字典。
  • vq_config (Union[AutoConfig, dict], 可选, 默认为 JanusVQVAEConfig) — VQVAE 骨干的配置对象或字典。
  • image_token_id (int, 可选, 默认为 100581) — 占位图像 token 的 token 索引。

这是一个配置类,用于存储 JanusModel 的配置。它用于根据指定的参数实例化 Janus 模型,定义模型架构。使用默认值实例化配置将生成与 Janus-1B 或 Janus-7B 模型相似的配置。

例如 deepseek-community/Janus-Pro-1Bdeepseek-community/Janus-Pro-7B

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PretrainedConfig 的文档。

示例

>>> from transformers import JanusForConditionalGeneration, JanusConfig, JanusVisionConfig, JanusVQVAEConfig, LlamaConfig

>>> # Initializing a Janus vision config
>>> vision_config = JanusVisionConfig()

>>> # Initializing a Llama config
>>> text_config = LlamaConfig()

>>> # Initializing a VQ config
>>> vq_config = JanusVQVAEConfig()

>>> # Initializing a Janus Pro 1B style configuration
>>> configuration = JanusConfig(vision_config=vision_config, text_config=text_config, vq_config=vq_config)

>>> # Initializing a model from the Janus Pro 1B style configuration
>>> model = JanusForConditionalGeneration(configuration)

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

JanusVisionConfig

class transformers.JanusVisionConfig

< >

( hidden_size = 1024 num_hidden_layers = 24 num_attention_heads = 16 num_channels = 3 patch_size = 16 image_size = 384 attention_dropout = 0.0 layer_norm_eps = 1e-06 hidden_act = 'gelu' mlp_ratio = 4.0 attention_bias = True hidden_dropout_rate = 0.0 projection_dim = 2048 projection_dropout = 0.0 use_qk_norm = False initializer_range = 0.02 depth = 2 num_image_tokens = 576 **kwargs )

参数

  • hidden_size (int, 可选, 默认为 1024) — 编码器层和池化层的维度。
  • num_hidden_layers (int, 可选, 默认为 24) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, 可选, 默认为 16) — Transformer 编码器中每个注意力层的注意力头数量。
  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • patch_size (int, 可选, 默认为 16) — 每个 patch 的大小(分辨率)。
  • image_size (int, 可选, 默认为 384) — 每张图像的大小(分辨率)。
  • attention_dropout (float, 可选, 默认为 0.0) — 注意力权重的 Dropout 概率。
  • layer_norm_eps (float, 可选, 默认为 1e-06) — 层归一化层使用的 epsilon。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,支持 "gelu""relu""selu""gelu_new"
  • mlp_ratio (float, 可选, 默认为 4.0) — MLP 隐藏维度与嵌入维度的比率。
  • attention_bias (bool, 可选, 默认为 True) — 是否在注意力层中为查询、键和值添加偏差。
  • hidden_dropout_rate (float, 可选, 默认为 0.0) — 编码器中全连接层的 Dropout 概率。
  • projection_dim (int, 可选, 默认为 2048) — MLP 投影头的维度。
  • projection_dropout (float, 可选, 默认为 0.0) — 投影层的 Dropout 概率。
  • use_qk_norm (bool, 可选, 默认为 False) — 是否归一化查询和键矩阵。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • depth (int, 可选, 默认为 2) — 对齐器模块中的隐藏层数量。
  • num_image_tokens (int, 可选, 默认为 576) — 图像 token 的数量。

这是一个配置类,用于存储 JanusVisionModel 的配置。它用于根据指定的参数实例化 JanusVisionModel,定义模型架构。

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PretrainedConfig 的文档。

JanusVQVAEConfig

class transformers.JanusVQVAEConfig

< >

( embed_dim: int = 8 num_embeddings: int = 16384 double_latent: bool = False latent_channels: int = 256 num_patches: int = 32 in_channels: int = 3 out_channels: int = 3 base_channels: int = 128 channel_multiplier: list = [1, 1, 2, 2, 4] num_res_blocks: int = 2 dropout: float = 0.0 initializer_range = 0.02 projection_dim = 2048 num_hidden_layers = 2 hidden_act = 'gelu' image_token_embed_dim = 2048 **kwargs )

参数

  • embed_dim (int, 可选, 默认为 8) — 每个嵌入向量的维度。
  • num_embeddings (int, 可选, 默认为 16384) — 码本嵌入的数量。
  • double_latent (bool, 可选, 默认为 False) — 是否使用双 z 通道。
  • latent_channels (int, 可选, 默认为 256) — 潜在空间的通道数量。
  • num_patches (int, 可选, 默认为 32) — 输入图像可分割成的 patch 数量。
  • in_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • out_channels (int, 可选, 默认为 3) — 输出通道的数量。
  • base_channels (int, 可选, 默认为 128) — 基本通道数。
  • channel_multiplier (list[int], 可选, 默认为 [1, 1, 2, 2, 4]) — 每个分辨率的通道乘数。
  • num_res_blocks (int, 可选, 默认为 2) — 残差块的数量。
  • dropout (float, 可选, 默认为 0.0) — Dropout 率。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • projection_dim (int, 可选, 默认为 2048) — MLP 投影头的维度。
  • num_hidden_layers (int, 可选, 默认为 2) — VAVAE MLP 连接器模块中的隐藏层数量。
  • hidden_act (strCallable, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,支持 "gelu""relu""silu""gelu_new"
  • image_token_embed_dim (int, 可选, 默认为 2048) — 图像嵌入的维度。应与文本嵌入的维度相同。

这是用于存储 JanusVQVAEModel 配置的配置类。它用于根据指定的参数实例化 JanusVQVAEModel,定义模型架构。配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PretrainedConfig 的文档。使用默认值实例化配置将产生与 deepseek-community/Janus-Pro-1B 的 VQModel 相似的配置。

JanusProcessor

class transformers.JanusProcessor

< 来源 >

( image_processor tokenizer chat_template = None use_default_system_prompt = False **kwargs )

参数

  • image_processor (JanusImageProcessor) — 图像处理器是必需的输入。
  • tokenizer (LlamaTokenizerFast) — 分词器是必需的输入。
  • chat_template (str, 可选) — 用于将聊天中的消息列表转换为可标记化字符串的 Jinja 模板。
  • use_default_system_prompt (str, 可选, 默认为 False) — 对文本生成使用默认系统提示。

构建一个 Janus 处理器,它将 Janus 图像处理器和 Llama 分词器封装成一个单一的处理器。

JanusProcessor 提供了 JanusImageProcessorLlamaTokenizerFast 的所有功能。有关更多信息,请参阅 __call__()decode()

batch_decode

< 来源 >

( *args **kwargs )

此方法将其所有参数转发给 LlamaTokenizerFast 的 batch_decode()。有关更多信息,请参阅此方法的文档字符串。

decode

< 来源 >

( *args **kwargs )

此方法将其所有参数转发给 LlamaTokenizerFast 的 decode()。有关更多信息,请参阅此方法的文档字符串。

postprocess

< 来源 >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs )

将所有参数转发给图像处理器的 postprocess 方法。有关更多详细信息,请参阅原始方法的文档字符串。

JanusImageProcessor

class transformers.JanusImageProcessor

< 来源 >

( do_resize: bool = True size: typing.Optional[dict[str, int]] = None min_size: int = 14 resample: Resampling = <Resampling.BICUBIC: 3> do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_rgb: typing.Optional[bool] = None **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的 (height, width) 尺寸调整为指定的 size。可以通过 preprocess 方法中的 do_resize 参数覆盖。
  • size (dict, 可选, 默认为 {"height" -- 384, "width": 384}):调整大小后输出图像的尺寸。可以通过 preprocess 方法中的 size 参数覆盖。
  • min_size (int, 可选, 默认为 14) — 调整大小后图像的最小允许尺寸。确保调整大小后高度和宽度都不低于此值。
  • resample (PILImageResampling, 可选, 默认为 Resampling.BICUBIC) — 如果调整图像大小,要使用的重采样过滤器。仅当 do_resize 设置为 True 时有效。可以通过 preprocess 方法中的 resample 参数覆盖。
  • do_rescale (bool, 可选, 默认为 True) — 是否按指定的比例 rescale_factor 缩放图像。可以通过 preprocess 方法中的 do_rescale 参数覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果缩放图像,要使用的比例因子。仅当 do_rescale 设置为 True 时有效。可以通过 preprocess 方法中的 rescale_factor 参数覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 是否对图像进行归一化。可以通过 preprocess 方法中的 do_normalize 参数覆盖。可以通过 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 如果对图像进行归一化,要使用的均值。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过 preprocess 方法中的 image_mean 参数覆盖。可以通过 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 如果对图像进行归一化,要使用的标准差。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过 preprocess 方法中的 image_std 参数覆盖。可以通过 preprocess 方法中的 image_std 参数覆盖。
  • do_convert_rgb (bool, 可选, 默认为 True) — 是否将图像转换为 RGB。

构建一个 JANUS 图像处理器。

pad_to_square

< 来源 >

( image: ndarray background_color: typing.Union[int, tuple[int, int, int]] = 0 data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None ) np.ndarray

参数

  • image (np.ndarray) — 要填充的图像。
  • background_color (inttuple[int, int, int], 可选, 默认为 0) — 用于填充的颜色。可以是单通道的整数,也可以是表示多通道图像的整数元组。如果在多通道模式下作为整数传入,则在后续通道中默认为 0
  • data_format (strChannelDimension, 可选) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像为 (num_channels, height, width) 格式。
    • "channels_last"ChannelDimension.LAST:图像为 (height, width, num_channels) 格式。如果未设置,将使用与输入图像相同的格式。
  • input_data_format (strChannelDimension, 可选) — 输入图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像为 (num_channels, height, width) 格式。
    • "channels_last"ChannelDimension.LAST:图像为 (height, width, num_channels) 格式。

返回

np.ndarray

填充后的图像。

将图像填充为以最长边为基准的正方形。

postprocess

< 来源 >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Optional[list[float]] = None image_std: typing.Optional[list[float]] = None input_data_format: typing.Optional[str] = None return_tensors: typing.Optional[str] = None )

通过反转预处理期间应用的转换,对解码的图像标记进行后处理。

preprocess

< 来源 >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None do_convert_rgb: typing.Optional[bool] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • images (ImageInput) — 要预处理的图像。期望单个或批量图像,像素值范围从 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], 可选, 默认为 self.size) — 控制 resize 后图像的大小。图像的最短边将调整为 size["shortest_edge"],同时保持纵横比。如果此调整大小后的图像的最长边大于 int(size["shortest_edge"] * (1333 / 800)),则图像将再次调整大小,使最长边等于 int(size["shortest_edge"] * (1333 / 800))
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 如果调整图像大小,要使用的重采样过滤器。仅当 do_resize 设置为 True 时有效。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 do_rescale 设置为 True,则用于缩放图像的比例因子。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化。
  • image_mean (floatlist[float], 可选, 默认为 self.image_mean) — 如果 do_normalize 设置为 True,则用于归一化图像的均值。
  • image_std (floatlist[float], 可选, 默认为 self.image_std) — 如果 do_normalize 设置为 True,则用于归一化图像的标准差。
  • do_convert_rgb (bool, 可选, 默认为 self.do_convert_rgb) — 是否将图像转换为 RGB。
  • return_tensors (strTensorType, 可选) — 要返回的张量类型。可以是以下之一:
    • 未设置:返回 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回 tf.Tensor 类型的批量。
    • TensorType.PYTORCH'pt':返回 torch.Tensor 类型的批量。
    • TensorType.NUMPY'np':返回 np.ndarray 类型的批量。
    • TensorType.JAX'jax':返回 jax.numpy.ndarray 类型的批量。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • 未设置: 使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

预处理一张或一批图像。

resize

< >

( image: ndarray size: typing.Union[dict[str, int], int] resample: Resampling = <Resampling.BICUBIC: 3> data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs ) np.ndarray

参数

  • image (np.ndarray) — 要调整大小的图像。
  • resample (PILImageResampling, 可选, 默认为 PILImageResampling.BICUBIC) — 调整图像大小时使用的 PILImageResampling 滤波器,例如 PILImageResampling.BICUBIC
  • data_format (ChannelDimensionstr, 可选) — 输出图像的通道维度格式。如果未设置,将使用输入图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • None: 将从输入中推断。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

返回

np.ndarray

调整大小后的图像。

将图像调整为动态计算的大小。

unnormalize

< >

( image: <built-in function array> image_mean: typing.Union[float, collections.abc.Iterable[float]] image_std: typing.Union[float, collections.abc.Iterable[float]] input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • image (形状为 (batch_size, num_channels, image_size, image_size)(num_channels, image_size, image_size)torch.Tensor) — 要后处理的像素值批次。
  • image_mean (floatIterable[float]) — 用于反归一化的均值。
  • image_std (floatIterable[float]) — 用于反归一化的标准差。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

使用 meanstd 指定的均值和标准差对 image 进行反归一化。image = (image * image_std) + image_mean

JanusVisionModel

class transformers.JanusVisionModel

< >

( config: JanusVisionConfig )

参数

  • config (JanusVisionConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化模型不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。

裸 Janus 模型,输出原始隐藏状态,顶部没有任何特定头部。

此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的一般方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档中与一般用法和行为相关的所有事项。

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None interpolate_pos_encoding: bool = False ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor, 可选) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是纯元组。
  • interpolate_pos_encoding (bool, 默认为 False) — 是否插值预训练位置编码。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutputWithPoolingtorch.FloatTensor 的元组(如果传递了 return_dict=Falseconfig.return_dict=False),包含根据配置(JanusConfig)和输入而变化的各种元素。

  • last_hidden_state (torch.FloatTensor, 形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。

  • pooler_output (形状为 (batch_size, hidden_size)torch.FloatTensor) — 序列第一个 token(分类 token)的最后一层隐藏状态,经过辅助预训练任务所用层的进一步处理。例如,对于 BERT 家族模型,这会返回分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层权重在预训练期间通过下一句预测(分类)目标进行训练。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层输出,如果模型有嵌入层,+ 每个层的输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传入 output_attentions=Trueconfig.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

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

JanusVisionModel 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然前向传播的配方需要在此函数中定义,但之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默忽略它们。

JanusVQVAE

class transformers.JanusVQVAE

< >

( config: JanusVQVAEConfig )

参数

  • config (JanusVQVAEConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化模型不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。

Janus 中用于将图像编码/解码为离散 token 的 VQ-VAE 模型。此模型遵循 Oran Gafni, Adam Polyak, Oron Ashual, Shelly Sheynin, Devi Parikh, and Yaniv Taigman 的“Make-a-scene: Scene-based text-to-image generation with human priors”论文。

此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的一般方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档中与一般用法和行为相关的所有事项。

forward

< >

( pixel_values: FloatTensor )

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。

JanusVQVAE 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然前向传播的配方需要在此函数中定义,但之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默忽略它们。

JanusModel

class transformers.JanusModel

< >

( config: JanusConfig )

参数

  • config (JanusConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化模型不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。

Janus 模型,由 siglip 视觉骨干、Llama 语言模型和 VQ 模型组成。

此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的一般方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档中与一般用法和行为相关的所有事项。

forward

< >

( input_ids: LongTensor = None pixel_values: FloatTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[transformers.cache_utils.Cache] = None cache_position: typing.Optional[torch.LongTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 **kwargs )

参数

  • input_ids (形状为 (batch_size, sequence_length)torch.LongTensor) — 词汇表中输入序列 token 的索引。默认情况下将忽略填充。

    索引可以使用 AutoTokenizer 获取。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是 input ID?

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • attention_mask (形状为 (batch_size, sequence_length)torch.Tensor, 可选) — 掩码,用于避免对填充 token 索引执行注意力。掩码值选择范围为 [0, 1]:

    • 1 表示 未被掩码 的 token,
    • 0 表示 被掩码 的 token。

    什么是注意力掩码?

  • position_ids (形状为 (batch_size, sequence_length)torch.LongTensor, 可选) — 每个输入序列 token 在位置嵌入中的位置索引。选择范围为 [0, config.n_positions - 1]

    什么是位置 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常包括模型在解码上一阶段返回的 past_key_values,当 use_cache=Trueconfig.use_cache=True 时。

    允许两种格式:

    • 一个 Cache 实例,请参阅我们的 kv 缓存指南
    • 长度为 config.n_layerstuple(torch.FloatTensor) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量)。这也被称为旧版缓存格式。

    模型将输出与作为输入馈送的缓存格式相同的缓存格式。如果没有传入 past_key_values,将返回旧版缓存格式。

    如果使用 past_key_values,用户可以选择只输入形状为 (batch_size, 1) 的最后一个 input_ids(那些没有将其过去的键值状态提供给此模型的)而不是形状为 (batch_size, sequence_length) 的所有 input_ids

  • cache_position (形状为 (sequence_length)torch.LongTensor, 可选) — 序列中输入序列 token 位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。
  • inputs_embeds (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对 input_ids 索引如何转换为相关向量有比模型内部嵌入查找矩阵更多的控制,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 True,将返回 past_key_values 键值状态,并可用于加速解码(请参阅 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 hidden_states
  • logits_to_keep (Union[int, torch.Tensor], 默认为 0) — 如果是 int,则计算最后 logits_to_keep 个 token 的 logits。如果是 0,则计算所有 input_ids 的 logits(特殊情况)。生成时只需要最后一个 token 的 logits,只计算该 token 可以节省内存,这对于长序列或大词汇量来说非常重要。如果是 torch.Tensor,则必须是 1D,对应于序列长度维度中要保留的索引。这在使用打包张量格式(批处理和序列长度的单维度)时非常有用。

JanusModel 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然前向传播的配方需要在此函数中定义,但之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默忽略它们。

JanusForConditionalGeneration

class transformers.JanusForConditionalGeneration

< >

( config: JanusConfig )

forward

< >

( input_ids: LongTensor = None pixel_values: FloatTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[transformers.cache_utils.Cache] = None cache_position: typing.Optional[torch.LongTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 **kwargs )

参数

  • input_ids (形状为 (batch_size, sequence_length)torch.LongTensor) — 词汇表中输入序列 token 的索引。默认情况下将忽略填充。

    索引可以使用 AutoTokenizer 获取。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是 input ID?

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • attention_mask (形状为 (batch_size, sequence_length)torch.Tensor, 可选) — 掩码,用于避免对填充 token 索引执行注意力。掩码值选择范围为 [0, 1]:

    • 1 表示 未被掩码 的 token,
    • 0 表示 被掩码 的 token。

    什么是注意力掩码?

  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 输入序列中每个标记在位置嵌入中的索引。选择范围为 [0, config.n_positions - 1]

    什么是位置ID?

  • past_key_values (~cache_utils.Cache可选) — 预先计算好的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速序列解码。这通常包括模型在解码前期返回的 past_key_values,当 use_cache=Trueconfig.use_cache=True 时。

    允许两种格式:

    • 一个 Cache 实例,参见我们的 kv 缓存指南
    • tuple(torch.FloatTensor) 的元组,长度为 config.n_layers,每个元组包含两个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量)。这也称为旧版缓存格式。

    模型将输出与输入相同的缓存格式。如果没有传入 past_key_values,则返回旧版缓存格式。

    如果使用了 past_key_values,用户可以选择性地只输入形状为 (batch_size, 1) 的最后一个 input_ids(那些没有将其过去键值状态提供给此模型的)而不是形状为 (batch_size, sequence_length) 的所有 input_ids

  • cache_position (torch.LongTensor,形状为 (sequence_length)可选) — 表示输入序列标记在序列中位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。
  • inputs_embeds (torch.FloatTensor,形状为 (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 的标记将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size] 中的标记计算。
  • use_cache (bool可选) — 如果设置为 True,则返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。更多详细信息请参见返回张量下的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。更多详细信息请参见返回张量下的 hidden_states
  • logits_to_keep (Union[int, torch.Tensor],默认为 0) — 如果是 int 类型,则计算最后 logits_to_keep 个标记的 logits。如果是 0,则计算所有 input_ids 的 logits(特殊情况)。生成时只需要最后一个标记的 logits,只计算该标记的 logits 可以节省内存,这对于长序列或大词汇量来说非常显著。如果是 torch.Tensor 类型,则必须是与序列长度维度中要保留的索引相对应的一维张量。这在使用打包张量格式(批次和序列长度的单个维度)时很有用。

JanusForConditionalGenerationforward 方法,重写了 __call__ 特殊方法。

虽然前向传播的配方需要在此函数中定义,但之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默忽略它们。

示例

>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, JanusForConditionalGeneration

>>> model = JanusForConditionalGeneration.from_pretrained("deepseek-community/Janus-Pro-1B")
>>> processor = AutoProcessor.from_pretrained("deepseek-community/Janus-Pro-1B")

>>> 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]
< > 在 GitHub 上更新