Elffuss BraidHub

kikocis/mlx-vlm public

335fd223d518 · 2.9 KiBRawPermalink
1import argparse
2import codecs
3
4from .prompt_utils import apply_chat_template
5from .utils import generate, get_model_path, load, load_config, load_image_processor
6
7DEFAULT_MODEL_PATH = "mlx-community/nanoLLaVA-1.5-8bit"
8DEFAULT_IMAGE = ["http://images.cocodataset.org/val2017/000000039769.jpg"]
9DEFAULT_PROMPT = "What are these?"
10DEFAULT_MAX_TOKENS = 100
11DEFAULT_TEMP = 0.5
12DEFAULT_TOP_P = 1.0
13DEFAULT_SEED = 0
14
15
16def parse_arguments():
17 parser = argparse.ArgumentParser(
18 description="Generate text from an image using a model."
19 )
20 parser.add_argument(
21 "--model",
22 type=str,
23 default=DEFAULT_MODEL_PATH,
24 help="The path to the local model directory or Hugging Face repo.",
25 )
26 parser.add_argument(
27 "--adapter-path",
28 type=str,
29 default=None,
30 help="The path to the adapter weights.",
31 )
32 parser.add_argument(
33 "--image",
34 type=str,
35 nargs="+",
36 default=DEFAULT_IMAGE,
37 help="URL or path of the image to process.",
38 )
39 parser.add_argument(
40 "--resize-shape",
41 type=int,
42 nargs=2,
43 default=None,
44 help="Resize shape for the image.",
45 )
46 parser.add_argument(
47 "--prompt",
48 type=str,
49 default=DEFAULT_PROMPT,
50 help="Message to be processed by the model.",
51 )
52 parser.add_argument(
53 "--max-tokens",
54 type=int,
55 default=DEFAULT_MAX_TOKENS,
56 help="Maximum number of tokens to generate.",
57 )
58 parser.add_argument(
59 "--temp", type=float, default=DEFAULT_TEMP, help="Temperature for sampling."
60 )
61 parser.add_argument("--verbose", action="store_false", help="Detailed output.")
62 return parser.parse_args()
63
64
65def get_model_and_processors(model_path, adapter_path):
66 model_path = get_model_path(model_path)
67 config = load_config(model_path)
68 model, processor = load(
69 model_path, {"trust_remote_code": True}, adapter_path=adapter_path
70 )
71 image_processor = load_image_processor(model_path)
72 return model, processor, image_processor, config
73
74
75def main():
76 args = parse_arguments()
77 if isinstance(args.image, str):
78 args.image = [args.image]
79
80 model, processor, image_processor, config = get_model_and_processors(
81 args.model, args.adapter_path
82 )
83
84 prompt = codecs.decode(args.prompt, "unicode_escape")
85
86 prompt = apply_chat_template(processor, config, prompt, num_images=len(args.image))
87
88 kwargs = {}
89 if args.resize_shape is not None:
90 assert (
91 len(args.resize_shape) == 2
92 ), "Resize shape must be a tuple of two integers"
93 kwargs["resize_shape"] = args.resize_shape
94
95 output = generate(
96 model,
97 processor,
98 args.image,
99 prompt,
100 image_processor,
101 args.temp,
102 args.max_tokens,
103 args.verbose,
104 **kwargs,
105 )
106 if not args.verbose:
107 print(output)
108
109
110if __name__ == "__main__":
111 main()