使用預訓練 LLM

Python 的 LLM 入門

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

語言理解

一個人坐在桌前,周圍有多項任務,示意文字分類、摘要、情感分析與問答

Python 的 LLM 入門

語言生成

一個人坐在桌前,周圍有多項任務,示意文字生成與翻譯

Python 的 LLM 入門

文字生成

generator = pipeline(task="text-generation", model="distilgpt2")

prompt = "The Gion neighborhood in Kyoto is famous for"

output = generator(prompt, max_length=100, pad_token_id=generator.tokenizer.eos_token_id)
  • 連貫的
  • 有意義的
  • 近似人類的文字
  • eos_token_id:序列結尾的 token ID
Python 的 LLM 入門

文字生成

兩個序列示意:we should go、i really like to travel。包含 token id,並標示補位與 EOS 位置

  • pad_token_id:將長度補到 max_length
  • Padding:加入額外 tokens
  • 設為 generator.tokenizer.eos_token_id 代表有意義文字的結尾,模型於訓練中學得
  • 模型會生成到 max_length 或遇到 pad_token_id 為止
  • truncation = True
Python 的 LLM 入門

文字生成

generator = pipeline(task="text-generation", model="distilgpt2")

prompt = "The Gion neighborhood in Kyoto is famous for"

output = generator(prompt, max_length=100, pad_token_id=generator.tokenizer.eos_token_id)

print(output[0]["generated_text"])
The Gion neighborhood in Kyoto is famous for its many colorful green forests, such as the 
Red Hill, the Red River and the Red River. The Gion neighborhood is home to the world's 
tallest trees.
  • 若提示過於籠統,輸出可能不佳
Python 的 LLM 入門

引導輸出

generator = pipeline(task="text-generation", model="distilgpt2")


review = "This book was great. I enjoyed the plot twist in Chapter 10." response = "Dear reader, thank you for your review." prompt = f"Book review:\n{review}\n\nBook shop response to the review:\n{response}"
output = generator(prompt, max_length=100, pad_token_id=generator.tokenizer.eos_token_id) print(output[0]["generated_text"])
Dear reader, thank you for your review. We'd like to thank you for your reading!
Python 的 LLM 入門

語言翻譯

  • Hugging Face 有完整的翻譯任務與模型清單
translator = pipeline(task="translation_en_to_es", model="Helsinki-NLP/opus-mt-en-es")

text = "Walking amid Gion's Machiya wooden houses was a mesmerizing experience."
output = translator(text, clean_up_tokenization_spaces=True)
print(output[0]["translation_text"])
Caminar entre las casas de madera Machiya de Gion fue una experiencia fascinante.
Python 的 LLM 入門

一起來練習吧!

Python 的 LLM 入門

Preparing Video For Download...