
中文命名實體識別(Named Entity Recognition, NER)初探
Janus 的設(shè)計靈感來源于羅馬神話中的雙面神 Janus,象征著理解與生成之間的平衡。模型通過獨立的視覺編碼器分別處理高維語義信息和低維空間細(xì)節(jié),使得多模態(tài)理解任務(wù)能夠提取更豐富的語義特征,而視覺生成任務(wù)則能夠生成更高質(zhì)量的圖像。
Janus 的核心創(chuàng)新在于分離視覺編碼路徑。在多模態(tài)理解任務(wù)中,模型需要提取圖像中的高級語義信息,例如物體類別和視覺屬性;而在視覺生成任務(wù)中,模型需要關(guān)注圖像的局部細(xì)節(jié)和全局一致性。傳統(tǒng)的多模態(tài)模型通常使用單一視覺編碼器來處理這兩種任務(wù),這會導(dǎo)致性能上的妥協(xié)。Janus 通過引入兩個獨立的視覺編碼器,分別針對理解任務(wù)和生成任務(wù)進(jìn)行優(yōu)化,從而解決了這一問題。
在多模態(tài)理解方面,Janus 在多個基準(zhǔn)測試中取得了優(yōu)異的成績。例如,在 MMBench、POPE、MME 等數(shù)據(jù)集上,Janus 的表現(xiàn)超過了之前的統(tǒng)一模型和其他一些特定任務(wù)的模型。在視覺生成方面,Janus 在 GenEval 和 DPG-Bench 等基準(zhǔn)測試中也表現(xiàn)出色,甚至在某些指標(biāo)上超過了 OpenAI 的 DALL-E 3 等知名模型。
Janus 的架構(gòu)基于 DeepSeek-LLM-1.3B 和 DeepSeek-LLM-7B,使用 SigLIP-L 作為視覺編碼器,支持 384×384 的圖像輸入。模型通過獨立的適配器將視覺特征映射到語言模型的輸入空間,然后通過統(tǒng)一的自回歸變換器進(jìn)行處理。這種設(shè)計使得模型在處理多模態(tài)任務(wù)時更加靈活,并且可以輕松擴(kuò)展到其他模態(tài),例如點云、EEG 信號或音頻數(shù)據(jù)。
Janus 的訓(xùn)練分為三個階段。第一階段主要訓(xùn)練適配器和圖像頭部,使模型能夠初步理解圖像內(nèi)容并具備基本的視覺生成能力。第二階段是統(tǒng)一預(yù)訓(xùn)練,使用多模態(tài)語料庫對模型進(jìn)行訓(xùn)練,使其能夠同時學(xué)習(xí)多模態(tài)理解和生成任務(wù)。第三階段是監(jiān)督微調(diào),通過指令調(diào)整數(shù)據(jù)來增強(qiáng)模型的指令遵循和對話能力。
DeepSeek Janus 提供了詳細(xì)的使用指南和代碼示例,方便開發(fā)者快速上手。模型已經(jīng)在 Hugging Face 上發(fā)布,用戶可以直接下載并使用。此外,Janus 還提供了 Gradio 和 FastAPI 的在線演示,方便用戶進(jìn)行測試和部署。
在 Python 3.8 及以上環(huán)境中,用戶可以通過以下命令安裝必要的依賴:
pip install -e .
以下是一個多模態(tài)理解的簡單示例代碼:
import torch
from transformers import AutoModelForCausalLM
from janus.models import MultiModalityCausalLM, VLChatProcessor
from janus.utils.io import load_pil_images
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": ""},
]
pil_images = load_pil_images(conversation)
prepare_inputs = vl_chat_processor(
conversations=conversation, images=pil_images, force_batchify=True
).to(vl_gpt.device)
inputs_embeds = vl_gpt.prepare_inputs_embeds(**prepare_inputs)
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
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
# 生成圖像的函數(shù)
@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,
)
除了 Janus,DeepSeek 還發(fā)布了 JanusFlow,這是一個結(jié)合了自回歸語言模型和流修正(Rectified Flow)的新型多模態(tài)模型。JanusFlow 通過在大語言模型框架內(nèi)直接訓(xùn)練流修正,無需復(fù)雜的架構(gòu)修改,顯著提升了多模態(tài)任務(wù)的性能。
JanusFlow 在多模態(tài)理解與生成任務(wù)中表現(xiàn)出色,尤其是在圖像生成方面,能夠生成更高質(zhì)量的圖像。其架構(gòu)設(shè)計簡潔,易于擴(kuò)展,為多模態(tài)模型的發(fā)展提供了新的方向。
DeepSeek Janus 系列模型的發(fā)布,標(biāo)志著多模態(tài)人工智能領(lǐng)域的一個重要進(jìn)步。通過分離視覺編碼路徑,Janus 解決了傳統(tǒng)多模態(tài)模型中的關(guān)鍵問題,提升了模型的靈活性和性能。同時,JanusFlow 的創(chuàng)新設(shè)計進(jìn)一步展示了結(jié)合自回歸和流修正的潛力。
對于研究人員和開發(fā)者來說,Janus 系列模型提供了一個強(qiáng)大的開源工具,可以用于各種多模態(tài)應(yīng)用的開發(fā)和研究。隨著技術(shù)的不斷發(fā)展,我們期待 DeepSeek 團(tuán)隊在未來帶來更多突破性的成果。
如果你對 DeepSeek Janus 感興趣,可以訪問其 GitHub 倉庫獲取更多詳細(xì)信息和代碼資源。