"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 나는 Granite를 시험해 보았다.

나는 Granite를 시험해 보았다.

2024-11-08에 게시됨
검색:988

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

산출

userPlease list one IBM Research laboratory located in the United States. You should only output its name and location.
assistant1. IBM Research - Austin, Texas

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.

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


Follow these instructions, alternating between [UTTERANCE] and [THINK] formats for responses.

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

Please respond to the following user_input.

Hello! What can you do?

"""

실행 코드 예

응답을 생성하는 코드:

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의 응답을 비동기적으로 스트리밍합니다.

import asyncio
from threading import Thread
from typing import AsyncIterator
from transformers import (
    AutoTokenizer,
    AutoModelForCausalLM,
    TextIteratorStreamer,
)

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

async def generate(chat) -> AsyncIterator[str]:
    # Apply chat template and tokenize input
    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")

    # Set up the streamer
    streamer = TextIteratorStreamer(
        tokenizer,
        skip_prompt=True,
        skip_special_tokens=True,
    )
    generation_kwargs = dict(
        **input_tokens,
        streamer=streamer,
        max_new_tokens=1024,
    )
    # Generate response in a separate thread
    thread = Thread(target=model.generate, kwargs=generation_kwargs)
    thread.start()

    for output in streamer:
        if not output:
            continue
        await asyncio.sleep(0)
        yield output

# Execute asynchronous generation in the main function
async def main():
    chat = [
        { "role": "user", "content": "Please list one IBM Research laboratory located in the United States. You should only output its name and location." },
    ]
    generator = generate(chat)
    async for output in generator:  # Use async for to retrieve responses sequentially
        print(output, end="|")

await main()

예제 출력

위 코드를 실행하면 다음 형식의 비동기 응답이 생성됩니다.

1. |IBM |Almaden |Research |Center |- |San |Jose, |California|

이 예는 성공적인 스트리밍을 보여줍니다. 각 토큰은 비동기적으로 생성되어 순차적으로 표시되므로 사용자는 생성 과정을 실시간으로 볼 수 있습니다.

요약

Granite 3.0은 8B 모델에서도 상당히 강력한 반응성을 제공합니다. 함수 호출 및 형식 사양 기능도 매우 잘 작동하여 광범위한 응용 프로그램에 대한 잠재력을 나타냅니다.

릴리스 선언문 이 글은 https://dev.to/m_sea_bass/i-tried-out-granite-30-53lm?1에서 복제되었습니다.1 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3