Heim  >  Artikel  >  Backend-Entwicklung  >  Ich habe Granite ausprobiert.

Ich habe Granite ausprobiert.

Susan Sarandon
Susan SarandonOriginal
2024-10-28 04:23:01602Durchsuche

I tried out Granite .

Granit 3.0

Granite 3.0 ist eine Open-Source-Familie generativer Sprachmodelle, die für eine Reihe von Aufgaben auf Unternehmensebene entwickelt wurde. Es unterstützt nativ mehrsprachige Funktionalität, Codierung, Argumentation und Tool-Nutzung und ist somit für Unternehmensumgebungen geeignet.

Ich habe dieses Modell getestet, um zu sehen, welche Aufgaben es bewältigen kann.

Umgebungseinrichtung

Ich habe die Granite 3.0-Umgebung in Google Colab eingerichtet und die erforderlichen Bibliotheken mit den folgenden Befehlen installiert:

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

Ausführung

Ich habe die Leistung der 2B- und 8B-Modelle von Granite 3.0 getestet.

2B-Modell

Ich habe das 2B-Modell verwendet. Hier ist das Codebeispiel für das 2B-Modell:

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])

Ausgabe

<|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-Modell

Das 8B-Modell kann verwendet werden, indem 2b durch 8b ersetzt wird. Hier ist ein Codebeispiel ohne Rollen- und Benutzereingabefelder für das 8B-Modell:

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)

Ausgabe

1. IBM Almaden Research Center - San Jose, California

Funktionsaufruf

Ich habe die Funktionsaufruffunktion erkundet und sie mit einer Dummy-Funktion getestet. Hier ist get_current_weather so definiert, dass Scheinwetterdaten zurückgegeben werden.

Dummy-Funktion

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"}

Schnelle Erstellung

Ich habe eine Eingabeaufforderung zum Aufrufen der Funktion erstellt:

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 }
]

Antwortgenerierung

Mit dem folgenden Code habe ich eine Antwort generiert:

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)

Ausgabe

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

Dies bestätigte die Fähigkeit des Modells, den richtigen Funktionsaufruf basierend auf der angegebenen Stadt zu generieren.

Formatspezifikation für erweiterten Interaktionsfluss

Granite 3.0 ermöglicht die Formatspezifikation, um Antworten in strukturierten Formaten zu erleichtern. In diesem Abschnitt wird erklärt, wie man [AUßERUNG] für Antworten und [DENKEN] für innere Gedanken verwendet.

Da Funktionsaufrufe andererseits als Klartext ausgegeben werden, kann es erforderlich sein, einen separaten Mechanismus zu implementieren, um zwischen Funktionsaufrufen und regulären Textantworten zu unterscheiden.

Ausgabeformat angeben

Hier ist eine Beispielaufforderung zur Steuerung der KI-Ausgabe:

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>
"""

Beispiel für einen Ausführungscode

der Code zum Generieren einer Antwort:

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)

Beispielausgabe

Die Ausgabe ist wie folgt:

[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.

Die Tags [UTTERANCE] und [THINK] wurden erfolgreich verwendet und ermöglichen eine effektive Antwortformatierung.

Abhängig von der Eingabeaufforderung können manchmal schließende Tags (wie [/UTTERANCE] oder [/THINK]) in der Ausgabe erscheinen, aber insgesamt kann das Ausgabeformat im Allgemeinen erfolgreich angegeben werden.

Beispiel für Streaming-Code

Sehen wir uns auch an, wie man Streaming-Antworten ausgibt.

Der folgende Code verwendet die Asyncio- und Threading-Bibliotheken, um Antworten von Granite 3.0 asynchron zu streamen.

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

Beispielausgabe

Durch Ausführen des obigen Codes werden asynchrone Antworten im folgenden Format generiert:

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])

Dieses Beispiel zeigt erfolgreiches Streaming. Jeder Token wird asynchron generiert und nacheinander angezeigt, sodass Benutzer den Generierungsprozess in Echtzeit verfolgen können.

Zusammenfassung

Granite 3.0 liefert selbst mit dem 8B-Modell einigermaßen starke Reaktionen. Die Funktionen „Funktionsaufruf“ und „Formatspezifikation“ funktionieren ebenfalls recht gut, was auf ihr Potenzial für eine Vielzahl von Anwendungen hinweist.

Das obige ist der detaillierte Inhalt vonIch habe Granite ausprobiert.. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn