from typing import Dict, List, Any from transformers import AutoProcessor, MusicgenForConditionalGeneration import torch processor = AutoProcessor.from_pretrained("facebook/musicgen-small") model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small") inputs = processor( text=["80s pop track with bassy drums and synth", "90s rock song with loud guitars and heavy drums"], padding=True, return_tensors="pt", ) audio_values = model.generate(**inputs, max_new_tokens=256) class EndpointHandler: def __init__(self, path=""): # load model and processor from path self.processor = AutoProcessor.from_pretrained(path) self.model = MusicgenForConditionalGeneration.from_pretrained(path) # self.model = AutoModelForSeq2SeqLM.from_pretrained(path, device_map="auto", load_in_8bit=True) # self.tokenizer = AutoTokenizer.from_pretrained(path) 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 # input_ids = self.tokenizer(inputs, return_tensors="pt").input_ids inputs = processor( text=inputs, padding=True, return_tensors="pt",) # pass inputs with all kwargs in data if parameters is not None: outputs = self.model.generate(inputs, max_new_tokens=256, **parameters) else: outputs = self.model.generate(inputs, max_new_tokens=256) # postprocess the prediction prediction = outputs[0].numpy() return [{"generated_audio": prediction}]