亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

首頁 后端開發(fā) Python教程 我嘗試過花崗巖。

我嘗試過花崗巖。

Oct 28, 2024 am 04:23 AM

I tried out Granite .

花崗巖3.0

Granite 3.0 是一個開源、輕量級的生成語言模型系列,專為一系列企業(yè)級任務而設計。它原生支持多語言功能、編碼、推理和工具使用,適合企業(yè)環(huán)境。

我測試了運行這個模型,看看它可以處理哪些任務。

環(huán)境設置

我在 Google Colab 中設置了 Granite 3.0 環(huán)境,并使用以下命令安裝了必要的庫:

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

執(zhí)行

我測試了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型號

將2b替換為8b即可使用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

函數(shù)調用

我探索了函數(shù)調用功能,并使用虛擬函數(shù)對其進行了測試。這里,get_current_weather 被定義為返回模擬天氣數(shù)據(jù)。

虛擬函數(shù)

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

即時創(chuàng)作

我創(chuàng)建了一個調用該函數(shù)的提示:

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

這證實了模型能夠根據(jù)指定城市生成正確的函數(shù)調用。

增強交互流程的格式規(guī)范

Granite 3.0 允許格式規(guī)范以促進結構化格式的響應。本節(jié)解釋如何使用 [UTTERANCE] 進行回應,使用 [THINK] 進行內心想法。

另一方面,由于函數(shù)調用以純文本形式輸出,因此可能需要實現(xiàn)單獨的機制來區(qū)分函數(shù)調用和常規(guī)文本響應。

指定輸出格式

以下是指導 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>
"""

執(zhí)行代碼示例

生成響應的代碼:

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] 標簽已成功使用,允許有效的響應格式。

根據(jù)提示的不同,輸出中有時可能會出現(xiàn)結束標簽(例如[/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])

此示例演示了成功的流式傳輸。每個token都是異步生成并順序顯示,讓用戶可以實時查看生成過程。

概括

Granite 3.0 即使使用 8B 型號也能提供相當強的響應。函數(shù)調用和格式規(guī)范功能也運行良好,表明其具有廣泛的應用潛力。

以上是我嘗試過花崗巖。的詳細內容。更多信息請關注PHP中文網其他相關文章!

本站聲明
本文內容由網友自發(fā)貢獻,版權歸原作者所有,本站不承擔相應法律責任。如您發(fā)現(xiàn)有涉嫌抄襲侵權的內容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅動的應用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

Python類中的多態(tài)性 Python類中的多態(tài)性 Jul 05, 2025 am 02:58 AM

多態(tài)是Python面向對象編程中的核心概念,指“一種接口,多種實現(xiàn)”,允許統(tǒng)一處理不同類型的對象。1.多態(tài)通過方法重寫實現(xiàn),子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實現(xiàn)。2.多態(tài)的實際用途包括簡化代碼結構、增強可擴展性,例如圖形繪制程序中統(tǒng)一調用draw()方法,或游戲開發(fā)中處理不同角色的共同行為。3.Python實現(xiàn)多態(tài)需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對象實現(xiàn)相同方法即可,這稱為“鴨子類型”。4.注意事項包括保持方

Python函數(shù)參數(shù)和參數(shù) Python函數(shù)參數(shù)和參數(shù) Jul 04, 2025 am 03:26 AM

參數(shù)(parameters)是定義函數(shù)時的占位符,而傳參(arguments)是調用時傳入的具體值。1.位置參數(shù)需按順序傳遞,順序錯誤會導致結果錯誤;2.關鍵字參數(shù)通過參數(shù)名指定,可改變順序且提高可讀性;3.默認參數(shù)值在定義時賦值,避免重復代碼,但應避免使用可變對象作為默認值;4.args和*kwargs可處理不定數(shù)量的參數(shù),適用于通用接口或裝飾器,但應謹慎使用以保持可讀性。

解釋Python發(fā)電機和迭代器。 解釋Python發(fā)電機和迭代器。 Jul 05, 2025 am 02:55 AM

迭代器是實現(xiàn)__iter__()和__next__()方法的對象,生成器是簡化版的迭代器,通過yield關鍵字自動實現(xiàn)這些方法。1.迭代器每次調用next()返回一個元素,無更多元素時拋出StopIteration異常。2.生成器通過函數(shù)定義,使用yield按需生成數(shù)據(jù),節(jié)省內存且支持無限序列。3.處理已有集合時用迭代器,動態(tài)生成大數(shù)據(jù)或需惰性求值時用生成器,如讀取大文件時逐行加載。注意:列表等可迭代對象不是迭代器,迭代器到盡頭后需重新創(chuàng)建,生成器只能遍歷一次。

python`@classmethod'裝飾師解釋了 python`@classmethod'裝飾師解釋了 Jul 04, 2025 am 03:26 AM

類方法是Python中通過@classmethod裝飾器定義的方法,其第一個參數(shù)為類本身(cls),用于訪問或修改類狀態(tài)。它可通過類或實例調用,影響的是整個類而非特定實例;例如在Person類中,show_count()方法統(tǒng)計創(chuàng)建的對象數(shù)量;定義類方法時需使用@classmethod裝飾器并將首參命名為cls,如change_var(new_value)方法可修改類變量;類方法與實例方法(self參數(shù))、靜態(tài)方法(無自動參數(shù))不同,適用于工廠方法、替代構造函數(shù)及管理類變量等場景;常見用途包括從

如何處理Python中的API身份驗證 如何處理Python中的API身份驗證 Jul 13, 2025 am 02:22 AM

處理API認證的關鍵在于理解并正確使用認證方式。1.APIKey是最簡單的認證方式,通常放在請求頭或URL參數(shù)中;2.BasicAuth使用用戶名和密碼進行Base64編碼傳輸,適合內部系統(tǒng);3.OAuth2需先通過client_id和client_secret獲取Token,再在請求頭中帶上BearerToken;4.為應對Token過期,可封裝Token管理類自動刷新Token;總之,根據(jù)文檔選擇合適方式,并安全存儲密鑰信息是關鍵。

什么是python魔法方法或dunder方法? 什么是python魔法方法或dunder方法? Jul 04, 2025 am 03:20 AM

Python的magicmethods(或稱dunder方法)是用于定義對象行為的特殊方法,它們以雙下劃線開頭和結尾。1.它們使對象能夠響應內置操作,如加法、比較、字符串表示等;2.常見用例包括對象初始化與表示(__init__、__repr__、__str__)、算術運算(__add__、__sub__、__mul__)及比較運算(__eq__、__lt__);3.使用時應確保其行為符合預期,例如__repr__應返回可重構對象的表達式,算術方法應返回新實例;4.應避免過度使用或以令人困惑的方

Python內存管理如何工作? Python內存管理如何工作? Jul 04, 2025 am 03:26 AM

Pythonmanagesmemoryautomaticallyusingreferencecountingandagarbagecollector.Referencecountingtrackshowmanyvariablesrefertoanobject,andwhenthecountreacheszero,thememoryisfreed.However,itcannothandlecircularreferences,wheretwoobjectsrefertoeachotherbuta

python`@property`裝飾師 python`@property`裝飾師 Jul 04, 2025 am 03:28 AM

@property是Python中用于將方法偽裝成屬性的裝飾器,允許在訪問屬性時執(zhí)行邏輯判斷或動態(tài)計算值。1.它通過@property裝飾器定義getter方法,使外部像訪問屬性一樣調用方法;2.搭配.setter可控制賦值行為,如校驗值合法性,不定義.setter則為只讀屬性;3.適用于屬性賦值校驗、動態(tài)生成屬性值、隱藏內部實現(xiàn)細節(jié)等場景;4.使用時注意屬性名與私有變量名不同名,避免死循環(huán),適合輕量級操作;5.示例中Circle類限制radius非負,Person類動態(tài)生成full_name屬

See all articles