Views
No views yet
ollama create and only supports fp16.ollama run huihui_ai/gemma3n-abliterated:e4b-fp16
transformers library:1
2from transformers import AutoProcessor, Gemma3nForConditionalGeneration
3from transformers.models.gemma3n.modeling_gemma3n import Gemma3nTextDecoderLayer
4from PIL import Image
5import requests
6import torch
7import jaxtyping
8import einops
9import base64
10
11model_id = "google/gemma-3n-E4B-it"
12
13model = Gemma3nForConditionalGeneration.from_pretrained(model_id, device_map="cuda", torch_dtype=torch.bfloat16,).eval()
14
15#refusal_dir= torch.load(model_id + "/final_refusal_dirs-16.pt", map_location='cpu', weights_only=True)
16#
17#refusal_dir = refusal_dir.to(model.device)
18#refusal_dir = refusal_dir.to(torch.bfloat16)
19#
20#def direction_ablation_hook(activation: jaxtyping.Float[torch.Tensor, "... d_act"],
21# direction: jaxtyping.Float[torch.Tensor, "d_act"]):
22# proj = einops.einsum(activation, direction.view(-1, 1), '... d_act, d_act single -> ... single') * direction
23# return activation - proj
24#
25#class AblationDecoderLayer(Gemma3nTextDecoderLayer):
26# def __init__(self, original_layer, config, layer_idx, refusal_dir):
27# super(AblationDecoderLayer, self).__init__(config, layer_idx)
28# self.original_layer = original_layer
29# self.refusal_dir = refusal_dir
30#
31# def forward(self, *args, **kwargs):
32# hidden_states = args[0]
33# ablated = direction_ablation_hook(hidden_states, self.refusal_dir.to(hidden_states.device)).to(hidden_states.device)
34# args = (ablated,) + args[1:]
35# return self.original_layer.forward(*args, **kwargs)
36#
37#for idx in range(len(model.model.language_model.layers)):
38# model.model.language_model.layers[idx] = AblationDecoderLayer(model.model.language_model.layers[idx], model.config.text_config, idx, refusal_dir)
39
40processor = AutoProcessor.from_pretrained(model_id)
41
42# https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg
43image_path = model_id + "/bee.jpg"
44
45with open(image_path, "rb") as image_file:
46 encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
47 image_type = "image/jpeg" if image_path.endswith(".jpg") else "image/png"
48 data_uri = f"data:{image_type};base64,{encoded_string}"
49
50 messages = [
51 {
52 "role": "system",
53 "content": [{"type": "text", "text": "You are a helpful assistant."}]
54 },
55 {
56 "role": "user",
57 "content": [
58 {"type": "image", "image": data_uri},
59 {"type": "text", "text": "Describe this image in detail."}
60 ]
61 }
62 ]
63
64 inputs = processor.apply_chat_template(
65 messages,
66 add_generation_prompt=True,
67 tokenize=True,
68 return_dict=True,
69 return_tensors="pt",
70 ).to(model.device, dtype=torch.bfloat16)
71
72 input_len = inputs["input_ids"].shape[-1]
73
74 with torch.inference_mode():
75 generation = model.generate(**inputs, max_new_tokens=1024, do_sample=True)
76 generation = generation[0][input_len:]
77
78 decoded = processor.decode(generation, skip_special_tokens=True)
79 print(decoded)
80
81
82 # ## A Close-Up of a Busy Bumblebee on a Pink Cosmos Flower
83 #
84 # This image is a charming, close-up shot of a vibrant pink cosmos flower, with a cute bumblebee taking center stage!
85 #
86 # **Overall Composition:**
87 #
88 # The photograph is well-composed, focusing primarily on a single, large cosmos flower with several other blooms scattered in the background. It has a slightly elevated perspective, making the subject feel quite prominent and engaging.
89 #
90 # **The Main Subject - The Pink Cosmos:**
91 #
92 # * **Color:** The star of the show is a beautiful, bright pink cosmos flower. The petals are a lovely shade, ranging from a slightly lighter to a deeper rose hue.
93 # * **Shape:** The flower is roughly circular with 5 distinct petals radiating from a central disc. The petals are quite full and have a slightly pointed tip.
94 # * **Details:** The central disc of the flower is a sunny yellow, adding a lovely contrast. The edges of the petals have a slight ruffled look, giving the flower some personality.
95 #
96 # **The Bumblebee - A Busy Friend:**
97 #
98 # * **Position:** A charming bumblebee is perched right in the middle of the pink flower, giving it a welcoming and lively feel.
99 # * **Size & Color:** The bee is a classic black and yellow mix, with a fuzzy body. It's a good-sized bee, making it easily noticeable.
100 # * **Pose:** The bee is positioned slightly diagonally, ensuring the viewer can see its head and legs clearly.
101 #
102 # **Background Elements:**
103 #
104 # * **Other Flowers:** Several other cosmos flowers are visible in the background, creating depth and visual interest. Some are slightly out of focus, while others are closer to the camera. These range in color from a lighter pink to a deeper magenta, and even a vibrant red.
105 # * **Green Foliage:** Lush green leaves are visible, adding a natural backdrop to the scene. The leaves are fairly large and contribute to the overall cheerful aesthetic.
106 # * **Rustic Details:** Scattered throughout are some dried flower heads, hinting at the abundance of cosmos plants in the garden.
107 #
108 # **Overall Impression:**
109 #
110 # The image is bright, cheerful, and full of life! The combination of the pink cosmos and the adorable bumblebee creates a delightful scene, perfect for anyone who loves gardening or insects. It's a clear and well-lit shot, making it a delightful visual treat.
111 #
112 # In summary, this image captures a happy little world, where a diligent bumblebee is hard at work on a beautiful pink cosmos flower!```
113 bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge