使用推理端點快速部署 MusicGen

釋出於 2023 年 8 月 4 日
在 GitHub 上更新

MusicGen 是一個強大的音樂生成模型,它接收文字提示和可選旋律來輸出音樂。這篇博文將指導您如何使用 推理端點 透過 MusicGen 生成音樂。

推理端點允許我們編寫名為 自定義處理程式 的自定義推理函式。當模型不被 `transformers` 高階抽象 `pipeline` 開箱即用地支援時,這些函式特別有用。

`transformers` pipelines 提供了強大的抽象功能,可以執行基於 `transformers` 的模型進行推理。推理端點利用 pipeline API,只需點選幾下即可輕鬆部署模型。然而,推理端點也可以用於部署沒有 pipeline 的模型,甚至是非 Transformer 模型!這是透過我們稱之為 自定義處理程式 的自定義推理函式實現的。

讓我們以 MusicGen 為例演示這個過程。要為 MusicGen 實現自定義處理函式並部署它,我們需要:

  1. 複製我們要服務的 MusicGen 倉庫,
  2. 在 `handler.py` 中編寫自定義處理程式,在 `requirements.txt` 中編寫所有依賴項,並將它們新增到複製的倉庫中,
  3. 為該倉庫建立推理端點。

或者,您也可以直接使用最終結果並部署我們的 自定義 MusicGen 模型倉庫,我們剛剛按照上述步驟操作了 :)

開始吧!

首先,我們將使用倉庫複製器facebook/musicgen-large 倉庫複製到我們自己的配置檔案中。

然後,我們將 `handler.py` 和 `requirements.txt` 新增到複製的倉庫中。首先,讓我們看看如何使用 MusicGen 執行推理。

from transformers import AutoProcessor, MusicgenForConditionalGeneration

processor = AutoProcessor.from_pretrained("facebook/musicgen-large")
model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-large")

inputs = processor(
    text=["80s pop track with bassy drums and synth"],
    padding=True,
    return_tensors="pt",
)
audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=256)

讓我們聽聽它聽起來怎麼樣

您可以選擇性地使用音訊片段來調整輸出,即生成一個結合文字生成的音訊與輸入音訊的補充片段。

from transformers import AutoProcessor, MusicgenForConditionalGeneration
from datasets import load_dataset

processor = AutoProcessor.from_pretrained("facebook/musicgen-large")
model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-large")

dataset = load_dataset("sanchit-gandhi/gtzan", split="train", streaming=True)
sample = next(iter(dataset))["audio"]

# take the first half of the audio sample
sample["array"] = sample["array"][: len(sample["array"]) // 2]

inputs = processor(
    audio=sample["array"],
    sampling_rate=sample["sampling_rate"],
    text=["80s blues track with groovy saxophone"],
    padding=True,
    return_tensors="pt",
)
audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=256)

讓我們聽聽看

在這兩種情況下,`model.generate` 方法都會生成音訊,並遵循與文字生成相同的原理。您可以在我們的如何生成部落格文章中閱讀更多相關內容。

好的!有了上面概述的基本用法,讓我們部署 MusicGen,既能娛樂又能盈利!

首先,我們將在 `handler.py` 中定義一個自定義處理程式。我們可以使用 Inference Endpoints 模板並用我們自定義的推理程式碼覆蓋 `__init__` 和 `__call__` 方法。`__init__` 將初始化模型和處理器,而 `__call__` 將接收資料並返回生成的音樂。您可以在下方找到修改後的 `EndpointHandler` 類。👇

from typing import Dict, List, Any
from transformers import AutoProcessor, MusicgenForConditionalGeneration
import torch

class EndpointHandler:
    def __init__(self, path=""):
        # load model and processor from path
        self.processor = AutoProcessor.from_pretrained(path)
        self.model = MusicgenForConditionalGeneration.from_pretrained(path, torch_dtype=torch.float16).to("cuda")

    def __call__(self, data: Dict[str, Any]) -> Dict[str, str]:
        """
        Args:
            data (:dict:):
                The payload with the text prompt and generation parameters.
        """
        # process input
        inputs = data.pop("inputs", data)
        parameters = data.pop("parameters", None)

        # preprocess
        inputs = self.processor(
            text=[inputs],
            padding=True,
            return_tensors="pt",).to("cuda")

        # pass inputs with all kwargs in data
        if parameters is not None:
            with torch.autocast("cuda"):
                outputs = self.model.generate(**inputs, **parameters)
        else:
            with torch.autocast("cuda"):
                outputs = self.model.generate(**inputs,)

        # postprocess the prediction
        prediction = outputs[0].cpu().numpy().tolist()

        return [{"generated_audio": prediction}]

為了簡單起見,在這個例子中,我們只從文字生成音訊,而不使用旋律進行條件化。接下來,我們將建立一個 `requirements.txt` 檔案,其中包含執行推理程式碼所需的所有依賴項。

transformers==4.31.0
accelerate>=0.20.3

將這兩個檔案上傳到我們的倉庫就足以提供模型服務。

inference-files

我們現在可以建立推理端點。前往 推理端點 頁面並點選 部署您的第一個模型。在“模型倉庫”欄位中,輸入您複製的倉庫的識別符號。然後選擇所需的硬體並建立端點。任何至少擁有 16 GB RAM 的例項都應該適用於 musicgen-large

Create Endpoint

建立端點後,它將自動啟動並準備好接收請求。

Endpoint Running

我們可以使用下面的程式碼片段查詢端點。

curl URL_OF_ENDPOINT \
-X POST \
-d '{"inputs":"happy folk song, cheerful and lively"}' \
-H "Authorization: {YOUR_TOKEN_HERE}" \
-H "Content-Type: application/json"

我們可以看到以下波形序列作為輸出。

[{"generated_audio":[[-0.024490159,-0.03154691,-0.0079551935,-0.003828604, ...]]}]

聽起來是這樣的

您還可以使用 `huggingface-hub` Python 庫的 `InferenceClient` 類來呼叫端點。

from huggingface_hub import InferenceClient

client = InferenceClient(model = URL_OF_ENDPOINT)
response = client.post(json={"inputs":"an alt rock song"})
# response looks like this b'[{"generated_text":[[-0.182352,-0.17802449, ...]]}]

output = eval(response)[0]["generated_audio"]

您可以按照您喜歡的方式將生成的序列轉換為音訊。您可以使用 Python 中的 `scipy` 將其寫入 .wav 檔案。

import scipy
import numpy as np

# output is [[-0.182352,-0.17802449, ...]]
scipy.io.wavfile.write("musicgen_out.wav", rate=32000, data=np.array(output[0]))

瞧!

在下面的演示中嘗試使用該端點。

結論

在這篇博文中,我們展示瞭如何使用帶自定義推理處理程式的推理端點部署 MusicGen。同樣的技巧可以用於 Hub 中任何沒有關聯 pipeline 的其他模型。您只需覆蓋 `handler.py` 中的 `Endpoint Handler` 類,並新增 `requirements.txt` 以反映專案的依賴項即可。

閱讀更多

社群

註冊登入 以評論

© . This site is unofficial and not affiliated with Hugging Face, Inc.