>  기사  >  백엔드 개발  >  나는 Granite를 시험해 보았다.

나는 Granite를 시험해 보았다.

Susan Sarandon
Susan Sarandon원래의
2024-10-28 04:23:01602검색

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

실행

그래니트 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 모델임에도 비교적 강력한 반응성을 제공합니다. 함수 호출 및 형식 지정 기능도 매우 잘 작동하여 광범위한 응용 분야에 대한 잠재력을 나타냅니다.

위 내용은 나는 Granite를 시험해 보았다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.