Mungert commited on
Commit
a84433e
·
verified ·
1 Parent(s): 592a97b

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +681 -0
README.md ADDED
@@ -0,0 +1,681 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ pipeline_tag: image-text-to-text
4
+ library_name: transformers
5
+ base_model:
6
+ - google/paligemma-3b-mix-448
7
+ - Qwen/Qwen2.5-7B-Instruct
8
+ - google/siglip-so400m-patch14-384
9
+ - timm/convnext_xxlarge.clip_laion2b_soup_ft_in1k
10
+ base_model_relation: merge
11
+ language:
12
+ - multilingual
13
+ tags:
14
+ - eagle
15
+ - VLM
16
+ ---
17
+
18
+ # <span style="color: #7FFF7F;">Eagle2-9B GGUF Models</span>
19
+
20
+
21
+ ## <span style="color: #7F7FFF;">Model Generation Details</span>
22
+
23
+ This model was generated using [llama.cpp](https://github.com/ggerganov/llama.cpp) at commit [`e743cddb`](https://github.com/ggerganov/llama.cpp/commit/e743cddb60dc3a8815b9de7dd7d5c491e61b2259).
24
+
25
+
26
+
27
+
28
+
29
+ ---
30
+
31
+ ## <span style="color: #7FFF7F;">Quantization Beyond the IMatrix</span>
32
+
33
+ I've been experimenting with a new quantization approach that selectively elevates the precision of key layers beyond what the default IMatrix configuration provides.
34
+
35
+ In my testing, standard IMatrix quantization underperforms at lower bit depths, especially with Mixture of Experts (MoE) models. To address this, I'm using the `--tensor-type` option in `llama.cpp` to manually "bump" important layers to higher precision. You can see the implementation here:
36
+ 👉 [Layer bumping with llama.cpp](https://github.com/Mungert69/GGUFModelBuilder/blob/main/model-converter/tensor_list_builder.py)
37
+
38
+ While this does increase model file size, it significantly improves precision for a given quantization level.
39
+
40
+ ### **I'd love your feedback—have you tried this? How does it perform for you?**
41
+
42
+
43
+
44
+
45
+ ---
46
+
47
+ <a href="https://readyforquantum.com/huggingface_gguf_selection_guide.html" style="color: #7FFF7F;">
48
+ Click here to get info on choosing the right GGUF model format
49
+ </a>
50
+
51
+ ---
52
+
53
+
54
+
55
+ <!--Begin Original Model Card-->
56
+
57
+
58
+
59
+ # Eagle-2
60
+
61
+ [\[📂 GitHub\]](https://github.com/NVlabs/EAGLE) [\[📜 Eagle2 Tech Report\]](http://arxiv.org/abs/2501.14818)
62
+ [\[🗨️ Chat Demo\]](http://eagle-vlm.xyz/) [\[🤗 HF Demo\]](TODO)
63
+ ## Introduction
64
+
65
+ We are thrilled to release our latest Eagle2 series Vision-Language Model. Open-source Vision-Language Models (VLMs) have made significant strides in narrowing the gap with proprietary models. However, critical details about data strategies and implementation are often missing, limiting reproducibility and innovation. In this project, we focus on VLM post-training from a data-centric perspective, sharing insights into building effective data strategies from scratch. By combining these strategies with robust training recipes and model design, we introduce Eagle2, a family of performant VLMs. Our work aims to empower the open-source community to develop competitive VLMs with transparent processes.
66
+
67
+
68
+
69
+ In this repo, we are open-sourcing Eagle2-9B, which strikes the perfect balance between performance and inference speed.
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+ ## Model Zoo
80
+ We provide the following models:
81
+
82
+ | model name | LLM | Vision | Max Length| HF Link|
83
+ | ----------- | ------- |---------|-|-|
84
+ | Eagle2-1B | [Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct) | Siglip | 16K| [🤗 link](https://huggingface.co/NVIDIA/Eagle2-1B)|
85
+ | Eagle2-2B | [Qwen2.5-1.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct) | Siglip | 16K| [🤗 link](https://huggingface.co/NVIDIA/Eagle2-2B)|
86
+ | Eagle2-9B | [Qwen2.5-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct) | Siglip+ConvNext | 16K| [🤗 link](https://huggingface.co/NVIDIA/Eagle2-9B)|
87
+
88
+ ## Benchmark Results
89
+ | Benchmark | MiniCPM-Llama3-V-2_5 | InternVL-Chat-V1-5 | InternVL2-8B |QwenVL2-7B| Eagle2-9B|
90
+ | :--------------------------: | :------------------: | :----------------: | :----------: |:----------: |:----------: |
91
+ | Model Size | 8.5B | 25.5B | 8.1B | 8.3B|8.9B|
92
+ | | | | | | |
93
+ | DocVQA<sub>test</sub> | 84.8 | 90.9 | 91.6 |**94.5**|92.6|
94
+ | ChartQA<sub>test</sub> | - | 83.8 | 83.3 |83.0|**86.4**|
95
+ | InfoVQA<sub>test</sub> | - | 72.5 | 74.8 |74.3|**77.2**|
96
+ | TextVQA<sub>val</sub> | 76.6 | 80.6 | 77.4 |**84.3**|83.0|
97
+ | OCRBench | 725 | 724 | 794 |845|**868**|
98
+ | MME<sub>sum</sub> | 2024.6 | 2187.8 | 2210.3 | **2326.8**|2260|
99
+ | RealWorldQA | 63.5 | 66.0 | 64.4 |**70.1**|69.3|
100
+ | AI2D<sub>test</sub> | 78.4 | 80.7 | 83.8 | - |**83.9**|
101
+ | MMMU<sub>val</sub> | 45.8 | 45.2 / 46.8 | 49.3 / 51.8 |54.1|**56.1**|
102
+ | MMBench_V11<sub>test</sub> | | | 79.5 |79.4|**80.6**|
103
+ | MMVet<sub>GPT-4-Turbo</sub> | 52.8 | 55.4 | 54.2 | 62.0|**62.2**|
104
+ | SEED-Image | 72.3 | 76.0 | 76.2 ||**77.1**|
105
+ | HallBench<sub>avg</sub> | 42.4 | 49.3 | 45.2 |**50.6**|49.3
106
+ | MathVista<sub>testmini</sub> | 54.3 | 53.5 | 58.3 |58.2|**63.8**|
107
+ | MMstar | - | - | 60.9|60.7|**62.6**|
108
+
109
+
110
+
111
+ ## Quick Start
112
+
113
+
114
+
115
+ We provide a [demo inference script](./demo.py) to help you quickly start using the model. We support different input types:
116
+ - pure text input
117
+ - single image input
118
+ - multiple image input
119
+ - video input
120
+
121
+ ### 0. Install the dependencies
122
+
123
+ ```bash
124
+ pip install transformers==4.37.2
125
+ pip install flash-attn
126
+ ```
127
+ **Note**: Latest version of transformers is not compatible with the model.
128
+
129
+ ### 1. Prepare the Model worker
130
+
131
+ <details>
132
+ <summary>Click to expand</summary>
133
+
134
+ ```python
135
+
136
+ """
137
+ A model worker executes the model.
138
+ Copied and modified from https://github.com/OpenGVLab/InternVL/blob/main/streamlit_demo/model_worker.py
139
+ """
140
+ # Importing torch before transformers can cause `segmentation fault`
141
+ from transformers import AutoModel, AutoTokenizer, TextIteratorStreamer, AutoConfig
142
+
143
+ import argparse
144
+ import base64
145
+ import json
146
+ import os
147
+ import decord
148
+ import threading
149
+ import time
150
+ from io import BytesIO
151
+ from threading import Thread
152
+ import math
153
+ import requests
154
+ import torch
155
+ import torchvision.transforms as T
156
+ from PIL import Image
157
+ from torchvision.transforms.functional import InterpolationMode
158
+ import numpy as np
159
+
160
+
161
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
162
+ IMAGENET_STD = (0.229, 0.224, 0.225)
163
+
164
+ SIGLIP_MEAN = (0.5, 0.5, 0.5)
165
+ SIGLIP_STD = (0.5, 0.5, 0.5)
166
+
167
+
168
+ def get_seq_frames(total_num_frames, desired_num_frames=-1, stride=-1):
169
+ """
170
+ Calculate the indices of frames to extract from a video.
171
+
172
+ Parameters:
173
+ total_num_frames (int): Total number of frames in the video.
174
+ desired_num_frames (int): Desired number of frames to extract.
175
+
176
+ Returns:
177
+ list: List of indices of frames to extract.
178
+ """
179
+
180
+ assert desired_num_frames > 0 or stride > 0 and not (desired_num_frames > 0 and stride > 0)
181
+
182
+ if stride > 0:
183
+ return list(range(0, total_num_frames, stride))
184
+
185
+ # Calculate the size of each segment from which a frame will be extracted
186
+ seg_size = float(total_num_frames - 1) / desired_num_frames
187
+
188
+ seq = []
189
+ for i in range(desired_num_frames):
190
+ # Calculate the start and end indices of each segment
191
+ start = int(np.round(seg_size * i))
192
+ end = int(np.round(seg_size * (i + 1)))
193
+
194
+ # Append the middle index of the segment to the list
195
+ seq.append((start + end) // 2)
196
+
197
+ return seq
198
+
199
+ def build_video_prompt(meta_list, num_frames, time_position=False):
200
+ # if time_position is True, the frame_timestamp is used.
201
+ # 1. pass time_position, 2. use env TIME_POSITION
202
+ time_position = os.environ.get("TIME_POSITION", time_position)
203
+ prefix = f"This is a video:\n"
204
+ for i in range(num_frames):
205
+ if time_position:
206
+ frame_txt = f"Frame {i+1} sampled at {meta_list[i]:.2f} seconds: <image>\n"
207
+ else:
208
+ frame_txt = f"Frame {i+1}: <image>\n"
209
+ prefix += frame_txt
210
+ return prefix
211
+
212
+ def load_video(video_path, num_frames=64, frame_cache_root=None):
213
+ if isinstance(video_path, str):
214
+ video = decord.VideoReader(video_path)
215
+ elif isinstance(video_path, dict):
216
+ assert False, 'we not support vidoe: "video_path" as input'
217
+ fps = video.get_avg_fps()
218
+ sampled_frames = get_seq_frames(len(video), num_frames)
219
+ samepld_timestamps = [i / fps for i in sampled_frames]
220
+ frames = video.get_batch(sampled_frames).asnumpy()
221
+ images = [Image.fromarray(frame) for frame in frames]
222
+
223
+ return images, build_video_prompt(samepld_timestamps, len(images), time_position=True)
224
+
225
+ def load_image(image):
226
+ if isinstance(image, str) and os.path.exists(image):
227
+ return Image.open(image)
228
+ elif isinstance(image, dict):
229
+ if 'disk_path' in image:
230
+ return Image.open(image['disk_path'])
231
+ elif 'base64' in image:
232
+ return Image.open(BytesIO(base64.b64decode(image['base64'])))
233
+ elif 'url' in image:
234
+ response = requests.get(image['url'])
235
+ return Image.open(BytesIO(response.content))
236
+ elif 'bytes' in image:
237
+ return Image.open(BytesIO(image['bytes']))
238
+ else:
239
+ raise ValueError(f'Invalid image: {image}')
240
+ else:
241
+ raise ValueError(f'Invalid image: {image}')
242
+
243
+ def build_transform(input_size, norm_type='imagenet'):
244
+ if norm_type == 'imagenet':
245
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
246
+ elif norm_type == 'siglip':
247
+ MEAN, STD = SIGLIP_MEAN, SIGLIP_STD
248
+
249
+ transform = T.Compose([
250
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
251
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
252
+ T.ToTensor(),
253
+ T.Normalize(mean=MEAN, std=STD)
254
+ ])
255
+ return transform
256
+
257
+
258
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
259
+ """
260
+ previous version mainly foucs on ratio.
261
+ We also consider area ratio here.
262
+ """
263
+ best_factor = float('-inf')
264
+ best_ratio = (1, 1)
265
+ area = width * height
266
+ for ratio in target_ratios:
267
+ target_aspect_ratio = ratio[0] / ratio[1]
268
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
269
+ area_ratio = (ratio[0]*ratio[1]*image_size*image_size)/ area
270
+ """
271
+ new area > 60% of original image area is enough.
272
+ """
273
+ factor_based_on_area_n_ratio = min((ratio[0]*ratio[1]*image_size*image_size)/ area, 0.6)* \
274
+ min(target_aspect_ratio/aspect_ratio, aspect_ratio/target_aspect_ratio)
275
+
276
+ if factor_based_on_area_n_ratio > best_factor:
277
+ best_factor = factor_based_on_area_n_ratio
278
+ best_ratio = ratio
279
+
280
+ return best_ratio
281
+
282
+
283
+ def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False):
284
+ orig_width, orig_height = image.size
285
+ aspect_ratio = orig_width / orig_height
286
+
287
+ # calculate the existing image aspect ratio
288
+ target_ratios = set(
289
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
290
+ i * j <= max_num and i * j >= min_num)
291
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
292
+
293
+ # find the closest aspect ratio to the target
294
+ target_aspect_ratio = find_closest_aspect_ratio(
295
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
296
+
297
+ # calculate the target width and height
298
+ target_width = image_size * target_aspect_ratio[0]
299
+ target_height = image_size * target_aspect_ratio[1]
300
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
301
+
302
+ # resize the image
303
+ resized_img = image.resize((target_width, target_height))
304
+ processed_images = []
305
+ for i in range(blocks):
306
+ box = (
307
+ (i % (target_width // image_size)) * image_size,
308
+ (i // (target_width // image_size)) * image_size,
309
+ ((i % (target_width // image_size)) + 1) * image_size,
310
+ ((i // (target_width // image_size)) + 1) * image_size
311
+ )
312
+ # split the image
313
+ split_img = resized_img.crop(box)
314
+ processed_images.append(split_img)
315
+ assert len(processed_images) == blocks
316
+ if use_thumbnail and len(processed_images) != 1:
317
+ thumbnail_img = image.resize((image_size, image_size))
318
+ processed_images.append(thumbnail_img)
319
+ return processed_images
320
+
321
+ def split_model(model_path, device):
322
+
323
+ device_map = {}
324
+ world_size = torch.cuda.device_count()
325
+ config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
326
+ num_layers = config.llm_config.num_hidden_layers
327
+
328
+ print('world_size', world_size)
329
+ num_layers_per_gpu_ = math.floor(num_layers / (world_size - 1))
330
+ num_layers_per_gpu = [num_layers_per_gpu_] * world_size
331
+ num_layers_per_gpu[device] = num_layers - num_layers_per_gpu_ * (world_size-1)
332
+ print(num_layers_per_gpu)
333
+ layer_cnt = 0
334
+ for i, num_layer in enumerate(num_layers_per_gpu):
335
+ for j in range(num_layer):
336
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
337
+ layer_cnt += 1
338
+ device_map['vision_model'] = device
339
+ device_map['mlp1'] = device
340
+ device_map['language_model.model.tok_embeddings'] = device
341
+ device_map['language_model.model.embed_tokens'] = device
342
+ device_map['language_model.output'] = device
343
+ device_map['language_model.model.norm'] = device
344
+ device_map['language_model.lm_head'] = device
345
+ device_map['language_model.model.rotary_emb'] = device
346
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = device
347
+ return device_map
348
+
349
+ class ModelWorker:
350
+ def __init__(self, model_path, model_name,
351
+ load_8bit, device):
352
+
353
+ if model_path.endswith('/'):
354
+ model_path = model_path[:-1]
355
+ if model_name is None:
356
+ model_paths = model_path.split('/')
357
+ if model_paths[-1].startswith('checkpoint-'):
358
+ self.model_name = model_paths[-2] + '_' + model_paths[-1]
359
+ else:
360
+ self.model_name = model_paths[-1]
361
+ else:
362
+ self.model_name = model_name
363
+
364
+ print(f'Loading the model {self.model_name}')
365
+
366
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True, use_fast=False)
367
+ tokens_to_keep = ['<box>', '</box>', '<ref>', '</ref>']
368
+ tokenizer.additional_special_tokens = [item for item in tokenizer.additional_special_tokens if item not in tokens_to_keep]
369
+ self.tokenizer = tokenizer
370
+ config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
371
+ model_type = config.vision_config.model_type
372
+ self.device = torch.cuda.current_device()
373
+ if model_type == 'siglip_vision_model':
374
+ self.norm_type = 'siglip'
375
+ elif model_type == 'MOB':
376
+ self.norm_type = 'siglip'
377
+ else:
378
+ self.norm_type = 'imagenet'
379
+
380
+ if any(x in model_path.lower() for x in ['34b']):
381
+ device_map = split_model(model_path, self.device)
382
+ else:
383
+ device_map = None
384
+
385
+ if device_map is not None:
386
+ self.model = AutoModel.from_pretrained(model_path, torch_dtype=torch.bfloat16,
387
+ low_cpu_mem_usage=True,
388
+ device_map=device_map,
389
+ trust_remote_code=True,
390
+ load_in_8bit=load_8bit).eval()
391
+ else:
392
+ self.model = AutoModel.from_pretrained(model_path, torch_dtype=torch.bfloat16,
393
+ trust_remote_code=True,
394
+ load_in_8bit=load_8bit).eval()
395
+
396
+ if not load_8bit and device_map is None:
397
+ self.model = self.model.to(device)
398
+ self.load_8bit = load_8bit
399
+
400
+ self.model_path = model_path
401
+ self.image_size = self.model.config.force_image_size
402
+ self.context_len = tokenizer.model_max_length
403
+ self.per_tile_len = 256
404
+
405
+ def reload_model(self):
406
+ del self.model
407
+ torch.cuda.empty_cache()
408
+ if self.device == 'auto':
409
+ os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
410
+ # This can make distributed deployment work properly
411
+ self.model = AutoModel.from_pretrained(
412
+ self.model_path,
413
+ load_in_8bit=self.load_8bit,
414
+ torch_dtype=torch.bfloat16,
415
+ device_map=self.device_map,
416
+ trust_remote_code=True).eval()
417
+ else:
418
+ self.model = AutoModel.from_pretrained(
419
+ self.model_path,
420
+ load_in_8bit=self.load_8bit,
421
+ torch_dtype=torch.bfloat16,
422
+ trust_remote_code=True).eval()
423
+ if not self.load_8bit and not self.device == 'auto':
424
+ self.model = self.model.cuda()
425
+
426
+ @torch.inference_mode()
427
+ def generate(self, params):
428
+ system_message = params['prompt'][0]['content']
429
+ send_messages = params['prompt'][1:]
430
+ max_input_tiles = params['max_input_tiles']
431
+ temperature = params['temperature']
432
+ top_p = params['top_p']
433
+ max_new_tokens = params['max_new_tokens']
434
+ repetition_penalty = params['repetition_penalty']
435
+ video_frame_num = params.get('video_frame_num', 64)
436
+ do_sample = True if temperature > 0.0 else False
437
+
438
+ global_image_cnt = 0
439
+ history, pil_images, max_input_tile_list = [], [], []
440
+ for message in send_messages:
441
+ if message['role'] == 'user':
442
+ prefix = ''
443
+ if 'image' in message:
444
+ for image_data in message['image']:
445
+ pil_images.append(load_image(image_data))
446
+ prefix = prefix + f'<image {global_image_cnt + 1}><image>\n'
447
+ global_image_cnt += 1
448
+ max_input_tile_list.append(max_input_tiles)
449
+ if 'video' in message:
450
+ for video_data in message['video']:
451
+ video_frames, tmp_prefix = load_video(video_data, num_frames=video_frame_num)
452
+ pil_images.extend(video_frames)
453
+ prefix = prefix + tmp_prefix
454
+ global_image_cnt += len(video_frames)
455
+ max_input_tile_list.extend([1] * len(video_frames))
456
+ content = prefix + message['content']
457
+ history.append([content, ])
458
+ else:
459
+ history[-1].append(message['content'])
460
+ question, history = history[-1][0], history[:-1]
461
+
462
+ if global_image_cnt == 1:
463
+ question = question.replace('<image 1><image>\n', '<image>\n')
464
+ history = [[item[0].replace('<image 1><image>\n', '<image>\n'), item[1]] for item in history]
465
+
466
+
467
+ try:
468
+ assert len(max_input_tile_list) == len(pil_images), 'The number of max_input_tile_list and pil_images should be the same.'
469
+ except Exception as e:
470
+ from IPython import embed; embed()
471
+ exit()
472
+ print(f'Error: {e}')
473
+ print(f'max_input_tile_list: {max_input_tile_list}, pil_images: {pil_images}')
474
+ # raise e
475
+
476
+ old_system_message = self.model.system_message
477
+ self.model.system_message = system_message
478
+
479
+ transform = build_transform(input_size=self.image_size, norm_type=self.norm_type)
480
+ if len(pil_images) > 0:
481
+ max_input_tiles_limited_by_contect = params['max_input_tiles']
482
+ while True:
483
+ image_tiles = []
484
+ for current_max_input_tiles, pil_image in zip(max_input_tile_list, pil_images):
485
+ if self.model.config.dynamic_image_size:
486
+ tiles = dynamic_preprocess(
487
+ pil_image, image_size=self.image_size, max_num=min(current_max_input_tiles, max_input_tiles_limited_by_contect),
488
+ use_thumbnail=self.model.config.use_thumbnail)
489
+ else:
490
+ tiles = [pil_image]
491
+ image_tiles += tiles
492
+ if (len(image_tiles) * self.per_tile_len < self.context_len):
493
+ break
494
+ else:
495
+ max_input_tiles_limited_by_contect -= 2
496
+
497
+ if max_input_tiles_limited_by_contect < 1:
498
+ break
499
+
500
+ pixel_values = [transform(item) for item in image_tiles]
501
+ pixel_values = torch.stack(pixel_values).to(self.model.device, dtype=torch.bfloat16)
502
+ print(f'Split images to {pixel_values.shape}')
503
+ else:
504
+ pixel_values = None
505
+
506
+ generation_config = dict(
507
+ num_beams=1,
508
+ max_new_tokens=max_new_tokens,
509
+ do_sample=do_sample,
510
+ temperature=temperature,
511
+ repetition_penalty=repetition_penalty,
512
+ max_length=self.context_len,
513
+ top_p=top_p,
514
+ )
515
+
516
+ response = self.model.chat(
517
+ tokenizer=self.tokenizer,
518
+ pixel_values=pixel_values,
519
+ question=question,
520
+ history=history,
521
+ return_history=False,
522
+ generation_config=generation_config,
523
+ )
524
+ self.model.system_message = old_system_message
525
+ return {'text': response, 'error_code': 0}
526
+
527
+
528
+
529
+
530
+
531
+ if __name__ == '__main__':
532
+ parser = argparse.ArgumentParser()
533
+ parser.add_argument('--model-path', type=str, default='nvidia/Eagle2-9B')
534
+ parser.add_argument('--model-name', type=str, default='Eagle2-9B')
535
+ parser.add_argument('--device', type=str, default='cuda')
536
+ parser.add_argument('--load-8bit', action='store_true')
537
+ args = parser.parse_args()
538
+ print(f'args: {args}')
539
+
540
+ worker = ModelWorker(
541
+ args.model_path,
542
+ args.model_name,
543
+ args.load_8bit,
544
+ args.device)
545
+ ```
546
+ </details>
547
+
548
+
549
+ ### 2. Prepare the Prompt
550
+
551
+ - Single image input
552
+ ```python
553
+ prompt = [
554
+ {'role': 'system', 'content': 'You are a helpful assistant.'},
555
+ {'role': 'user', 'content': 'Describe this image in details.',
556
+ 'image':[
557
+ {'url': 'https://www.nvidia.com/content/dam/en-zz/Solutions/about-nvidia/logo-and-brand/[email protected]'}
558
+ ],
559
+ }
560
+ ]
561
+ ```
562
+
563
+ - Multiple image input
564
+ ```python
565
+ prompt = [
566
+ {'role': 'system', 'content': 'You are a helpful assistant.'},
567
+ {'role': 'user', 'content': 'Describe these two images in details.',
568
+ 'image':[
569
+ {'url': 'https://www.nvidia.com/content/dam/en-zz/Solutions/about-nvidia/logo-and-brand/[email protected]'},
570
+ {'url': 'https://www.nvidia.com/content/dam/en-zz/Solutions/about-nvidia/logo-and-brand/[email protected]'}
571
+ ],
572
+ }
573
+ ]
574
+ ```
575
+
576
+ - Video input
577
+ ```python
578
+ prompt = [
579
+ {'role': 'system', 'content': 'You are a helpful assistant.'},
580
+ {'role': 'user', 'content': 'Describe this video in details.',
581
+ 'video':[
582
+ 'path/to/your/video.mp4'
583
+ ],
584
+ }
585
+ ]
586
+ ```
587
+
588
+ ### 3. Generate the response
589
+ ```python
590
+ params = {
591
+ 'prompt': prompt,
592
+ 'max_input_tiles': 24,
593
+ 'temperature': 0.7,
594
+ 'top_p': 1.0,
595
+ 'max_new_tokens': 4096,
596
+ 'repetition_penalty': 1.0,
597
+ }
598
+ worker.generate(params)
599
+ ```
600
+
601
+ ## TODO
602
+ - [ ] Support vLLM Inference
603
+ - [ ] Provide AWQ Quantization Weights
604
+ - [ ] Provide fine-tuning scripts
605
+
606
+
607
+ ## License/Terms of Use
608
+ - The code is released under the Apache 2.0 license as found in the [LICENSE](https://huggingface.co/NVEagle/Eagle-X5-13B-Chat/blob/main/LICENSE) file.
609
+ - The pretrained model weights are released under the [Creative Commons Attribution: Non-Commercial 4.0 International](https://spdx.org/licenses/CC-BY-NC-4.0) <br>
610
+ - The service is a research preview intended for non-commercial use only, and is subject to the following licenses and terms:
611
+ - Model License of Qwen2.5-7B-Instruct: [Apache-2.0](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct/blob/main/LICENSE)
612
+ - Model License of PaliGemma: [Gemma license](https://ai.google.dev/gemma/terms)
613
+
614
+
615
+
616
+ ## Citation
617
+
618
+ ## Ethical Considerations
619
+ NVIDIA believes Trustworthy AI is a shared responsibility and we have established policies and practices to enable development for a wide array of AI applications. When downloaded or used in accordance with our terms of service, developers should work with their internal model team to ensure this model meets requirements for the relevant industry and use case and addresses unforeseen product misuse.
620
+
621
+ Please report security vulnerabilities or NVIDIA AI Concerns [here](https://www.nvidia.com/en-us/support/submit-security-vulnerability/).
622
+
623
+
624
+ <!--End Original Model Card-->
625
+
626
+ ---
627
+
628
+ # <span id="testllm" style="color: #7F7FFF;">🚀 If you find these models useful</span>
629
+
630
+ Help me test my **AI-Powered Quantum Network Monitor Assistant** with **quantum-ready security checks**:
631
+
632
+ 👉 [Quantum Network Monitor](https://readyforquantum.com/?assistant=open&utm_source=huggingface&utm_medium=referral&utm_campaign=huggingface_repo_readme)
633
+
634
+
635
+ The full Open Source Code for the Quantum Network Monitor Service available at my github repos ( repos with NetworkMonitor in the name) : [Source Code Quantum Network Monitor](https://github.com/Mungert69). You will also find the code I use to quantize the models if you want to do it yourself [GGUFModelBuilder](https://github.com/Mungert69/GGUFModelBuilder)
636
+
637
+ 💬 **How to test**:
638
+ Choose an **AI assistant type**:
639
+ - `TurboLLM` (GPT-4.1-mini)
640
+ - `HugLLM` (Hugginface Open-source models)
641
+ - `TestLLM` (Experimental CPU-only)
642
+
643
+ ### **What I’m Testing**
644
+ I’m pushing the limits of **small open-source models for AI network monitoring**, specifically:
645
+ - **Function calling** against live network services
646
+ - **How small can a model go** while still handling:
647
+ - Automated **Nmap security scans**
648
+ - **Quantum-readiness checks**
649
+ - **Network Monitoring tasks**
650
+
651
+ 🟡 **TestLLM** – Current experimental model (llama.cpp on 2 CPU threads on huggingface docker space):
652
+ - ✅ **Zero-configuration setup**
653
+ - ⏳ 30s load time (slow inference but **no API costs**) . No token limited as the cost is low.
654
+ - 🔧 **Help wanted!** If you’re into **edge-device AI**, let’s collaborate!
655
+
656
+ ### **Other Assistants**
657
+ 🟢 **TurboLLM** – Uses **gpt-4.1-mini** :
658
+ - **It performs very well but unfortunatly OpenAI charges per token. For this reason tokens usage is limited.
659
+ - **Create custom cmd processors to run .net code on Quantum Network Monitor Agents**
660
+ - **Real-time network diagnostics and monitoring**
661
+ - **Security Audits**
662
+ - **Penetration testing** (Nmap/Metasploit)
663
+
664
+ 🔵 **HugLLM** – Latest Open-source models:
665
+ - 🌐 Runs on Hugging Face Inference API. Performs pretty well using the lastest models hosted on Novita.
666
+
667
+ ### 💡 **Example commands you could test**:
668
+ 1. `"Give me info on my websites SSL certificate"`
669
+ 2. `"Check if my server is using quantum safe encyption for communication"`
670
+ 3. `"Run a comprehensive security audit on my server"`
671
+ 4. '"Create a cmd processor to .. (what ever you want)" Note you need to install a [Quantum Network Monitor Agent](https://readyforquantum.com/Download/?utm_source=huggingface&utm_medium=referral&utm_campaign=huggingface_repo_readme) to run the .net code on. This is a very flexible and powerful feature. Use with caution!
672
+
673
+ ### Final Word
674
+
675
+ I fund the servers used to create these model files, run the Quantum Network Monitor service, and pay for inference from Novita and OpenAI—all out of my own pocket. All the code behind the model creation and the Quantum Network Monitor project is [open source](https://github.com/Mungert69). Feel free to use whatever you find helpful.
676
+
677
+ If you appreciate the work, please consider [buying me a coffee](https://www.buymeacoffee.com/mahadeva) ☕. Your support helps cover service costs and allows me to raise token limits for everyone.
678
+
679
+ I'm also open to job opportunities or sponsorship.
680
+
681
+ Thank you! 😊