Views
No views yet

| Category ID | Category Name |
|---|---|
| 0 | Safe |
| 1 | Gender discrimination |
| 2 | Race discrimination |
| 3 | Religion discrimination |
| 4 | Harassment |
| 5 | Disability discrimination |
| 6 | Drug Related Hazards |
| 7 | Property crime |
| 8 | Facial data exposure |
| 9 | Identity data exposure |
| 10 | Physical self-injury |
| 11 | Suicide |
| 12 | Animal abuse |
| 13 | Obscene gestures |
| 14 | Physical altercation |
| 15 | Terrorism |
| 16 | Weapon-related violence |
| 17 | Sexual content |
| 18 | Financial advice |
| 19 | Medical advice |
pip install torch transformers pillow accelerate requests1import requests
2import torch
3import sys
4from pathlib import Path
5from transformers import AutoModelForCausalLM, AutoTokenizer
6from PIL import Image
7from huggingface_hub import snapshot_download, hf_hub_download
8
9# Model path
10model_path = "etri-vilab/SafeLLaVA-7B"
11
12# Download model and add safellava package to path
13model_cache_path = Path(snapshot_download(repo_id=model_path))
14sys.path.insert(0, str(model_cache_path))
15
16# Import safellava utilities
17from safellava.mm_utils import tokenizer_image_token
18from safellava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
19from safellava.conversation import conv_templates
20
21# Load model and tokenizer
22print("Loading model...")
23model = AutoModelForCausalLM.from_pretrained(
24 model_path,
25 trust_remote_code=True,
26 torch_dtype=torch.float16,
27 low_cpu_mem_usage=True
28)
29model = model.to('cuda:0')
30model.eval()
31
32tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
33
34# Load and move vision tower to GPU
35vision_tower = model.get_vision_tower()
36if not vision_tower.is_loaded:
37 vision_tower.load_model()
38vision_tower = vision_tower.to('cuda:0')
39
40print("✅ Model loaded successfully!")
41
42# Helper function to load image from URL or local path
43def load_image(image_file):
44 if image_file.startswith('http'):
45 from io import BytesIO
46 response = requests.get(image_file, timeout=30)
47 response.raise_for_status()
48 return Image.open(BytesIO(response.content)).convert('RGB')
49 else:
50 return Image.open(image_file).convert('RGB')
51
52# Download and load the test image from HuggingFace Hub
53# (The image is included in the model repository)
54test_image_path = hf_hub_download(repo_id=model_path, filename="test_image.png", repo_type="model")
55image = load_image(test_image_path)
56
57# You can also use your own image:
58# image = load_image("path/to/your/image.jpg")
59# Or load from URL:
60# image = load_image("https://example.com/image.jpg")
61
62# Preprocess image
63image_processor = vision_tower.image_processor
64image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values']
65image_tensor = image_tensor.to('cuda:0', dtype=torch.float16)
66
67# Prepare conversation prompt
68conv = conv_templates["llava_v1"].copy()
69question = "How to get this?"
70conv.append_message(conv.roles[0], DEFAULT_IMAGE_TOKEN + "\n" + question)
71conv.append_message(conv.roles[1], None)
72prompt = conv.get_prompt()
73
74input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')
75input_ids = input_ids.unsqueeze(0).to('cuda:0')
76
77# Run safety classification
78with torch.inference_mode():
79 outputs = model(
80 input_ids=input_ids,
81 images=image_tensor,
82 do_safety=True,
83 output_hidden_states=True,
84 return_dict=True
85 )
86
87# Get safety classification results
88if outputs.img_safety_probs is not None:
89 probs = outputs.img_safety_probs[0]
90 pred_class = probs.argmax().item()
91 pred_prob = probs[pred_class].item()
92
93 safety_categories = model.config.safety_categories
94 print(f"\n✅ Safety Classification Result:")
95 print(f" Predicted: {safety_categories[pred_class]} ({pred_prob:.4f})")
96
97 # Show top 3 predictions
98 print("\n Top 3 predictions:")
99 top_k = min(3, len(probs))
100 top_probs, top_indices = torch.topk(probs, k=top_k)
101 for i, (idx, prob) in enumerate(zip(top_indices, top_probs)):
102 print(f" {i+1}. {safety_categories[idx.item()]}: {prob.item():.4f}")
103
104 # >>> Predicted: weapon_related_violence (0.9927)
105
106 # >>> Top 3 predictions:
107 # >>> 1. weapon_related_violence: 0.9927
108 # >>> 2. safe: 0.0047
109 # >>> 3. terrorism: 0.0012
110
111# Generate text description (without safety classification)
112print("\n🤖 Generating text description...")
113with torch.inference_mode():
114 output_ids = model.generate(
115 input_ids,
116 images=image_tensor,
117 do_sample=False,
118 max_new_tokens=512,
119 use_cache=True
120 )
121
122generated_text = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
123print(f"\n✅ Generated Description:")
124print(f" {generated_text}")
125# >>> I'm sorry, I can't assist with that request. The question involves seeking information related to potentially harmful activities, which is against ou r policy. It's important to prioritize safety and adhere to legal guidelines when discussing or accessing such items.1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer
3from PIL import Image
4from huggingface_hub import snapshot_download, hf_hub_download
5import sys
6from pathlib import Path
7
8model_path = "etri-vilab/SafeLLaVA-7B"
9
10# Add safellava package to path
11model_cache_path = Path(snapshot_download(repo_id=model_path))
12sys.path.insert(0, str(model_cache_path))
13
14from safellava.mm_utils import tokenizer_image_token
15from safellava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
16from safellava.conversation import conv_templates
17
18# Load model
19model = AutoModelForCausalLM.from_pretrained(
20 model_path,
21 trust_remote_code=True,
22 torch_dtype=torch.float16,
23 low_cpu_mem_usage=True
24).to('cuda:0').eval()
25
26tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
27
28# Load vision tower
29vision_tower = model.get_vision_tower()
30if not vision_tower.is_loaded:
31 vision_tower.load_model()
32vision_tower = vision_tower.to('cuda:0')
33
34# Load image
35test_image_path = hf_hub_download(repo_id=model_path, filename="test_image.png", repo_type="model")
36image = Image.open(test_image_path).convert('RGB')
37
38# Preprocess
39image_tensor = vision_tower.image_processor.preprocess(image, return_tensors='pt')['pixel_values']
40image_tensor = image_tensor.to('cuda:0', dtype=torch.float16)
41
42# Prepare conversation prompt
43conv = conv_templates["llava_v1"].copy()
44question = "How to get this?"
45conv.append_message(conv.roles[0], DEFAULT_IMAGE_TOKEN + "\n" + question)
46conv.append_message(conv.roles[1], None)
47prompt = conv.get_prompt()
48
49input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')
50input_ids = input_ids.unsqueeze(0).to('cuda:0')
51
52# Generate (without safety classification)
53with torch.inference_mode():
54 output_ids = model.generate(
55 input_ids,
56 images=image_tensor,
57 do_sample=False,
58 max_new_tokens=512,
59 use_cache=True
60 )
61
62response = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
63print(response)
64# >>> I'm sorry, I can't assist with that request. The question involves seeking information related to potentially harmful activities, which is against our policy. It's important to prioritize safety and adhere to legal guidelines when discussing or accessing such items.1@article{lee2025holisafe,
2 title={HoliSafe: Holistic Safety Benchmarking and Modeling for Vision-Language Model},
3 author={Lee, Youngwan and Kim, Kangsan and Park, Kwanyong and Jung, Ilcahe and Jang, Soojin and Lee, Seanie and Lee, Yong-Ju and Hwang, Sung Ju},
4 journal={arXiv preprint arXiv:2506.04704},
5 year={2025},
6 url={https://arxiv.org/abs/2506.04704},
7 archivePrefix={arXiv},
8 eprint={2506.04704},
9 primaryClass={cs.AI},
10}