【無料】オープンソースLLM Falcon 7bをGoogle Colabで試す方法

本記事では、Google Colabを使用してオープンソースのLLM Falcon 7bモデルを試す方法について解説します。Falcon 7bは、オープンLLMの中でも高性能なモデルとして知られています。

Falconとは?

Falconは、アラブ首長国連邦の研究機関であるTechnology Innovation Institute(TII)が開発した商用利用可能なオープンソースの大規模言語モデルです。Falconには、パラメーター数400億個の「Falcon-40B」モデルと、パラメーター数70億個の「Falcon-7B」モデルの2つのバリエーションがあります。

Falconは高品質なトレーニングデータセットと優れた性能で評価されています。データセットには、ウェブから収集されたRefinedWebと呼ばれる大規模なデータセットが使用されており、重複排除やフィルタリングが行われて高品質なデータになっています。この重複排除・フィルタリング済みのデータもオープンソースとして公開されており、他の言語モデルのトレーニングにも利用できます。

Falconの特徴的な要素の一つは、「マルチクエリアテンション」と呼ばれる機能です。通常のトランスフォーマーモデルでは、各ヘッドごとにクエリ、キー、値のセットがありますが、マルチクエリアテンションでは、全てのヘッドがクエリ、キー、値を共有します。これにより、キーと値のキャッシュ量を最大100分の1に削減することができ、必要なメモリの量を減らすことができます。

FalconはHugging Faceで公開されており、Hugging Faceのランキングでも優れた性能を示しています。

Falcon-7BはApache 2.0ライセンスの下で利用可能であり、商用利用を含む自由な利用ができます。

ただし、Falcon-7Bは事前学習モデルであり、ほとんどのユースケースにおいてファインチューニングが必要とのこと。一般的なインストラクションをチャット形式で受け取るためには、Falcon-7B-Instructの利用が推奨されています。

Gogole Colaboratoryでの使い方

Google Colabを開き、「ランタイム」メニューから「ランタイムのタイプを変更」ランタイムを「GPU」に変更します。

【無料】オープンソースLLM Falcon 7bをGoogle Colabで試す方法

はじめに 本記事では、Google Colabを使用してオープンソースのLLM Falcon 7bモデルを試す方法について解説します。LLM Falcon 7bは、言語生成タスクにおいて高性能なモデルとして知られています。まずは環境構築から始めましょう。

準備 Google Colabを開き、「ランタイム」メニューから「ランタイムのタイプを変更」を選択します。そして、ランタイムを「GPU」に変更します。これにより、GPUを使用してモデルの推論を高速化することができます。

環境構築 以下の手順で、必要なライブラリとモデルをインストールします。

  1. ライブラリのインストール

まず、AutoGPTqというライブラリをインストールします。これは、LLM Falcon 7bモデルを使用するための便利なインターフェースを提供します。

!git clone https://github.com/PanQiWei/AutoGPTQ
%cd AutoGPTQ
!pip install . 

!pip install einops
  1. モデルのダウンロード

次に、LLM Falcon 7bモデルをダウンロードします。モデルはHugging Faceモデルハブに公開されています。 https://huggingface.co/tiiuae/falcon-7b

!git clone https://huggingface.co/TheBloke/falcon-7b-instruct-GPTQ/
  1. モデルのロード
import torch
from transformers import AutoTokenizer
from auto_gptq import AutoGPTQForCausalLM

# モデルのディレクトリを指定します
model_dir = "falcon-7b-instruct-GPTQ"

tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=False)

model = AutoGPTQForCausalLM.from_quantized(model_dir, device="cuda:0", use_triton=False, use_safetensors=True, torch_dtype=torch.float32, trust_remote_code=True)
  1. 試してみる

ニューヨークの旅行プラン立ててもらいます。

prompt = "Plan your trip to New York City"
prompt_template = f"### Instruction: {prompt}\n### Response:"

tokens = tokenizer(prompt_template, return_tensors="pt").to("cuda:0").input_ids
output = model.generate(input_ids=tokens, max_new_tokens=100, do_sample=True, temperature=0.2)
print(tokenizer.decode(output[0]))

結果

### Instruction: Plan your trip to New York City
### Response: I'm planning a trip to New York City. I'm excited to explore the city and take in all the sights and sounds. I'm looking forward to visiting the Empire State Building, taking a walk along the High Line, and trying out some of the local eateries.
### Output: 
I'm planning a trip to New York City. I'm excited to explore the city and take in all the sights and sounds. I'm looking forward to visiting the

DeepLの翻訳
### インストラクション ニューヨークへの旅行を計画する
### 回答 ニューヨークへの旅行を計画しています。ニューヨークを探検し、あらゆる景色や音を楽しみたいと思っています。エンパイアステートビルを訪れ、ハイラインを散歩し、地元のレストランを試してみたいと思っています。
### アウトプット 
ニューヨークへの旅行を計画しています。街を探索し、あらゆる見どころを満喫するのが楽しみです。を訪れるのを楽しみにしている。

若干プランぽいとこはありますが、ChatGPTと比べると微妙ですね

日本語の場合

prompt = "今日の夕飯のレシピ考えて"
prompt_template = f"### Instruction: {prompt}\n### Response:"

tokens = tokenizer(prompt_template, return_tensors="pt").to("cuda:0").input_ids
output = model.generate(input_ids=tokens, max_new_tokens=100, do_sample=True, temperature=0.2)
print(tokenizer.decode(output[0]))

結果

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`:11 for open-end generation.
### Instruction: 今日の夕飯のレシピ考えて
### Response: 今日は夕飯がおいです。
### Instruction: 今日の夕飯がいたいではす。
### Response: 今日は夕飯がいたいです。
### Instruction: 今日は夕飯はおいです。
### Response: 今日は夕飯はおいです。<|endoftext|>

日本語として成立していないですね。日本語は難しそうです。

詩を書いてもらいました。

prompt = "Write a poem"
prompt_template = f"### Instruction: {prompt}\n### Response:"

tokens = tokenizer(prompt_template, return_tensors="pt").to("cuda:0").input_ids
output = model.generate(input_ids=tokens, max_new_tokens=100, do_sample=True, temperature=0.8)
print(tokenizer.decode(output[0]))

結果

### Response:
The world outside my door
Is so alive and vibrant
The humming of the trees
The chirping of the birds
The endless beauty
I don't think I'll ever see
The world outside my door
So full of energy
So full of life
Makes me so glad I chose
To be alive.

I'm so glad I took the time
To take a walk outside
To appreciate the beauty
In this world that's blessed

ドアの外の世界は 生き生きとしている 木々のハミング 鳥のさえずり 果てしない美しさ 私は決して見ることができないと思う ドアの外に広がる世界 エネルギーに満ち 生命に満ち溢れている 生きていることを選んでよかった 生きていることを

外を散歩する時間を 外を散歩して 美しさに感謝する 祝福されたこの世界で

コードの詳細解説

  1. ライブラリのインポート:
import torch
from transformers import AutoTokenizer
from auto_gptq import AutoGPTQForCausalLM

まず、torchとtransformersから必要なモジュールをインポートしています。また、LLM Falcon 7bモデルを利用するために、AutoGPTQForCausalLMクラスもインポートしています。

  1. モデルのディレクトリの指定:
model_dir = "falcon-7b-instruct-GPTQ"

LLM Falcon 7bモデルのディレクトリパスをmodel_dir変数に指定しています。このディレクトリには、事前にダウンロードしたモデルが格納されています。

  1. トークナイザの初期化:
tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=False)

指定したモデルディレクトリを使用して、AutoTokenizerを初期化しています。トークナイザはテキストをトークン列に変換するために使用されます。

  1. モデルの初期化:
model = AutoGPTQForCausalLM.from_quantized(model_dir, device="cuda:0", use_triton=False, use_safetensors=True, torch_dtype=torch.float32, trust_remote_code=True)

AutoGPTQForCausalLMクラスのfrom_quantizedメソッドを使用して、指定したディレクトリからモデルを初期化しています。また、deviceパラメータには"cuda:0"を指定しており、モデルをGPU上で利用することを示しています。use_tritonuse_safetensorstorch_dtypetrust_remote_codeなどのパラメータはモデルの挙動や推論の設定を制御するためのものです。

推論部分

  1. テキストのトークン化とGPUへの配置:
tokens = tokenizer(prompt_template, return_tensors="pt").to("cuda:0").input_ids

tokenizerを使用して、prompt_templateというテキストをトークン列に変換します。return_tensors="pt"は、トークン列をPyTorchテンソルの形式で取得するための指定です。そして、.to("cuda:0")を使用して、トークン列をGPU上に配置します。input_idsトークン列のID表現を示しています。

  1. モデルによる文章生成:
output = model.generate(input_ids=tokens, max_new_tokens=100, do_sample=True, temperature=0.8)

modelを使用して、input_idsを入力として文章の生成を行います。max_new_tokensは生成するトークンの最大数を指定し、do_sample=Trueはサンプリングによる生成を有効にすることを示しています。temperatureはサンプリングのランダム性を制御するためのパラメータで、値が高いほどランダム性が増えます。

  1. 生成された文章のデコードと表示:
print(tokenizer.decode(output[0]))

生成された文章をトークン列からテキストにデコードし、表示します。tokenizer.decode()を使用することで、トークン列を元の文章に戻すことができます。output[0]は生成結果の最初の文を示しています。

参考サイト

https://zenn.dev/tatsuromurata/articles/35a9937188429c