|
| 1 | +from transformers import FuyuForCausalLM, AutoTokenizer, FuyuImageProcessor, FuyuProcessor |
| 2 | +from lmms_eval.api.model import lmms |
| 3 | +from lmms_eval.api.registry import register_model |
| 4 | +import torch |
| 5 | +from PIL import Image |
| 6 | +from typing import List, Optional, Union, Tuple |
| 7 | +from lmms_eval import utils |
| 8 | +from lmms_eval.api.instance import Instance |
| 9 | +from tqdm import tqdm |
| 10 | + |
| 11 | + |
| 12 | +@register_model("fuyu") |
| 13 | +class Fuyu(lmms): |
| 14 | + """ |
| 15 | + Fuyu Model |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + pretrained: str = "adept/fuyu-8b", |
| 21 | + device: Optional[str] = "cuda", |
| 22 | + max_new_tokens: int = 256, |
| 23 | + batch_size: Optional[Union[int, str]] = 1, |
| 24 | + **kwargs, |
| 25 | + ) -> None: |
| 26 | + super().__init__() |
| 27 | + # Do not use kwargs for now |
| 28 | + assert kwargs == {}, f"Unexpected kwargs: {kwargs}" |
| 29 | + |
| 30 | + self.device = device if torch.cuda.is_available() else "cpu" |
| 31 | + self.model = FuyuForCausalLM.from_pretrained(pretrained, torch_dtype=torch.bfloat16, device_map=self.device) |
| 32 | + self.model.eval() |
| 33 | + self.tokenizer = AutoTokenizer.from_pretrained(pretrained) |
| 34 | + self.image_processor = FuyuImageProcessor() |
| 35 | + self.processor = FuyuProcessor(image_processor=self.image_processor, tokenizer=self.tokenizer) |
| 36 | + self.max_new_tokens = max_new_tokens |
| 37 | + self.batch_size_per_gpu = int(batch_size) |
| 38 | + |
| 39 | + @property |
| 40 | + def max_length(self): |
| 41 | + # Assuming max_length is the sum of max context tokens and max new tokens |
| 42 | + return self.tokenizer.model_max_length |
| 43 | + |
| 44 | + # @property |
| 45 | + # def max_gen_toks(self) -> int: |
| 46 | + # return self.max_new_tokens |
| 47 | + |
| 48 | + @property |
| 49 | + def batch_size(self): |
| 50 | + return self.batch_size_per_gpu |
| 51 | + |
| 52 | + def flatten(self, input, only_get_first=False): |
| 53 | + new_list = [] |
| 54 | + for i in input: |
| 55 | + for j in i: |
| 56 | + new_list.append(j) |
| 57 | + if only_get_first: |
| 58 | + break |
| 59 | + return new_list |
| 60 | + |
| 61 | + def generate_until(self, requests: List[Instance]) -> List[str]: |
| 62 | + res = [] |
| 63 | + |
| 64 | + def _collate(x): |
| 65 | + # the negative sign on len(toks) sorts descending - this has a few advantages: |
| 66 | + # - time estimates will always be over not underestimates, which is more useful for planning |
| 67 | + # - to know the size of a batch when going through the list, you know the first one is always the batch |
| 68 | + # padded context length. this is useful to simplify the batching logic and more importantly to make |
| 69 | + # automatic adaptive batches much much easier to implement |
| 70 | + # - any OOMs will happen right away rather than near the end |
| 71 | + toks = self.tok_encode(x[0]) |
| 72 | + return -len(toks), x[0] |
| 73 | + |
| 74 | + re_ords = utils.Collator([reg.args for reg in requests], _collate, grouping=True) |
| 75 | + chunks = re_ords.get_batched(n=self.batch_size, batch_fn=None) |
| 76 | + num_iters = len(requests) // self.batch_size if len(requests) % self.batch_size == 0 else len(requests) // self.batch_size + 1 |
| 77 | + pbar = tqdm(total=num_iters, disable=(self.rank != 0), desc="Model Responding") |
| 78 | + |
| 79 | + for chunk in chunks: |
| 80 | + contexts, all_gen_kwargs, doc_to_visual, doc_id, task, split = zip(*chunk) |
| 81 | + task = task[0] |
| 82 | + split = split[0] |
| 83 | + visuals = [doc_to_visual[0](self.task_dict[task][split][ids]) for ids in doc_id] |
| 84 | + visuals = self.flatten(visuals, only_get_first=True) |
| 85 | + gen_kwargs = all_gen_kwargs[0] |
| 86 | + |
| 87 | + # if isinstance(visuals[0], list): |
| 88 | + # visuals = [visuals[idx][0] for idx in range(len(visuals))] # get the first image in multi-image scenarios. |
| 89 | + |
| 90 | + # assert len(contexts) == self.batch_size_per_gpu, f"Expected contexts batch size {self.batch_size_per_gpu}, got {len(contexts)}" |
| 91 | + # assert len(visuals) == self.batch_size_per_gpu, f"Expected visuals batch size {self.batch_size_per_gpu}, got {len(visuals)}" |
| 92 | + formatted_contexts = [f"{context}\n" for context in contexts] |
| 93 | + model_inputs = self.processor(text=formatted_contexts, images=visuals, device=self.device) |
| 94 | + for k, v in model_inputs.items(): |
| 95 | + model_inputs[k] = v.to(self.device, non_blocking=True) if isinstance(v, torch.Tensor) else [vv.to(self.device, non_blocking=True) for vv in v] |
| 96 | + |
| 97 | + for index in range(len(model_inputs["image_patches"])): |
| 98 | + model_inputs["image_patches"][index] = model_inputs["image_patches"][index].to(dtype=next(self.model.parameters()).dtype) |
| 99 | + |
| 100 | + # preconfigure gen_kwargs with defaults |
| 101 | + gen_kwargs["image_sizes"] = [visuals[idx].size for idx in range(len(visuals))] |
| 102 | + if "max_new_tokens" not in gen_kwargs: |
| 103 | + gen_kwargs["max_new_tokens"] = 1024 |
| 104 | + if "temperature" not in gen_kwargs: |
| 105 | + gen_kwargs["temperature"] = 0 |
| 106 | + if "top_p" not in gen_kwargs: |
| 107 | + gen_kwargs["top_p"] = None |
| 108 | + if "num_beams" not in gen_kwargs: |
| 109 | + gen_kwargs["num_beams"] = 1 |
| 110 | + generation_output = self.model.generate(**model_inputs, max_new_tokens=gen_kwargs["max_new_tokens"], pad_token_id=self.tokenizer.eos_token_id) |
| 111 | + generation_texts = self.processor.batch_decode(generation_output, skip_special_tokens=True) |
| 112 | + response = [gen_text.split("\x04")[1].strip(" ").strip("\n") for gen_text in generation_texts] |
| 113 | + res.extend(response) |
| 114 | + pbar.update(1) |
| 115 | + |
| 116 | + pbar.close() |
| 117 | + return res |
| 118 | + |
| 119 | + def loglikelihood(self, requests: List[Instance]) -> List[Tuple[float, bool]]: |
| 120 | + # TODO |
| 121 | + assert False, "We have not implemented this function for llava yet" |
| 122 | + |
| 123 | + def loglikelihood_rolling(self, requests: List[Instance]) -> List[float]: |
| 124 | + # TODO |
| 125 | + assert False, "We have not implemented this function for llava yet" |
| 126 | + |
| 127 | + def tok_encode(self, string: str, left_truncate_len=None, add_special_tokens=None) -> List[int]: |
| 128 | + """ """ |
| 129 | + add_special_tokens = False if add_special_tokens is None else add_special_tokens |
| 130 | + encoding = self.tokenizer.encode(string, add_special_tokens=add_special_tokens) |
| 131 | + # left-truncate the encoded context to be at most `left_truncate_len` tokens long |
| 132 | + if left_truncate_len: |
| 133 | + encoding = encoding[-left_truncate_len:] |
| 134 | + return encoding |
| 135 | + |
| 136 | + def tok_decode(self, tokens): |
| 137 | + return self.tokenizer.decode(tokens) |
0 commit comments