찾다
백엔드 개발파이썬 튜토리얼나는 Granite를 시험해 보았다.

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

산출

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.
<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으로 문의하세요.
Python의 병합 목록 : 올바른 메소드 선택Python의 병합 목록 : 올바른 메소드 선택May 14, 2025 am 12:11 AM

Tomergelistsinpython, youcanusethe operator, extendmethod, listcomprehension, oritertools.chain, 각각은 각각의 지위를 불러 일으킨다

Python 3에서 두 목록을 연결하는 방법은 무엇입니까?Python 3에서 두 목록을 연결하는 방법은 무엇입니까?May 14, 2025 am 12:09 AM

Python 3에서는 다양한 방법을 통해 두 개의 목록을 연결할 수 있습니다. 1) 작은 목록에 적합하지만 큰 목록에는 비효율적입니다. 2) 메모리 효율이 높지만 원래 목록을 수정하는 큰 목록에 적합한 확장 방법을 사용합니다. 3) 원래 목록을 수정하지 않고 여러 목록을 병합하는 데 적합한 * 운영자 사용; 4) 메모리 효율이 높은 대형 데이터 세트에 적합한 itertools.chain을 사용하십시오.

Python은 문자열을 연결합니다Python은 문자열을 연결합니다May 14, 2025 am 12:08 AM

join () 메소드를 사용하는 것은 Python의 목록에서 문자열을 연결하는 가장 효율적인 방법입니다. 1) join () 메소드를 사용하여 효율적이고 읽기 쉽습니다. 2)주기는 큰 목록에 비효율적으로 운영자를 사용합니다. 3) List Comprehension과 Join ()의 조합은 변환이 필요한 시나리오에 적합합니다. 4) READE () 방법은 다른 유형의 감소에 적합하지만 문자열 연결에 비효율적입니다. 완전한 문장은 끝납니다.

파이썬 실행, 그게 뭐야?파이썬 실행, 그게 뭐야?May 14, 2025 am 12:06 AM

pythonexecutionissprocessoftransformingpythoncodeintoExecutableInstructions.1) the -interreadsTheCode, ConvertingItintoByTecode, thethepythonVirtualMachine (pvm)을 실행합니다

파이썬 : 주요 기능은 무엇입니까?파이썬 : 주요 기능은 무엇입니까?May 14, 2025 am 12:02 AM

Python의 주요 특징은 다음과 같습니다. 1. 구문은 간결하고 이해하기 쉽고 초보자에게 적합합니다. 2. 개발 속도 향상, 동적 유형 시스템; 3. 여러 작업을 지원하는 풍부한 표준 라이브러리; 4. 광범위한 지원을 제공하는 강력한 지역 사회와 생태계; 5. 스크립팅 및 빠른 프로토 타이핑에 적합한 해석; 6. 다양한 프로그래밍 스타일에 적합한 다중-파라 디그 지원.

파이썬 : 컴파일러 또는 통역사?파이썬 : 컴파일러 또는 통역사?May 13, 2025 am 12:10 AM

Python은 해석 된 언어이지만 편집 프로세스도 포함됩니다. 1) 파이썬 코드는 먼저 바이트 코드로 컴파일됩니다. 2) 바이트 코드는 Python Virtual Machine에 의해 해석되고 실행됩니다. 3)이 하이브리드 메커니즘은 파이썬이 유연하고 효율적이지만 완전히 편집 된 언어만큼 빠르지는 않습니다.

루프 대 루프를위한 파이썬 : 루프시기는 언제 사용해야합니까?루프 대 루프를위한 파이썬 : 루프시기는 언제 사용해야합니까?May 13, 2025 am 12:07 AM

USEAFORLOOPHENTERATINGOVERASERASERASPECIFICNUMBEROFTIMES; USEAWHILLOOPWHENTINUTIMONDITINISMET.FORLOOPSAREIDEALFORKNOWNSEDINGENCENCENS, WHILEWHILELOOPSSUITSITUATIONS WITHERMINGEDERITERATIONS.

파이썬 루프 : 가장 일반적인 오류파이썬 루프 : 가장 일반적인 오류May 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrors likeinfiniteloops, modifyinglistsdizeration, off-by-by-byerrors, zero-indexingissues, andnestedloopineficiencies.toavoidthese : 1) aing'i

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구