MLMs之Janus:Janus/Janus-Pro的简介、安装和使用方法、案例应用
MLMs之Janus:Janus/Janus-Pro的简介、安装和使用方法、案例应用
目录
相关文章
MLMs之Janus:《Janus-Pro: Unified Multimodal Understanding and Generation with Data and Model Scaling》翻译与解读
MLMs之Janus:Janus/Janus-Pro的简介、安装和使用方法、案例应用
Janus的简介
0、更新日志
1、Janus-Pro简介
2、JanusFlow简介
Janus的安装和使用方法
1、安装
模型下载
安装依赖
2、Janus-Pro的使用方法
多模态理解
文本到图像生成
Gradio 演示
T1、基于Huggingface部署的在线演示
测试图文理解:
测试文本生成:好像没能理解文本描述
T2、本地 gradio 演示
3、Janus的使用方法
多模态理解
文本到图像生成
Gradio 演示
T1、基于Huggingface部署的在线演示
T2、本地 gradio 演示
FastAPI 演示
4、JanusFlow的使用方法
Janus的案例应用
相关文章
MLMs之Janus:《Janus-Pro: Unified Multimodal Understanding and Generation with Data and Model Scaling》翻译与解读
MLMs之Janus:《Janus-Pro: Unified Multimodal Understanding and Generation with Data and Model Scaling》翻-CSDN博客
MLMs之Janus:Janus/Janus-Pro的简介、安装和使用方法、案例应用
https://yunyaniu.blog.csdn.net/article/details/145385376
Janus的简介
Janus是一个新颖的自回归框架,它统一了多模态理解和生成。它通过将视觉编码解耦成独立的路径来解决先前方法的局限性,同时仍然使用单个统一的Transformer架构进行处理。这种解耦不仅减轻了视觉编码器在理解和生成中的角色冲突,而且增强了框架的灵活性。Janus超越了之前的统一模型,并且在性能上与特定任务的模型相匹配甚至超过它们。Janus的简洁性、高灵活性以及有效性使其成为下一代统一多模态模型的有力竞争者。
GitHub地址:GitHub - deepseek-ai/Janus: Janus-Series: Unified Multimodal Understanding and Generation Models
0、更新日志
2025 年 1 月 27 日:Janus-Pro 发布,这是 Janus 的高级版本,在多模态理解和视觉生成方面均有显著提升。
2024 年 11 月 13 日:JanusFlow 发布,这是一种用于图像生成的具有修正流的新统一模型。
2024 年 10 月 23 日:用于重现论文中多模态理解结果的评估代码已添加到 VLMEvalKit 中。
2024 年 10 月 20 日:(1)修复了 tokenizer_config.json 中的一个错误。之前的版本导致无分类器引导功能无法正常工作,从而导致视觉生成质量相对较差。(2)发布 Gradio 演示(在线演示和本地演示)。
1、Janus-Pro简介
Janus-Pro是Janus的改进版本。它通过以下改进实现了多模态理解和图像生成的显著提升:
>> 优化的训练策略:采用了更有效的训练方法。
>> 扩展的训练数据:使用了更多的数据进行训练。
>> 更大的模型规模:模型参数量更大。
这些改进使得Janus-Pro在多模态理解和文本到图像指令遵循能力方面取得了显著进展,同时还增强了文本到图像生成的稳定性。
2、JanusFlow简介
JanusFlow 结合了自回归语言模型和校正流(rectified flow),这是一种最先进的生成模型方法。其核心发现是,校正流可以直接在大型语言模型框架内进行训练,无需复杂的架构修改。大量的实验表明,JanusFlow 在各自领域中达到了与专用模型相当或更好的性能,同时在标准基准测试中显著优于现有的统一方法。这项工作代表着朝着更高效、更通用的视觉语言模型迈进的一步。
Janus的安装和使用方法
1、安装
模型下载
Janus系列模型可以在Hugging Face上下载
Model | Sequence Length | Download |
---|---|---|
Janus-1.3B | 4096 | 🤗 Hugging Face |
JanusFlow-1.3B | 4096 | 🤗 Hugging Face |
Janus-Pro-1B | 4096 | 🤗 Hugging Face |
Janus-Pro-7B | 4096 | 🤗 Hugging Face |
安装依赖
在环境基础上Python >= 3.8,运行以下命令安装必要的依赖项:
pip install -e .
2、Janus-Pro的使用方法
多模态理解
import torch
from transformers import AutoModelForCausalLM
from janus.models import MultiModalityCausalLM, VLChatProcessor
from janus.utils.io import load_pil_images
# specify the path to the model
model_path = "deepseek-ai/Janus-Pro-7B"
vl_chat_processor: VLChatProcessor = VLChatProcessor.from_pretrained(model_path)
tokenizer = vl_chat_processor.tokenizer
vl_gpt: MultiModalityCausalLM = AutoModelForCausalLM.from_pretrained(
model_path, trust_remote_code=True
)
vl_gpt = vl_gpt.to(torch.bfloat16).cuda().eval()
conversation = [
{
"role": "<|User|>",
"content": f"<image_placeholder>\n{question}",
"images": [image],
},
{"role": "<|Assistant|>", "content": ""},
]
# load images and prepare for inputs
pil_images = load_pil_images(conversation)
prepare_inputs = vl_chat_processor(
conversations=conversation, images=pil_images, force_batchify=True
).to(vl_gpt.device)
# # run image encoder to get the image embeddings
inputs_embeds = vl_gpt.prepare_inputs_embeds(**prepare_inputs)
# # run the model to get the response
outputs = vl_gpt.language_model.generate(
inputs_embeds=inputs_embeds,
attention_mask=prepare_inputs.attention_mask,
pad_token_id=tokenizer.eos_token_id,
bos_token_id=tokenizer.bos_token_id,
eos_token_id=tokenizer.eos_token_id,
max_new_tokens=512,
do_sample=False,
use_cache=True,
)
answer = tokenizer.decode(outputs[0].cpu().tolist(), skip_special_tokens=True)
print(f"{prepare_inputs['sft_format'][0]}", answer)
文本到图像生成
import os
import PIL.Image
import torch
import numpy as np
from transformers import AutoModelForCausalLM
from janus.models import MultiModalityCausalLM, VLChatProcessor
# specify the path to the model
model_path = "deepseek-ai/Janus-Pro-7B"
vl_chat_processor: VLChatProcessor = VLChatProcessor.from_pretrained(model_path)
tokenizer = vl_chat_processor.tokenizer
vl_gpt: MultiModalityCausalLM = AutoModelForCausalLM.from_pretrained(
model_path, trust_remote_code=True
)
vl_gpt = vl_gpt.to(torch.bfloat16).cuda().eval()
conversation = [
{
"role": "<|User|>",
"content": "A stunning princess from kabul in red, white traditional clothing, blue eyes, brown hair",
},
{"role": "<|Assistant|>", "content": ""},
]
sft_format = vl_chat_processor.apply_sft_template_for_multi_turn_prompts(
conversations=conversation,
sft_format=vl_chat_processor.sft_format,
system_prompt="",
)
prompt = sft_format + vl_chat_processor.image_start_tag
@torch.inference_mode()
def generate(
mmgpt: MultiModalityCausalLM,
vl_chat_processor: VLChatProcessor,
prompt: str,
temperature: float = 1,
parallel_size: int = 16,
cfg_weight: float = 5,
image_token_num_per_image: int = 576,
img_size: int = 384,
patch_size: int = 16,
):
input_ids = vl_chat_processor.tokenizer.encode(prompt)
input_ids = torch.LongTensor(input_ids)
tokens = torch.zeros((parallel_size*2, len(input_ids)), dtype=torch.int).cuda()
for i in range(parallel_size*2):
tokens[i, :] = input_ids
if i % 2 != 0:
tokens[i, 1:-1] = vl_chat_processor.pad_id
inputs_embeds = mmgpt.language_model.get_input_embeddings()(tokens)
generated_tokens = torch.zeros((parallel_size, image_token_num_per_image), dtype=torch.int).cuda()
for i in range(image_token_num_per_image):
outputs = mmgpt.language_model.model(inputs_embeds=inputs_embeds, use_cache=True, past_key_values=outputs.past_key_values if i != 0 else None)
hidden_states = outputs.last_hidden_state
logits = mmgpt.gen_head(hidden_states[:, -1, :])
logit_cond = logits[0::2, :]
logit_uncond = logits[1::2, :]
logits = logit_uncond + cfg_weight * (logit_cond-logit_uncond)
probs = torch.softmax(logits / temperature, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
generated_tokens[:, i] = next_token.squeeze(dim=-1)
next_token = torch.cat([next_token.unsqueeze(dim=1), next_token.unsqueeze(dim=1)], dim=1).view(-1)
img_embeds = mmgpt.prepare_gen_img_embeds(next_token)
inputs_embeds = img_embeds.unsqueeze(dim=1)
dec = mmgpt.gen_vision_model.decode_code(generated_tokens.to(dtype=torch.int), shape=[parallel_size, 8, img_size//patch_size, img_size//patch_size])
dec = dec.to(torch.float32).cpu().numpy().transpose(0, 2, 3, 1)
dec = np.clip((dec + 1) / 2 * 255, 0, 255)
visual_img = np.zeros((parallel_size, img_size, img_size, 3), dtype=np.uint8)
visual_img[:, :, :] = dec
os.makedirs('generated_samples', exist_ok=True)
for i in range(parallel_size):
save_path = os.path.join('generated_samples', "img_{}.jpg".format(i))
PIL.Image.fromarray(visual_img[i]).save(save_path)
generate(
vl_gpt,
vl_chat_processor,
prompt,
)
Gradio 演示
T1、基于Huggingface部署的在线演示
测试地址:https://huggingface.co/spaces/deepseek-ai/Janus-1.3B
测试图文理解:
这张图片分为两部分,分别展示了不同语言模型在多模态理解任务和指令跟随基准测试中的表现。
测试文本生成:好像没能理解文本描述
T2、本地 gradio 演示
pip install -e .[gradio]
python demo/app_januspro.py
3、Janus的使用方法
多模态理解
import torch
from transformers import AutoModelForCausalLM
from janus.models import MultiModalityCausalLM, VLChatProcessor
from janus.utils.io import load_pil_images
# specify the path to the model
model_path = "deepseek-ai/Janus-1.3B"
vl_chat_processor: VLChatProcessor = VLChatProcessor.from_pretrained(model_path)
tokenizer = vl_chat_processor.tokenizer
vl_gpt: MultiModalityCausalLM = AutoModelForCausalLM.from_pretrained(
model_path, trust_remote_code=True
)
vl_gpt = vl_gpt.to(torch.bfloat16).cuda().eval()
conversation = [
{
"role": "User",
"content": "<image_placeholder>\nConvert the formula into latex code.",
"images": ["images/equation.png"],
},
{"role": "Assistant", "content": ""},
]
# load images and prepare for inputs
pil_images = load_pil_images(conversation)
prepare_inputs = vl_chat_processor(
conversations=conversation, images=pil_images, force_batchify=True
).to(vl_gpt.device)
# # run image encoder to get the image embeddings
inputs_embeds = vl_gpt.prepare_inputs_embeds(**prepare_inputs)
# # run the model to get the response
outputs = vl_gpt.language_model.generate(
inputs_embeds=inputs_embeds,
attention_mask=prepare_inputs.attention_mask,
pad_token_id=tokenizer.eos_token_id,
bos_token_id=tokenizer.bos_token_id,
eos_token_id=tokenizer.eos_token_id,
max_new_tokens=512,
do_sample=False,
use_cache=True,
)
answer = tokenizer.decode(outputs[0].cpu().tolist(), skip_special_tokens=True)
print(f"{prepare_inputs['sft_format'][0]}", answer)
文本到图像生成
import os
import PIL.Image
import torch
import numpy as np
from transformers import AutoModelForCausalLM
from janus.models import MultiModalityCausalLM, VLChatProcessor
# specify the path to the model
model_path = "deepseek-ai/Janus-1.3B"
vl_chat_processor: VLChatProcessor = VLChatProcessor.from_pretrained(model_path)
tokenizer = vl_chat_processor.tokenizer
vl_gpt: MultiModalityCausalLM = AutoModelForCausalLM.from_pretrained(
model_path, trust_remote_code=True
)
vl_gpt = vl_gpt.to(torch.bfloat16).cuda().eval()
conversation = [
{
"role": "User",
"content": "A stunning princess from kabul in red, white traditional clothing, blue eyes, brown hair",
},
{"role": "Assistant", "content": ""},
]
sft_format = vl_chat_processor.apply_sft_template_for_multi_turn_prompts(
conversations=conversation,
sft_format=vl_chat_processor.sft_format,
system_prompt="",
)
prompt = sft_format + vl_chat_processor.image_start_tag
@torch.inference_mode()
def generate(
mmgpt: MultiModalityCausalLM,
vl_chat_processor: VLChatProcessor,
prompt: str,
temperature: float = 1,
parallel_size: int = 16,
cfg_weight: float = 5,
image_token_num_per_image: int = 576,
img_size: int = 384,
patch_size: int = 16,
):
input_ids = vl_chat_processor.tokenizer.encode(prompt)
input_ids = torch.LongTensor(input_ids)
tokens = torch.zeros((parallel_size*2, len(input_ids)), dtype=torch.int).cuda()
for i in range(parallel_size*2):
tokens[i, :] = input_ids
if i % 2 != 0:
tokens[i, 1:-1] = vl_chat_processor.pad_id
inputs_embeds = mmgpt.language_model.get_input_embeddings()(tokens)
generated_tokens = torch.zeros((parallel_size, image_token_num_per_image), dtype=torch.int).cuda()
for i in range(image_token_num_per_image):
outputs = mmgpt.language_model.model(inputs_embeds=inputs_embeds, use_cache=True, past_key_values=outputs.past_key_values if i != 0 else None)
hidden_states = outputs.last_hidden_state
logits = mmgpt.gen_head(hidden_states[:, -1, :])
logit_cond = logits[0::2, :]
logit_uncond = logits[1::2, :]
logits = logit_uncond + cfg_weight * (logit_cond-logit_uncond)
probs = torch.softmax(logits / temperature, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
generated_tokens[:, i] = next_token.squeeze(dim=-1)
next_token = torch.cat([next_token.unsqueeze(dim=1), next_token.unsqueeze(dim=1)], dim=1).view(-1)
img_embeds = mmgpt.prepare_gen_img_embeds(next_token)
inputs_embeds = img_embeds.unsqueeze(dim=1)
dec = mmgpt.gen_vision_model.decode_code(generated_tokens.to(dtype=torch.int), shape=[parallel_size, 8, img_size//patch_size, img_size//patch_size])
dec = dec.to(torch.float32).cpu().numpy().transpose(0, 2, 3, 1)
dec = np.clip((dec + 1) / 2 * 255, 0, 255)
visual_img = np.zeros((parallel_size, img_size, img_size, 3), dtype=np.uint8)
visual_img[:, :, :] = dec
os.makedirs('generated_samples', exist_ok=True)
for i in range(parallel_size):
save_path = os.path.join('generated_samples', "img_{}.jpg".format(i))
PIL.Image.fromarray(visual_img[i]).save(save_path)
generate(
vl_gpt,
vl_chat_processor,
prompt,
)
Gradio 演示
T1、基于Huggingface部署的在线演示
持续更新中……
T2、本地 gradio 演示
pip install -e .[gradio]
python demo/app.py
FastAPI 演示
运行 FastAPI 服务器来托管运行与 gradio 相同功能的 API 服务器很容易。
要启动 FastAPI 服务器,请运行以下命令:
python demo/fastapi_app.py
要测试服务器,您可以打开另一个终端并运行:
python demo/fastapi_client.py
4、JanusFlow的使用方法
更新中……
Janus的案例应用
根据模型的描述,Janus系列模型可以应用于各种多模态任务,例如:
图像理解:对图像内容进行理解和描述。
图像生成:根据文本指令生成图像。
视觉问答:根据图像回答问题。
其他多模态任务:例如视频理解、跨模态检索等。