昨天完成了Hugging Face的Token申請 和模型授權,今天就要來驗證這些準備到底有沒有用:實際在Colab上下載一個受限模型(我選的是Gemma-3-1B-Instruct),並讓它跑出第一段文字。
實際操作
from huggingface_hub import login
# 貼上你的 Token(xxxxxxxx)
login("xxxxxxxx")
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
model_id = "google/gemma-3-1b-it"
# 載入 tokenizer 和模型
tok = AutoTokenizer.from_pretrained(model_id, use_auth_token=True, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_id,
device_map="auto",
torch_dtype="auto",
use_auth_token=True,
trust_remote_code=True
)
# 建立 pipeline
pipe = pipeline("text-generation", model=model, tokenizer=tok)
prompt = "你是一個人工智慧專家,請用三句話簡潔易懂解釋人工智慧在醫療上的應用。"
resp = pipe(prompt, max_new_tokens=100, temperature=0.7, top_p=0.9)[0]["generated_text"]
print(resp)
4.執行結果
和前幾天GPT-2動不動就亂接龍或句子重複比起來,Gemma的輸出真的清楚太多了...