|
| 1 | +from typing import TYPE_CHECKING, Any, Iterator, List, Optional, Union |
| 2 | + |
| 3 | +from outlines.generate.api import GenerationParameters, SamplingParameters |
| 4 | +from outlines.models import Transformers |
| 5 | + |
| 6 | +if TYPE_CHECKING: |
| 7 | + from outlines.processors import OutlinesLogitsProcessor |
| 8 | + |
| 9 | + |
| 10 | +class TransformersAudio(Transformers): |
| 11 | + def __init__(self, model, tokenizer, processor): |
| 12 | + super().__init__(model, tokenizer) |
| 13 | + self.processor = processor |
| 14 | + |
| 15 | + def generate( # type: ignore |
| 16 | + self, |
| 17 | + prompts: Union[str, List[str]], |
| 18 | + media: Union[List[Any], List[List[Any]]], |
| 19 | + generation_parameters: GenerationParameters, |
| 20 | + logits_processor: Optional["OutlinesLogitsProcessor"], |
| 21 | + sampling_parameters: SamplingParameters, |
| 22 | + ) -> Union[str, List[str], List[List[str]]]: |
| 23 | + """Generate text using `transformers`. |
| 24 | +
|
| 25 | + Arguments |
| 26 | + --------- |
| 27 | + prompts |
| 28 | + A prompt or list of prompts. |
| 29 | + media |
| 30 | + A List[numpy.ndarray] or List[List[numpy.ndarray]] |
| 31 | + generation_parameters |
| 32 | + An instance of `GenerationParameters` that contains the prompt, |
| 33 | + the maximum number of tokens, stop sequences and seed. All the |
| 34 | + arguments to `SequenceGeneratorAdapter`'s `__cal__` method. |
| 35 | + logits_processor |
| 36 | + The logits processor to use when generating text. |
| 37 | + sampling_parameters |
| 38 | + An instance of `SamplingParameters`, a dataclass that contains |
| 39 | + the name of the sampler to use and related parameters as available |
| 40 | + in Outlines. |
| 41 | +
|
| 42 | + Returns |
| 43 | + ------- |
| 44 | + The generated text |
| 45 | + """ |
| 46 | + inputs = self.processor( |
| 47 | + text=prompts, audios=media, padding=True, return_tensors="pt" |
| 48 | + ).to(self.model.device) |
| 49 | + |
| 50 | + generation_kwargs = self._get_generation_kwargs( |
| 51 | + prompts, |
| 52 | + generation_parameters, |
| 53 | + logits_processor, |
| 54 | + sampling_parameters, |
| 55 | + ) |
| 56 | + generated_ids = self._generate_output_seq(prompts, inputs, **generation_kwargs) |
| 57 | + |
| 58 | + # if single str input and single sample per input, convert to a 1D output |
| 59 | + if isinstance(prompts, str): |
| 60 | + # Should always be true until NotImplementedError above is fixed |
| 61 | + generated_ids = generated_ids.squeeze(0) |
| 62 | + |
| 63 | + return self._decode_generation(generated_ids) |
| 64 | + |
| 65 | + def stream( # type: ignore |
| 66 | + self, |
| 67 | + prompts: Union[str, List[str]], |
| 68 | + media: Union[Any, List[Any]], # TODO: docstring |
| 69 | + generation_parameters: GenerationParameters, |
| 70 | + logits_processor: Optional["OutlinesLogitsProcessor"], |
| 71 | + sampling_parameters: SamplingParameters, |
| 72 | + ) -> Iterator[Union[str, List[str]]]: |
| 73 | + raise NotImplementedError |
| 74 | + |
| 75 | + |
| 76 | +def transformers_audio( |
| 77 | + model_name: str, |
| 78 | + model_class, |
| 79 | + device: Optional[str] = None, |
| 80 | + model_kwargs: dict = {}, |
| 81 | + processor_kwargs: dict = {}, |
| 82 | + tokenizer_class=None, |
| 83 | + processor_class=None, |
| 84 | +): |
| 85 | + """Instantiate a model from the `transformers` library and its tokenizer. |
| 86 | +
|
| 87 | + Parameters |
| 88 | + ---------- |
| 89 | + model_name |
| 90 | + The name of the model as listed on Hugging Face's model page. |
| 91 | + model_class |
| 92 | + The `PreTrainedModel` class from transformers to use in initializing the vision model from `model_name`. |
| 93 | + https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel |
| 94 | + device |
| 95 | + The device(s) on which the model should be loaded. This overrides |
| 96 | + the `device_map` entry in `model_kwargs` when provided. |
| 97 | + model_kwargs |
| 98 | + A dictionary that contains the keyword arguments to pass to the |
| 99 | + `from_pretrained` method when loading the model. |
| 100 | + processor_kwargs |
| 101 | + A dictionary that contains the keyword arguments to pass to the |
| 102 | + `from_pretrained` method when loading the processor. |
| 103 | +
|
| 104 | + Returns |
| 105 | + ------- |
| 106 | + A `TransformersModel` model instance. |
| 107 | +
|
| 108 | + """ |
| 109 | + if processor_class is None or tokenizer_class is None: |
| 110 | + try: |
| 111 | + from transformers import AutoProcessor, AutoTokenizer |
| 112 | + except ImportError: |
| 113 | + raise ImportError( |
| 114 | + "The `transformers` library needs to be installed in order to use `transformers` models." |
| 115 | + ) |
| 116 | + if processor_class is None: |
| 117 | + processor_class = AutoProcessor |
| 118 | + |
| 119 | + if device is not None: |
| 120 | + model_kwargs["device_map"] = device |
| 121 | + |
| 122 | + model = model_class.from_pretrained(model_name, **model_kwargs) |
| 123 | + |
| 124 | + processor_kwargs.setdefault("padding_side", "left") |
| 125 | + processor_kwargs.setdefault("pad_token", "[PAD]") |
| 126 | + processor = processor_class.from_pretrained(model_name, **processor_kwargs) |
| 127 | + |
| 128 | + if tokenizer_class is None: |
| 129 | + if getattr(processor, "tokenizer", None): |
| 130 | + tokenizer = processor.tokenizer |
| 131 | + else: |
| 132 | + tokenizer = AutoTokenizer.from_pretrained(model_name, **processor_kwargs) |
| 133 | + else: |
| 134 | + tokenizer = tokenizer_class.from_pretrained(model_name, **processor_kwargs) |
| 135 | + |
| 136 | + return TransformersAudio(model, tokenizer, processor) |
0 commit comments