LlamaをGoogle Colabから実行

はじめに

LLMを実行するためのサンプルコードです。
コードは下記にあります。
https://github.com/toshi-4886/LLM/blob/main/notebook/2_llama.ipynb

概要

  • Llamaの小型モデルを動かします。

  • 認証などについても説明します。

事前準備

  1. Hugging Faceのアカウント作成

  2. アクセストークンの作成
    Hugging Faceのアカウントにログインし、「自分のアイコン→Settings→Access Tokens→+ Create new token」からトークンを作成します。
    「Read access to contents of all public gated repos you can access」の権限が必要となります。

3.Llamaの利用申請
Hugging Faceで使用したいモデルのページにアクセスして、必要事項を記入して申請します。
申請が承認されると利用可能になります。

実装

1. ライブラリのインポート

import sys
import os

!pip install -U bitsandbytes
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
import torch

2. 認証

Hugging Faceからモデルをダウンロードするために、アカウント認証を行います。
login()を実行するとトークンを入力するUIが出てくるので、そこにトークンを入力します。

また、colabのシークレットにトークンを保存しておけば、それを利用することもできます。

from huggingface_hub import login
# login()

# シークレットにトークンを保存しておけば下記で認証可能
from google.colab import userdata
login(token=userdata.get('HF_TOKEN'))

3. モデルの準備

トークナイザーとモデルを準備します。
小型のモデルのため量子化せずに使用します。

tokenizer = AutoTokenizer.from_pretrained(
    "meta-llama/Llama-3.2-1B-Instruct",
)

model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.2-1B-Instruct",
    torch_dtype=torch.float16,
    device_map="auto",
    trust_remote_code=False,
)

4. 推論

プロンプトをモデルに入力して、得られた出力を表示します。

# 推論時間を計測
%%time

# プロンプトの準備
conversation = [{"role": "user", "content": "What's the weather like in Paris?"}]

# 推論の実行
with torch.no_grad():
    token_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True,
            return_dict=True, return_tensors="pt").to(model.device)
    output_ids = model.generate(
        **token_ids,
        pad_token_id=tokenizer.eos_token_id,
        temperature=0.1,
        do_sample=True,
        top_p=0.95,
        top_k=40,
        max_new_tokens=256,
    )
output = tokenizer.decode(output_ids[0], skip_special_tokens=True)
print(output)
system

Cutting Knowledge Date: December 2023
Today Date: 26 Jul 2024

user

What's the weather like in Paris?assistant

In Paris, the weather is typically mild and temperate, with four distinct seasons. Here's a breakdown of what you can expect:

- Spring (March to May): Spring in Paris is lovely, with mild temperatures ranging from 10°C (50°F) to 20°C (68°F). The days are getting longer, and the sun shines brightly, making it ideal for exploring the city's parks and gardens. However, it can still be quite chilly, especially in the mornings and evenings.
- Summer (June to August): Summer in Paris is warm and sunny, with average highs around 25°C (77°F) and lows around 15°C (59°F). It's a great time to visit the city's famous beaches, such as the Champs-Élysées and the Seine River. However, the heat can be intense, especially in July and August.
- Autumn (September to November): Autumn in Paris is lovely, with mild temperatures ranging from 10°C (50°F) to 20°C (68°F). The days are getting shorter, and the sun shines brightly, making it ideal for exploring the city's historic sites and museums. However, it can still be quite chilly, especially in the mornings and evenings.
- Winter (December
CPU times: user 5.32 s, sys: 163 µs, total: 5.32 s
Wall time: 5.34 s

おわりに

今回の結果

Llamaでプロンプトの回答を生成することができました。
一般的な天気を答えているので、ハルシネーションを防ぐための調整もされていることが確認できました。

次にやること

プロンプトの設定方法について様々な方法を試してみたいと思います。

参考資料

いいなと思ったら応援しよう!