Views
No views yet
ollama create and only supports fp16.ollama run huihui_ai/gemma3n-abliterated:e2b-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-E2B-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 Vibrant Garden Scene: A Close-Up of a Busy Bee
83 #
84 # This image is a delightful close-up shot showcasing a charming bee in full swing, visiting a beautiful daisy-like flower in a garden. Here's a detailed breakdown:
85 #
86 # **Overall Composition:**
87 #
88 # The image is divided into three main sections: a large central focus on a pink flower, a smaller top section indicating another pink flower, and a bottom right section highlighting a vibrant red flower. This creates a sense of a bustling garden scene.
89 #
90 # **Central Focus: The Mighty Bee on a Pink Daisy:**
91 #
92 # * **The Bee:** The star of the show is a plump, fuzzy bee positioned prominently on a bright pink daisy.
93 # * **Body:** The bee has a dark, almost black body with a yellow band across its abdomen. Its wings are visible, slightly spread, giving it a charming "flying" look.
94 # * **Wings:** It has a distinctive crown of small, white and black stripes.
95 # * **Position:** The bee is centered on a large, open flower head, often called a daisy, making it easily identifiable.
96 # * **The Daisy:**
97 # * **Color:** A vibrant pink color dominates the central area.
98 # * **Petals:** The daisy has four distinct, rounded petals, each with a subtle inner line for definition.
99 # * **Size:** It's a generous size, with a yellow center and a green background.
100 # * **Variety:** A smaller version of the same daisy is placed above, allowing for easy comparison.
101 #
102 # **Background Details:**
103 #
104 # * **Background:** The background is divided into two rows of flowers, creating a visually appealing layering effect.
105 # * **Upper Row (Larger):** A large, bright pink flower dominates the top half of the image.
106 # * **Lower Row (Smaller):** A series of smaller flowers are arranged for a more detailed view.
107 # * **Flower Types:**
108 # * **Red Flower:** A bold red flower is positioned towards the bottom right, with a small white dot on the petals for added visual interest.
109 # * **Smaller Pink Flowers:** Several smaller pink flowers are arranged around the main crop, creating a sense of a dense garden.
110 # * **Brown Buds:** A cluster of brown buds is placed towards the bottom left, with a smaller pink flower peeking out.
111 #
112 # **Overall Style:**
113 #
114 # The image has a charming, slightly rustic feel, often used for illustrating items or creating a consistent visual style. The use of a light background makes the flowers and bee easily legible.
115 #
116 # **In summary:**
117 #
118 # This is a delightful image highlighting the busy life of a bee in a thriving garden. It's a vibrant scene, well-organized, and easily readable, making it perfect for any "garden" enthusiast!
119
120 bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge