跳到正文
Hugging Face Blog·· 2024-09-25精選AI 評分79

Meta 發佈 Llama 3.2,涵蓋視覺模型與裝置端小型模型

Llama can now see and run on your device - welcome Llama 3.2

AI 導讀

Meta 發佈 Llama 3.2,共有 10 個開放權重模型,包括 5 個多模態模型和 5 個純文字模型,涵蓋 11B、90B 視覺模型及面向裝置端的 1B、3B 純文字模型。

推薦理由

Llama 3.2 涵蓋 11B、90B 視覺模型與 1B、3B 裝置端純文字模型,並列出 Transformers、llama.cpp 等運行示例,可作為選擇部署路徑的參考。

正文 · 繁體中文

Llama 3.2 正式推出!今天,我們歡迎 Llama 系列新一代模型登陸 Hugging Face。這次我們很高興與 Meta 合作,推出多模態和小型模型。Hub 上現有 10 款開放權重模型(5 款多模態和 5 款純文字模型)。

Llama 3.2 Vision 有兩種規模:11B 適合在一般消費級 GPU 高效部署和開發,90B 則適用於大規模應用。兩種規模均提供基礎版和指令微調版。除了 4 款多模態模型,Meta 也推出支援視覺的新版本 Llama Guard。Llama Guard 3 是一款安全防護模型,可分類模型輸入和生成內容,包括偵測有害的多模態提示或助理回應。

Llama 3.2 也包括可在裝置上執行的小型純文字語言模型,新增 1B 和 3B 兩種規模,均提供基礎版和 instruct 版;以相應規模而言,能力相當出色。此外還有 1B 的小型 Llama Guard,可與這些模型或較大型文字模型一起部署於生產應用。

此次推出的功能和整合包括:

目錄

甚麼是 Llama 3.2 Vision?

Llama 3.2 Vision 是 Meta 推出的最強開放多模態模型,具備出色的視覺理解和推理能力,可執行多種任務,包括視覺推理和 grounding、文件問答,以及圖文檢索。它經常能產生優秀的思維鏈(CoT)答案,因此特別適合視覺推理。

Llama 3.2 Vision 可同時處理文字和圖像,也能只處理文字。使用圖文提示時,模型只接受英文輸入;純文字提示則支援多種語言。

純文字模式支援的語言完整清單如下:

  • 英文
  • 德文
  • 法文
  • 意大利文
  • 葡萄牙文
  • 印地文
  • 西班牙文
  • 泰文

這些模型結合 Llama 3.1 LLM、視覺主幹和圖像 adapter。Llama 3.2 11B Vision 使用 Llama 3.1 8B 作為文字模型;3.2 90B Vision 則使用 Llama 3.1 70B。據我們瞭解,訓練視覺模型期間,文字模型保持凍結,以保留純文字表現。

以下是 11B 指令微調模型的推論示例,展示其現實知識、文件推理和資訊圖表理解能力。

輸入圖像輸入提示回答
這個地方在哪裏?附近還有甚麼景點? 圖像顯示泰國曼谷的大皇宮。這是一組建築羣,曾作為暹羅國王的官邸和政府行政中心達 150 年。它是曼谷最受歡迎的旅遊景點之一,也是到訪曼谷必看的地方。

大皇宮附近的其他景點包括:
* 玉佛寺:位於大皇宮建築羣內,供奉著著名的翡翠佛像。
* 鄭王廟:位於昭披耶河西岸,以壯麗建築和優美城市景觀聞名。
* 卧佛寺:位於大皇宮附近,供奉大型卧佛像。

根據這幅圖,哪些地區發生旱災? 2016 年旱災地區
根據圖示,2016 年有兩個地區發生旱災:
* 東非和南非:這些地區遭遇嚴重旱災。
* 智利:智利在 1 月經歷了 50 多年來最乾旱的情況。這些地區在當時都面臨嚴重缺水問題。
由發票日期到到期日相隔多久?請簡短回答。 發票日期:11/02/2019
到期日:26/02/2019
時間差計算:
26/02/2019 - 11/02/2019 = 15 日
發票日期到到期日相隔 15 日。

視覺模型的 context 長度為 128k tokens,可支援包含圖像的多輪對話。不過,模型處理單一圖像時表現最佳,因此 transformers 實作只會關注輸入中的最後一張圖像。這樣能維持品質並節省記憶體。

11B 基礎模型支援 448 tile 尺寸;instruct 版和 90B 模型則使用 560 tile 尺寸。模型以包含 60 億組圖文配對的龐大多元資料集訓練,非常適合針對下游任務微調。Meta 提供的部分基準測試如下,可比較 11B、90B 及其指令微調版本。如需其他基準測試和詳情,請參閲 model card。

11B 11B(指令微調) 90B 90B(指令微調) 指標
MMMU(驗證集) 41.7 50.7(CoT) 49.3(zero-shot) 60.3(CoT) 微平均準確率
VQAv2 66.8(驗證集) 75.2(測試集) 73.6(驗證集) 78.1(測試集) 準確率
DocVQA 62.3(驗證集) 88.4(測試集) 70.7(驗證集) 90.1(測試集) ANLS
AI2D 62.4 91.1 75.3 92.3 準確率

我們預期這些模型的文字能力分別與 8B 和 70B Llama 3.1 相若,因為據我們瞭解,訓練 Vision 模型時文字模型保持凍結。因此,文字基準測試應與 8B 和 70B 模型一致。

Llama 3.2 授權變更。歐盟用戶抱歉 :(

License Change

授權條款方面,Llama 3.2 與 Llama 3.1 採用非常相似的授權,唯獨可接受使用政策有一項重要差異:居住於歐盟的個人,或主要營業地位於歐盟的公司,均未獲授權使用 Llama 3.2 所含多模態模型。若產品或服務包含這類多模態模型,此限制不適用於產品或服務的終端使用者,因此大家仍可使用視覺版本建立全球產品。

完整詳情請務必閲讀官方授權和可接受使用政策。

Llama 3.2 1B 和 3B 有甚麼特別?

Llama 3.2 系列包括 1B 和 3B 純文字模型,專為裝置端用途設計,例如改寫提示、多語言知識檢索、摘要、工具使用和本機助理。它們勝過許多同等規模的開放存取模型,並可與大上數倍的模型競爭。本文稍後會示範如何離線執行。

模型架構與 Llama 3.1 相同,以最多 9 兆 tokens 訓練,並支援長達 128k tokens 的 context。模型支援多種語言,包括英文、德文、法文、意大利文、葡萄牙文、印地文、西班牙文和泰文。

另有新版小型 Llama Guard,即 Llama Guard 3 1B,可與這些模型一起部署,評估多輪對話中最近一則使用者或助理回應。它使用一組預先定義的類別(此版本新增功能),可按開發者的使用場景自訂或排除。Llama Guard 詳情請參閲 model card。

補充:Llama 3.2 接觸過比上述 8 種支援語言更廣泛的語言。鼓勵開發者針對自己的語言使用場景微調 Llama 3.2 模型。

我們以 Open LLM Leaderboard 評估基礎模型;instruct 模型則以 3 項熱門基準測試評估,這些測試衡量指令遵循能力,並與 LMSYS Chatbot Arena 有良好相關性:IFEval、AlpacaEval 和 MixEval-Hard。以下是基礎模型結果,並列入 Llama-3.1-8B 作參考:

模型 BBH MATH Lvl 5 GPQA MUSR MMLU-PRO 平均
Meta-Llama-3.2-1B 4.37 0.23 0.00 2.56 2.26 1.88
Meta-Llama-3.2-3B 14.73 1.28 4.03 3.39 16.57 8.00
Meta-Llama-3.1-8B 25.29 4.61 6.15 8.98 24.95 14.00

以下是 instruct 模型結果,並列入 Llama-3.1-8B-Instruct 作參考:

模型 AlpacaEval(LC) IFEval MixEval-Hard 平均
Meta-Llama-3.2-1B-Instruct 7.17 58.92 26.10 30.73
Meta-Llama-3.2-3B-Instruct 20.88 77.01 31.80 43.23
Meta-Llama-3.1-8B-Instruct 25.74 76.49 44.10 48.78

值得注意的是,3B 模型在 IFEval 的表現與 8B 模型一樣好!由於遵循指令對提升可靠性至關重要,這令模型特別適合 agent 應用。以這個規模而言,IFEval 分數非常出色。

1B 和 3B 指令微調模型都支援工具使用。使用者可在 zero-shot 情況下指定工具(模型事前不知道開發者會使用哪些工具)。因此,Llama 3.1 模型內建的工具(brave_search 和 wolfram_alpha)不再提供。

這些小型模型可作為較大型模型的助理,並執行輔助生成(亦稱推測解碼)。此處示範如何把 Llama 3.2 1B 用作 Llama 3.1 8B 的助理。如需離線使用,請參閲本文稍後的裝置端執行一節。

示範

以下示範可試用 3 款 Instruct 模型:

Demo GIF

使用 Hugging Face Transformers

純文字 checkpoint 架構與先前版本相同,無需更新環境。不過,由於採用新架構,Llama 3.2 Vision 需要更新 Transformers。請升級至 4.45.0 或更新版本。

pip install "transformers>=4.45.0" --upgrade

升級後便可使用全新的 Llama 3.2 模型,並運用 Hugging Face 生態系統中的所有工具。

Llama 3.2 1B 和 3B 語言模型

使用 Transformers,只需幾行程式碼便可執行 1B 和 3B 文字模型 checkpoint。checkpoint 以 bfloat16 精度上載,但你也可使用 float16 或量化權重。記憶體需求取決於模型大小和權重精度。以下列出不同配置的約略推論記憶體需求:

模型大小 BF16/FP16 FP8 INT4
3B 6.5 GB 3.2 GB 1.75 GB
1B 2.5 GB 1.25 GB 0.75 GB
from transformers import pipeline
import torch

model_id = "meta-llama/Llama-3.2-3B-Instruct"
pipe = pipeline(
    "text-generation",
    model=model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto",
)

messages = [
    {"role": "user", "content": "Who are you? Please, answer in pirate-speak."},
]
outputs = pipe(
    messages,
    max_new_tokens=256,
)
response = outputs[0]["generated_text"][-1]["content"]
print(response)
# Arrrr, me hearty! Yer lookin' fer a bit o' information about meself, eh? Alright then, matey! I be a language-generatin' swashbuckler, a digital buccaneer with a penchant fer spinnin' words into gold doubloons o' knowledge! Me name be... (dramatic pause)...Assistant! Aye, that be me name, and I be here to help ye navigate the seven seas o' questions and find the hidden treasure o' answers! So hoist the sails and set course fer adventure, me hearty! What be yer first question?

補充兩點:

  • 我們以 bfloat16 載入模型。如上所述,這是 Meta 原始 checkpoint 使用的格式,因此建議採用,確保精度最高或進行評估。視乎硬件而定,float16 可能更快。

  • 預設情況下,transformers 使用與 Meta 原始程式碼庫相同的抽樣參數(temperature=0.6 和 top_p=0.9)。我們尚未進行全面測試,歡迎自行探索!

Llama 3.2 Vision

Vision 模型較大,執行時比小型文字模型需要更多記憶體。供參考,11B Vision 模型以 4-bit 模式推論時約需 10 GB GPU RAM。

使用內建 chat template,是推論指令微調 Llama Vision 模型最簡單的方法。輸入包含 user 和 assistant 角色,用以表示對話輪次。與文字模型不同的是,它不支援 system 角色。使用者輪次可包含圖文或純文字輸入。若要表示輸入含圖像,請在輸入的 content 部分加入 {"type": "image"},再把圖像資料傳給 processor:

import requests
import torch
from PIL import Image
from transformers import MllamaForConditionalGeneration, AutoProcessor

model_id = "meta-llama/Llama-3.2-11B-Vision-Instruct"
model = MllamaForConditionalGeneration.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device="cuda",
)
processor = AutoProcessor.from_pretrained(model_id)

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg"
image = Image.open(requests.get(url, stream=True).raw)

messages = [
    {"role": "user", "content": [
        {"type": "image"},
        {"type": "text", "text": "Can you please describe this image in just one sentence?"}
    ]}
]

input_text = processor.apply_chat_template(
    messages, add_generation_prompt=True,
)
inputs = processor(
    image,
    input_text,
    add_special_tokens=False,
    return_tensors="pt",
).to(model.device)
output = model.generate(**inputs, max_new_tokens=70)

print(processor.decode(output[0][inputs["input_ids"].shape[-1]:]))


## The image depicts a rabbit dressed in a blue coat and brown vest, standing on a dirt road in front of a stone house.

你可以繼續就圖像內容對話。不過請記住,如果在新的使用者輪次提供另一張圖像,模型從那時起就會改為參照新圖像;你無法同時詢問兩張不同圖像。以下示範如何延續先前對話:把助理輪次加入對話,再詢問更多詳情。

messages = [
    {"role": "user", "content": [
        {"type": "image"},
        {"type": "text", "text": "Can you please describe this image in just one sentence?"}
    ]},
    {"role": "assistant", "content": "The image depicts a rabbit dressed in a blue coat and brown vest, standing on a dirt road in front of a stone house."},
    {"role": "user", "content": "What is in the background?"}
]

input_text = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
)
inputs = processor(image, input_text, return_tensors="pt").to(model.device)
output = model.generate(**inputs, max_new_tokens=70)
print(processor.decode(output[0][inputs["input_ids"].shape[-1]:]))

這是我們收到的回答:

In the background, there is a stone house with a thatched roof, a dirt road, a field of flowers, and rolling hills.

你也可透過 bitsandbytes 函式庫自動量化模型,以 8-bit 或 4-bit 模式載入。以下示範如何以 4-bit 載入生成 pipeline:

import torch
from transformers import MllamaForConditionalGeneration, AutoProcessor
+from transformers import BitsAndBytesConfig

+bnb_config = BitsAndBytesConfig(
+    load_in_4bit=True,
+    bnb_4bit_quant_type="nf4",
+    bnb_4bit_compute_dtype=torch.bfloat16
)
 
model = MllamaForConditionalGeneration.from_pretrained(
    model_id,
-   torch_dtype=torch.bfloat16,
-   device="cuda",
+   quantization_config=bnb_config,
)

接着套用 chat template、使用 processor,並像之前一樣呼叫模型。

裝置端執行

你可透過以下幾個開放原始碼函式庫,在裝置的 CPU、GPU 或瀏覽器直接執行 Llama 3.2 1B 和 3B。

Llama.cpp 和 Llama-cpp-python

Llama.cpp 是跨平台裝置端 ML 推論的首選框架。我們為這個系列的 1B 和 3B 模型提供 4-bit 和 8-bit 量化權重。期待社羣採用這些模型,並建立更多量化版本和微調模型。你可在此處找到所有量化版 Llama 3.2 模型。

以下示範如何直接透過 llama.cpp 使用這些 checkpoint。

透過 brew 安裝 llama.cpp(適用於 Mac 和 Linux)。

brew install llama.cpp

你可使用 CLI 執行單次生成,或啟動與 OpenAI messages 規格相容的 llama.cpp server。

可使用以下類似指令執行 CLI:

llama-cli --hf-repo hugging-quants/Llama-3.2-3B-Instruct-Q8_0-GGUF --hf-file llama-3.2-3b-instruct-q8_0.gguf -p "The meaning to life and the universe is"

可使用以下指令啟動 server:

llama-server --hf-repo hugging-quants/Llama-3.2-3B-Instruct-Q8_0-GGUF --hf-file llama-3.2-3b-instruct-q8_0.gguf -c 2048

你也可使用 llama-cpp-python,在 Python 中以程式方式使用這些模型。使用 PyPI 安裝函式庫:

pip install llama-cpp-python

然後即可如下執行模型:

from llama_cpp import Llama

llm = Llama.from_pretrained(
    repo_id="hugging-quants/Llama-3.2-3B-Instruct-Q8_0-GGUF",
    filename="*q8_0.gguf",
)
output = llm.create_chat_completion(
      messages = [
          {
              "role": "user",
              "content": "What is the capital of France?"
          }
      ]
)

print(output)

Transformers.js

你甚至可使用 Transformers.js,在瀏覽器或 Node.js、Deno、Bun 等 JavaScript runtime 執行 Llama 3.2。你可在 Hub 找到 ONNX 模型。如果尚未安裝,可透過 NPM 安裝函式庫:

npm i @huggingface/transformers

然後即可如下執行模型:

import { pipeline } from "@huggingface/transformers";

// Create a text generation pipeline
const generator = await pipeline("text-generation", "onnx-community/Llama-3.2-1B-Instruct");

// Define the list of messages
const messages = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content: "Tell me a joke." },
];

// Generate a response
const output = await generator(messages, { max_new_tokens: 128 });
console.log(output[0].generated_text.at(-1).content);

輸出示例

Here's a joke for you:

What do you call a fake noodle?

An impasta!

I hope that made you laugh! Do you want to hear another one?

MLC.ai Web-LLM

MLC.ai Web-LLM 是高效能瀏覽器內 LLM 推論 engine,可直接在網頁瀏覽器中執行語言模型推論,並使用硬件加速。所有工作都在瀏覽器中執行,無需伺服器支援,並由 WebGPU 加速。

WebLLM 完全相容 OpenAI API。也就是説,你可在本機對任何開放原始碼模型使用相同的 OpenAI API,支援串流、JSON 模式、function calling 等功能。

可透過 npm 安裝 Web-LLM。

npm install @mlc/web-llm

然後即可如下執行模型:

// Import everything
import * as webllm from "@mlc-ai/web-llm";
// Or only import what you need
import { CreateMLCEngine } from "@mlc-ai/web-llm";

// Callback function to update model loading progress
const initProgressCallback = (initProgress) => {
  console.log(initProgress);
}
const selectedModel = "Llama-3.2-3B-Instruct-q4f32_1-MLC";

const engine = await CreateMLCEngine(
  selectedModel,
  { initProgressCallback: initProgressCallback }, // engineConfig
);

成功初始化 engine 後,你便可透過 engine.chat.completions 介面,使用 OpenAI 風格的 chat API 呼叫聊天 completion。

const messages = [
  { role: "system", content: "You are a helpful AI assistant." },
  { role: "user", content: "Explain the meaning of life as a pirate!" },
]

const reply = await engine.chat.completions.create({
  messages,
});
console.log(reply.choices[0].message);
console.log(reply.usage);

微調 Llama 3.2

TRL 開箱即支援 Llama 3.2 文字模型的聊天和微調:

# Chat
trl chat --model_name_or_path meta-llama/Llama-3.2-3B

# Fine-tune
trl sft  --model_name_or_path meta-llama/Llama-3.2-3B \
         --dataset_name HuggingFaceH4/no_robots \
         --output_dir Llama-3.2-3B-Instruct-sft \
         --gradient_checkpointing

TRL 也支援微調 Llama 3.2 Vision,請參閲這個指令碼。

# Tested on 8x H100 GPUs
accelerate launch --config_file=examples/accelerate_configs/deepspeed_zero3.yaml \
    examples/sft_visual_chat/sft_visual_chat.py \
    --dataset_name HuggingFaceH4/llava-instruct-mix-vsft \
    --model_name_or_path meta-llama/Llama-3.2-11B-Vision-Instruct \
    --per_device_train_batch_size 8 \
    --gradient_accumulation_steps 8 \
    --output_dir Llama-3.2-11B-Vision-Instruct-sft \
    --bf16 \
    --torch_dtype bfloat16 \
    --gradient_checkpointing

你也可查看這份 Notebook,瞭解如何使用 transformers 和 PEFT 進行 LoRA 微調。

Hugging Face 合作夥伴整合

我們正與 AWS、Google Cloud、Microsoft Azure 和 DELL 合作,把 Llama 3.2 11B、90B 加入 Amazon SageMaker、Google Kubernetes Engine、Vertex AI Model Catalog、Azure AI Studio 和 DELL Enterprise Hub。容器一旦推出,我們便會更新本節;你也可訂閲 Hugging Squad 接收電郵通知。

其他資源

鳴謝

如果沒有數以千計社羣成員為 transformers、text-generation-inference、vllm、pytorch、LM Eval Harness 和許多其他專案作出貢獻,就不可能在生態系統中推出這類模型,並提供支援和評估。特別感謝 VLLM 團隊協助測試並回報問題。這次發佈也有賴多位人士的支持:Clémentine、Alina、Elie 和 Loubna 負責 LLM 評估;Nicolas Patry、Olivier Dehaene 和 Daniël de Kok 負責 Text Generation Inference;Lysandre、Arthur、Pavel、Edward Beeching、Amy、Benjamin、Joao、Pablo、Raushan Turganbay、Matthew Carrigan 和 Joshua Lochner 支援 transformers、transformers.js、TRL 和 PEFT;Nathan Sarrazin 和 Victor 讓 Llama 3.2 登陸 Hugging Chat;Brigitte Tousignant 和 Florent Daudens 負責溝通;Hub 團隊的 Julien、Simon、Pierric、Eliott、Lucain、Alvaro、Caleb 和 Mishig 則負責 Hub 開發和發佈功能。

也非常感謝 Meta 團隊推出 Llama 3.2,並讓開放 AI 社羣能夠使用!

來源:Hugging Face Blog · huggingface.co