ホームページ  >  記事  >  バックエンド開発  >  グラナイトを試してみました。

グラナイトを試してみました。

Susan Sarandon
Susan Sarandonオリジナル
2024-10-28 04:23:01601ブラウズ

I tried out Granite .

花崗岩 3.0

Granite 3.0 は、エンタープライズレベルのさまざまなタスク向けに設計された、オープンソースの軽量の生成言語モデル ファミリです。多言語機能、コーディング、推論、ツールの使用をネイティブにサポートしているため、エンタープライズ環境に適しています。

このモデルを実行して、どのようなタスクを処理できるかを確認しました。

環境設定

Google Colab で Granite 3.0 環境をセットアップし、次のコマンドを使用して必要なライブラリをインストールしました。

!pip install torch torchvision torchaudio
!pip install accelerate
!pip install -U transformers

実行

Granite 3.0 の 2B モデルと 8B モデルの両方のパフォーマンスをテストしました。

2Bモデル

私は 2B モデルを実行しました。 2B モデルのコードサンプルは次のとおりです:

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

device = "auto"
model_path = "ibm-granite/granite-3.0-2b-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()

chat = [
    { "role": "user", "content": "Please list one IBM Research laboratory located in the United States. You should only output its name and location." },
]
chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
input_tokens = tokenizer(chat, return_tensors="pt").to("cuda")
output = model.generate(**input_tokens, max_new_tokens=100)
output = tokenizer.batch_decode(output)
print(output[0])

出力

<|start_of_role|>user<|end_of_role|>Please list one IBM Research laboratory located in the United States. You should only output its name and location.<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>1. IBM Research - Austin, Texas<|end_of_text|>

8Bモデル

8Bモデルは2bを8bに置き換えて使用できます。以下は、8B モデルのロールとユーザー入力フィールドのないコード サンプルです:

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

device = "auto"
model_path = "ibm-granite/granite-3.0-8b-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()

chat = [
    { "content": "Please list one IBM Research laboratory located in the United States. You should only output its name and location." },
]
chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)

input_tokens = tokenizer(chat, add_special_tokens=False, return_tensors="pt").to("cuda")
output = model.generate(**input_tokens, max_new_tokens=100)
generated_text = tokenizer.decode(output[0][input_tokens["input_ids"].shape[1]:], skip_special_tokens=True)
print(generated_text)

出力

1. IBM Almaden Research Center - San Jose, California

関数呼び出し

私は関数呼び出し機能を調査し、ダミー関数を使用してテストしました。ここで、get_current_weather は模擬天気データを返すように定義されています。

ダミー関数

import json

def get_current_weather(location: str) -> dict:
    """
    Retrieves current weather information for the specified location (default: San Francisco).
    Args:
        location (str): Name of the city to retrieve weather data for.
    Returns:
        dict: Dictionary containing weather information (temperature, description, humidity).
    """
    print(f"Getting current weather for {location}")

    try:
        weather_description = "sample"
        temperature = "20.0"
        humidity = "80.0"

        return {
            "description": weather_description,
            "temperature": temperature,
            "humidity": humidity
        }
    except Exception as e:
        print(f"Error fetching weather data: {e}")
        return {"weather": "NA"}

プロンプト作成

関数を呼び出すためのプロンプトを作成しました:

functions = [
    {
        "name": "get_current_weather",
        "description": "Get the current weather",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and country code, e.g. San Francisco, US",
                }
            },
            "required": ["location"],
        },
    },
]
query = "What's the weather like in Boston?"
payload = {
    "functions_str": [json.dumps(x) for x in functions]
}
chat = [
    {"role":"system","content": f"You are a helpful assistant with access to the following function calls. Your task is to produce a sequence of function calls necessary to generate response to the user utterance. Use the following function calls as required.{payload}"},
    {"role": "user", "content": query }
]

応答の生成

次のコードを使用して、応答を生成しました:

instruction_1 = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
input_tokens = tokenizer(instruction_1, return_tensors="pt").to("cuda")
output = model.generate(**input_tokens, max_new_tokens=1024)
generated_text = tokenizer.decode(output[0][input_tokens["input_ids"].shape[1]:], skip_special_tokens=True)
print(generated_text)

出力

{'name': 'get_current_weather', 'arguments': {'location': 'Boston'}}

これにより、モデルが指定された都市に基づいて正しい関数呼び出しを生成できることが確認されました。

強化されたインタラクション フローのためのフォーマット仕様

Granite 3.0 では、構造化フォーマットでの応答を容易にするフォーマット指定が可能です。ここでは、応答には[UTTERANCE]、内なる思考には[THINK]を使用して説明します。

一方、関数呼び出しはプレーンテキストとして出力されるため、関数呼び出しと通常のテキスト応答を区別するための別のメカニズムを実装する必要がある場合があります。

出力形式の指定

AI の出力をガイドするためのサンプル プロンプトは次のとおりです。

prompt = """You are a conversational AI assistant that deepens interactions by alternating between responses and inner thoughts.
<Constraints>
* Record spoken responses after the [UTTERANCE] tag and inner thoughts after the [THINK] tag.
* Use [UTTERANCE] as a start marker to begin outputting an utterance.
* After [THINK], describe your internal reasoning or strategy for the next response. This may include insights on the user's reaction, adjustments to improve interaction, or further goals to deepen the conversation.
* Important: **Use [UTTERANCE] and [THINK] as a start signal without needing a closing tag.**
</Constraints>

Follow these instructions, alternating between [UTTERANCE] and [THINK] formats for responses.
<output example>
example1:
  [UTTERANCE]Hello! How can I assist you today?[THINK]I’ll start with a neutral tone to understand their needs. Preparing to offer specific suggestions based on their response.[UTTERANCE]Thank you! In that case, I have a few methods I can suggest![THINK]Since I now know what they’re looking for, I'll move on to specific suggestions, maintaining a friendly and approachable tone.
...
</output example>

Please respond to the following user_input.
<user_input>
Hello! What can you do?
</user_input>
"""

実行コード例

応答を生成するコード:

chat = [
    { "role": "user", "content": prompt },
]
chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)

input_tokens = tokenizer(chat, return_tensors="pt").to("cuda")
output = model.generate(**input_tokens, max_new_tokens=1024)
generated_text = tokenizer.decode(output[0][input_tokens["input_ids"].shape[1]:], skip_special_tokens=True)
print(generated_text)

出力例

出力は次のとおりです:

[UTTERANCE]Hello! I'm here to provide information, answer questions, and assist with various tasks. I can help with a wide range of topics, from general knowledge to specific queries. How can I assist you today?
[THINK]I've introduced my capabilities and offered assistance, setting the stage for the user to share their needs or ask questions.

[UTTERANCE] タグと [THINK] タグが正常に使用され、効果的な応答フォーマットが可能になりました。

プロンプトによっては、終了タグ ([/UTTERANCE] や [/THINK] など) が出力に表示される場合がありますが、全体的には、出力形式は通常正常に指定できます。

ストリーミング コードの例

ストリーミング応答を出力する方法についても見てみましょう。

次のコードは、asyncio ライブラリとスレッド ライブラリを使用して、Granite 3.0 からの応答を非同期的にストリーミングします。

!pip install torch torchvision torchaudio
!pip install accelerate
!pip install -U transformers

出力例

上記のコードを実行すると、次の形式で非同期応答が生成されます:

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

device = "auto"
model_path = "ibm-granite/granite-3.0-2b-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
model.eval()

chat = [
    { "role": "user", "content": "Please list one IBM Research laboratory located in the United States. You should only output its name and location." },
]
chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
input_tokens = tokenizer(chat, return_tensors="pt").to("cuda")
output = model.generate(**input_tokens, max_new_tokens=100)
output = tokenizer.batch_decode(output)
print(output[0])

この例では、ストリーミングが成功する例を示します。各トークンは非同期で生成され、順番に表示されるため、ユーザーは生成プロセスをリアルタイムで確認できます。

まとめ

Granite 3.0 は 8B モデルでも適度に強いレスポンスを提供します。関数呼び出し機能とフォーマット仕様機能も非常にうまく動作し、幅広いアプリケーションへの可能性を示しています。

以上がグラナイトを試してみました。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。