以下程序調用本地部署的 LLaMA3 模型進行多輪對話生成,通過 Hugging Face Transformers API 加載、預處理、生成并輸出最終回答。
- 程序用的是 Chat 模型格式(如 LLaMA3 Instruct 模型),遵循 ChatML 模板,并使用 apply_chat_template 正確構造 prompt。
首先執行下面這個python腳本下載大模型到本地(下載到本地的具體路徑通過cache_dir參數指定)。
#模型下載
from modelscope import snapshot_download
model_dir = snapshot_download('LLM-Research/Llama-3.2-1B-Instruct', cache_dir="/root/autodl-tmp/llm")
然后,加載下載好的本地大模型,執行后續操作
from transformers import AutoModelForCausalLM, AutoTokenizerDEVICE = "cuda"# 加載本地模型路徑為該模型配置文件所在的根目錄
model_dir = "/root/autodl-tmp/llm/LLM-Research/Llama-3___2-1B-Instruct"
# 使用transformer加載模型
model = AutoModelForCausalLM.from_pretrained(model_dir, torch_dtype="auto", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_dir)# 調用模型
# 定義提示詞
prompt = "你好,你叫什么名字?你是由誰創造的?"
# 將提示詞封裝為message
messages = [{"role": "system", "content": "You are a helpful assistant system"},{"role": "user", "content": prompt}]
# 使用分詞器的apply_chat_template方法將messages轉換為chat引擎可以接受的信息
# tokenize=False表示此時不進行令牌化
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)print("--------------")
print(text)
print("--------------")# 將處理后的文本令牌化并轉換為模型的輸入張量
model_inputs = tokenizer([text], return_tensors="pt").to(DEVICE)
# 輸入模型得到輸出
generated = model.generate(model_inputs.input_ids, max_new_tokens=512)
print(generated)# 對輸出的內容進行解碼還原
response = tokenizer.batch_decode(generated, skip_special_tokens=True)
print(response)
root@autodl-container-38c543b634-d7f7c9f4:~/autodl-tmp/demo_10# python llama3.2_test.py
--------------
<|begin_of_text|><|start_header_id|>system<|end_header_id|>Cutting Knowledge Date: December 2023
Today Date: 12 May 2025You are a helpful assistant system<|eot_id|><|start_header_id|>user<|end_header_id|>你好,你叫什么名字?你是由誰創造的?<|eot_id|><|start_header_id|>assistant<|end_header_id|>--------------
The attention mask and the pad token id were not set. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.
Setting `pad_token_id` to `eos_token_id`:128001 for open-end generation.
The attention mask is not set and cannot be inferred from input because pad token is same as eos token. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.
tensor([[128000, 128000, 128006, 9125, 128007, 271, 38766, 1303, 33025,2696, 25, 6790, 220, 2366, 18, 198, 15724, 2696,25, 220, 717, 3297, 220, 2366, 20, 271, 2675,527, 264, 11190, 18328, 1887, 128009, 128006, 882, 128007,271, 57668, 53901, 104660, 105424, 101879, 119395, 11571, 57668,21043, 68171, 112471, 104251, 67178, 9554, 11571, 128009, 128006,78191, 128007, 271, 37046, 21043, 16197, 44689, 15836, 18328,3922, 113230, 13372, 18184, 445, 81101, 1811, 43, 81101,55951, 16197, 44689, 48044, 27384, 121790, 9554, 109683, 120074,55642, 123123, 3922, 68438, 38129, 43240, 87502, 41007, 37507,111478, 34208, 23226, 42399, 1811, 128009]], device='cuda:0')
['system\n\nCutting Knowledge Date: December 2023\nToday Date: 12 May 2025\n\nYou are a helpful assistant systemuser\n\n你好,你叫什么名字?你是由誰創造的?assistant\n\n我是 Meta 的AI assistant,目前名為 Llama。Llama 是 Meta 的一個大規模的自然語言處理模型,通過使用多種方法來學習和改進。']
這段程序的目的是:使用本地部署的 LLaMA 3 模型進行多輪中文對話生成,主要包括模型加載、輸入構造、文本生成和輸出解析四個核心部分。
程序一開始導入了必要的模塊,并設置計算設備為 "cuda"
,也就是使用 GPU 來加速模型推理。接著,它指定了模型所在的本地目錄路徑 model_dir
,這個目錄中應該包含 Hugging Face 格式的模型權重和配置文件。程序通過 AutoModelForCausalLM.from_pretrained
來加載模型,并指定了 torch_dtype="auto"
和 device_map="auto"
,這讓 transformers 自動選擇合適的數據精度(比如 float16)并智能將模型加載到可用的 GPU 上(需要安裝 accelerate 庫)。同時,AutoTokenizer
也從該路徑中加載對應的分詞器,它會把人類語言轉換成模型可以理解的 token ID。
接下來,程序準備了一條用戶輸入:你好,你叫什么名字?你是由誰創造的?
。為了構建標準的聊天輸入,程序創建了一個 messages
列表,其中包含一個 "system"
信息(設定助手角色),以及一條 "user"
提問。這種格式是 Chat 模型(如 LLaMA3 Instruct)所支持的,類似于 ChatGPT 的對話格式。之后,通過 tokenizer.apply_chat_template
方法將這組消息轉換為模型能夠理解的 純文本格式。這個方法的參數中,tokenize=False
表示暫時不轉換為 token ID,而 add_generation_prompt=True
會在文本結尾添加生成提示符,引導模型開始生成回答。
完成 prompt 構造后,程序使用分詞器將文本轉換為 token ID,并用 return_tensors="pt"
表示返回 PyTorch 張量,隨后將其 .to(DEVICE)
移到 GPU 上,準備作為模型輸入。然后調用 model.generate
方法,讓模型基于輸入生成回復。這里設置了 max_new_tokens=512
,即最多生成 512 個 token 的新內容。
模型生成的是一串 token ID,因此最后一步需要用分詞器進行反解碼。tokenizer.batch_decode
方法會將生成的 token 序列還原為人類可讀的自然語言文本,skip_special_tokens=True
參數會去除控制符號。程序最后將生成的回復打印出來,實現了從用戶提問到模型生成回答的完整過程。