Spaces:
Running
on
Zero
Running
on
Zero
added text models
Browse files- app.py +15 -9
- app_text.py +304 -0
- backbone_text.py +239 -0
app.py
CHANGED
@@ -20,7 +20,7 @@ import time
|
|
20 |
import threading
|
21 |
import os
|
22 |
|
23 |
-
from backbone import extract_features,
|
24 |
from backbone import MODEL_DICT, LAYER_DICT, RES_DICT
|
25 |
from ncut_pytorch import NCUT, eigenvector_to_rgb
|
26 |
|
@@ -66,7 +66,7 @@ def compute_ncut(
|
|
66 |
):
|
67 |
logging_str = ""
|
68 |
|
69 |
-
num_nodes = np.prod(features.shape[
|
70 |
if num_nodes / 2 < num_eig:
|
71 |
# raise gr.Error("Number of eigenvectors should be less than half the number of nodes.")
|
72 |
gr.Warning("Number of eigenvectors should be less than half the number of nodes.\n" f"Setting num_eig to {num_nodes // 2 - 1}.")
|
@@ -100,7 +100,7 @@ def compute_ncut(
|
|
100 |
)
|
101 |
logging_str += f"{embedding_method} time: {time.time() - start:.2f}s\n"
|
102 |
|
103 |
-
rgb = rgb.reshape(features.shape[
|
104 |
return rgb, logging_str, eigvecs
|
105 |
|
106 |
|
@@ -584,7 +584,7 @@ def make_output_images_section():
|
|
584 |
return output_gallery
|
585 |
|
586 |
def make_parameters_section():
|
587 |
-
gr.Markdown(
|
588 |
from backbone import get_all_model_names
|
589 |
model_names = get_all_model_names()
|
590 |
model_dropdown = gr.Dropdown(model_names, label="Backbone", value="DiNO(dino_vitb8)", elem_id="model_name")
|
@@ -605,6 +605,7 @@ def make_parameters_section():
|
|
605 |
model_dropdown.change(fn=change_layer_slider, inputs=model_dropdown, outputs=[layer_slider, node_type_dropdown])
|
606 |
|
607 |
with gr.Accordion("➡️ Click to expand: more parameters", open=False):
|
|
|
608 |
affinity_focal_gamma_slider = gr.Slider(0.01, 1, step=0.01, label="NCUT: Affinity focal gamma", value=0.5, elem_id="affinity_focal_gamma", info="decrease for shaper segmentation")
|
609 |
num_sample_ncut_slider = gr.Slider(100, 50000, step=100, label="NCUT: num_sample", value=10000, elem_id="num_sample_ncut", info="Nyström approximation")
|
610 |
sampling_method_dropdown = gr.Dropdown(["fps", "random"], label="NCUT: Sampling method", value="fps", elem_id="sampling_method", info="Nyström approximation")
|
@@ -822,11 +823,12 @@ with demo:
|
|
822 |
)
|
823 |
|
824 |
with gr.Tab('Text'):
|
825 |
-
|
826 |
-
|
827 |
-
|
828 |
-
|
829 |
-
|
|
|
830 |
with gr.Tab('Compare Models'):
|
831 |
def add_one_model(i_model=1):
|
832 |
with gr.Column(scale=5, min_width=200) as col:
|
@@ -897,7 +899,11 @@ with demo:
|
|
897 |
|
898 |
|
899 |
if USE_HUGGINGFACE_SPACE:
|
|
|
|
|
|
|
900 |
threading.Thread(target=download_all_models).start()
|
|
|
901 |
threading.Thread(target=download_all_datasets).start()
|
902 |
demo.launch()
|
903 |
else:
|
|
|
20 |
import threading
|
21 |
import os
|
22 |
|
23 |
+
from backbone import extract_features, get_model
|
24 |
from backbone import MODEL_DICT, LAYER_DICT, RES_DICT
|
25 |
from ncut_pytorch import NCUT, eigenvector_to_rgb
|
26 |
|
|
|
66 |
):
|
67 |
logging_str = ""
|
68 |
|
69 |
+
num_nodes = np.prod(features.shape[:-1])
|
70 |
if num_nodes / 2 < num_eig:
|
71 |
# raise gr.Error("Number of eigenvectors should be less than half the number of nodes.")
|
72 |
gr.Warning("Number of eigenvectors should be less than half the number of nodes.\n" f"Setting num_eig to {num_nodes // 2 - 1}.")
|
|
|
100 |
)
|
101 |
logging_str += f"{embedding_method} time: {time.time() - start:.2f}s\n"
|
102 |
|
103 |
+
rgb = rgb.reshape(features.shape[:-1] + (3,))
|
104 |
return rgb, logging_str, eigvecs
|
105 |
|
106 |
|
|
|
584 |
return output_gallery
|
585 |
|
586 |
def make_parameters_section():
|
587 |
+
gr.Markdown("### Parameters <a style='color: #0044CC;' href='https://ncut-pytorch.readthedocs.io/en/latest/how_to_get_better_segmentation/' target='_blank'>Help</a>")
|
588 |
from backbone import get_all_model_names
|
589 |
model_names = get_all_model_names()
|
590 |
model_dropdown = gr.Dropdown(model_names, label="Backbone", value="DiNO(dino_vitb8)", elem_id="model_name")
|
|
|
605 |
model_dropdown.change(fn=change_layer_slider, inputs=model_dropdown, outputs=[layer_slider, node_type_dropdown])
|
606 |
|
607 |
with gr.Accordion("➡️ Click to expand: more parameters", open=False):
|
608 |
+
gr.Markdown("<a href='https://ncut-pytorch.readthedocs.io/en/latest/how_to_get_better_segmentation/' target='_blank'>Docs: How to Get Better Segmentation</a>")
|
609 |
affinity_focal_gamma_slider = gr.Slider(0.01, 1, step=0.01, label="NCUT: Affinity focal gamma", value=0.5, elem_id="affinity_focal_gamma", info="decrease for shaper segmentation")
|
610 |
num_sample_ncut_slider = gr.Slider(100, 50000, step=100, label="NCUT: num_sample", value=10000, elem_id="num_sample_ncut", info="Nyström approximation")
|
611 |
sampling_method_dropdown = gr.Dropdown(["fps", "random"], label="NCUT: Sampling method", value="fps", elem_id="sampling_method", info="Nyström approximation")
|
|
|
823 |
)
|
824 |
|
825 |
with gr.Tab('Text'):
|
826 |
+
if USE_HUGGINGFACE_SPACE:
|
827 |
+
from app_text import make_demo
|
828 |
+
else:
|
829 |
+
from draft_gradio_app_text import make_demo
|
830 |
+
make_demo()
|
831 |
+
|
832 |
with gr.Tab('Compare Models'):
|
833 |
def add_one_model(i_model=1):
|
834 |
with gr.Column(scale=5, min_width=200) as col:
|
|
|
899 |
|
900 |
|
901 |
if USE_HUGGINGFACE_SPACE:
|
902 |
+
from backbone import download_all_models
|
903 |
+
threading.Thread(target=download_all_models).start()
|
904 |
+
from backbone_text import download_all_models
|
905 |
threading.Thread(target=download_all_models).start()
|
906 |
+
|
907 |
threading.Thread(target=download_all_datasets).start()
|
908 |
demo.launch()
|
909 |
else:
|
app_text.py
ADDED
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# %%
|
2 |
+
USE_HUGGINGFACE_SPACE = True
|
3 |
+
|
4 |
+
if USE_HUGGINGFACE_SPACE: # huggingface ZeroGPU, dynamic GPU allocation
|
5 |
+
try:
|
6 |
+
import spaces
|
7 |
+
except ImportError:
|
8 |
+
USE_HUGGINGFACE_SPACE = False # run on local machine
|
9 |
+
|
10 |
+
import gradio as gr
|
11 |
+
|
12 |
+
import torch
|
13 |
+
import torch.nn.functional as F
|
14 |
+
from PIL import Image
|
15 |
+
import numpy as np
|
16 |
+
import time
|
17 |
+
import threading
|
18 |
+
import os
|
19 |
+
import matplotlib.pyplot as plt
|
20 |
+
import matplotlib.colors as mcolors
|
21 |
+
import numpy as np
|
22 |
+
|
23 |
+
from ncut_pytorch import NCUT, eigenvector_to_rgb
|
24 |
+
|
25 |
+
from backbone_text import MODEL_DICT as TEXT_MODEL_DICT
|
26 |
+
from backbone_text import LAYER_DICT as TEXT_LAYER_DICT
|
27 |
+
|
28 |
+
def compute_ncut(
|
29 |
+
features,
|
30 |
+
num_eig=100,
|
31 |
+
num_sample_ncut=10000,
|
32 |
+
affinity_focal_gamma=0.3,
|
33 |
+
knn_ncut=10,
|
34 |
+
knn_tsne=10,
|
35 |
+
embedding_method="UMAP",
|
36 |
+
num_sample_tsne=300,
|
37 |
+
perplexity=150,
|
38 |
+
n_neighbors=150,
|
39 |
+
min_dist=0.1,
|
40 |
+
sampling_method="fps",
|
41 |
+
metric="cosine",
|
42 |
+
):
|
43 |
+
logging_str = ""
|
44 |
+
print("running ncut")
|
45 |
+
print(features.shape)
|
46 |
+
num_nodes = np.prod(features.shape[:-1])
|
47 |
+
if num_nodes / 2 < num_eig:
|
48 |
+
# raise gr.Error("Number of eigenvectors should be less than half the number of nodes.")
|
49 |
+
gr.Warning("Number of eigenvectors should be less than half the number of nodes.\n" f"Setting num_eig to {num_nodes // 2 - 1}.")
|
50 |
+
num_eig = num_nodes // 2 - 1
|
51 |
+
logging_str += f"Number of eigenvectors should be less than half the number of nodes.\n" f"Setting num_eig to {num_nodes // 2 - 1}.\n"
|
52 |
+
|
53 |
+
start = time.time()
|
54 |
+
eigvecs, eigvals = NCUT(
|
55 |
+
num_eig=num_eig,
|
56 |
+
num_sample=num_sample_ncut,
|
57 |
+
device="cuda" if torch.cuda.is_available() else "cpu",
|
58 |
+
affinity_focal_gamma=affinity_focal_gamma,
|
59 |
+
knn=knn_ncut,
|
60 |
+
sample_method=sampling_method,
|
61 |
+
distance=metric,
|
62 |
+
normalize_features=False,
|
63 |
+
).fit_transform(features.reshape(-1, features.shape[-1]))
|
64 |
+
# print(f"NCUT time: {time.time() - start:.2f}s")
|
65 |
+
logging_str += f"NCUT time: {time.time() - start:.2f}s\n"
|
66 |
+
|
67 |
+
start = time.time()
|
68 |
+
_, rgb = eigenvector_to_rgb(
|
69 |
+
eigvecs,
|
70 |
+
method=embedding_method,
|
71 |
+
num_sample=num_sample_tsne,
|
72 |
+
perplexity=perplexity,
|
73 |
+
n_neighbors=n_neighbors,
|
74 |
+
min_distance=min_dist,
|
75 |
+
knn=knn_tsne,
|
76 |
+
device="cuda" if torch.cuda.is_available() else "cpu",
|
77 |
+
)
|
78 |
+
logging_str += f"{embedding_method} time: {time.time() - start:.2f}s\n"
|
79 |
+
|
80 |
+
rgb = rgb.reshape(features.shape[:-1] + (3,))
|
81 |
+
return rgb, logging_str, eigvecs
|
82 |
+
|
83 |
+
|
84 |
+
def make_plot(token_texts, rgb, num_lines=50, title=""):
|
85 |
+
fig, ax = plt.subplots(figsize=(10, 20))
|
86 |
+
# Define the colors
|
87 |
+
# fill nan with 0
|
88 |
+
rgb = np.nan_to_num(rgb)
|
89 |
+
colors = [mcolors.rgb2hex(rgb[i]) for i in range(len(token_texts))]
|
90 |
+
|
91 |
+
# Split the sentence into words
|
92 |
+
words = token_texts
|
93 |
+
|
94 |
+
y_pos = 0.96
|
95 |
+
x_pos = 0.0
|
96 |
+
max_word_length = max(len(word) for word in words)
|
97 |
+
count = 0
|
98 |
+
for word, color in zip(words, colors):
|
99 |
+
if '\n' in word:
|
100 |
+
word = word.replace('\n', '')
|
101 |
+
y_pos -= 0.025
|
102 |
+
x_pos = 0.0
|
103 |
+
count += 1
|
104 |
+
if count >= num_lines:
|
105 |
+
break
|
106 |
+
|
107 |
+
text_color = 'black' if sum(mcolors.hex2color(color)) > 1.3 else 'white' # Choose text color based on background color
|
108 |
+
# text_color = 'black'
|
109 |
+
txt = ax.text(x_pos, y_pos, word, color=text_color, fontsize=12, bbox=dict(facecolor=color, alpha=0.8, edgecolor='none', pad=2))
|
110 |
+
txt_width = txt.get_window_extent().width / (fig.dpi * fig.get_size_inches()[0]) # Calculate the width of the text in inches
|
111 |
+
|
112 |
+
x_pos += txt_width * 1.2 + 0.01 # Adjust the spacing between words
|
113 |
+
|
114 |
+
if x_pos > 0.97:
|
115 |
+
y_pos -= 0.025
|
116 |
+
x_pos = 0.0
|
117 |
+
count += 1
|
118 |
+
if count >= num_lines:
|
119 |
+
break
|
120 |
+
# break
|
121 |
+
|
122 |
+
# Remove the axis ticks and spines
|
123 |
+
ax.set_xticks([])
|
124 |
+
ax.set_yticks([])
|
125 |
+
ax.spines['top'].set_visible(False)
|
126 |
+
ax.spines['right'].set_visible(False)
|
127 |
+
ax.spines['bottom'].set_visible(False)
|
128 |
+
ax.spines['left'].set_visible(False)
|
129 |
+
|
130 |
+
ax.set_title(title, fontsize=20)
|
131 |
+
|
132 |
+
return fig
|
133 |
+
|
134 |
+
|
135 |
+
|
136 |
+
def ncut_run(
|
137 |
+
model,
|
138 |
+
text,
|
139 |
+
model_name,
|
140 |
+
layer=-1,
|
141 |
+
num_eig=100,
|
142 |
+
node_type="block",
|
143 |
+
affinity_focal_gamma=0.3,
|
144 |
+
num_sample_ncut=10000,
|
145 |
+
knn_ncut=10,
|
146 |
+
embedding_method="UMAP",
|
147 |
+
num_sample_tsne=1000,
|
148 |
+
knn_tsne=10,
|
149 |
+
perplexity=500,
|
150 |
+
n_neighbors=500,
|
151 |
+
min_dist=0.1,
|
152 |
+
sampling_method="fps",
|
153 |
+
):
|
154 |
+
logging_str = ""
|
155 |
+
if perplexity >= num_sample_tsne or n_neighbors >= num_sample_tsne:
|
156 |
+
# raise gr.Error("Perplexity must be less than the number of samples for t-SNE.")
|
157 |
+
gr.Warning("Perplexity/n_neighbors must be less than the number of samples.\n" f"Setting Perplexity to {num_sample_tsne-1}.")
|
158 |
+
logging_str += f"Perplexity/n_neighbors must be less than the number of samples.\n" f"Setting Perplexity to {num_sample_tsne-1}.\n"
|
159 |
+
perplexity = num_sample_tsne - 1
|
160 |
+
n_neighbors = num_sample_tsne - 1
|
161 |
+
|
162 |
+
if torch.cuda.is_available():
|
163 |
+
torch.cuda.empty_cache()
|
164 |
+
|
165 |
+
node_type = node_type.split(":")[0].strip()
|
166 |
+
|
167 |
+
model = model.to("cuda" if torch.cuda.is_available() else "cpu")
|
168 |
+
|
169 |
+
start = time.time()
|
170 |
+
out = model(text)
|
171 |
+
features = out[node_type][layer-1].squeeze(0).detach().float()
|
172 |
+
token_texts = out["token_texts"]
|
173 |
+
|
174 |
+
if perplexity >= features.shape[0] or n_neighbors >= features.shape[0]:
|
175 |
+
# raise gr.Error("Perplexity must be less than the number of samples.")
|
176 |
+
gr.Warning("Perplexity/n_neighbors must be less than the number of samples.\n" f"Setting Perplexity to {features.shape[0]-1}.")
|
177 |
+
logging_str += f"Perplexity/n_neighbors must be less than the number of samples.\n" f"Setting Perplexity to {features.shape[0]-1}.\n"
|
178 |
+
perplexity = features.shape[0] - 1
|
179 |
+
n_neighbors = features.shape[0] - 1
|
180 |
+
|
181 |
+
# print(f"Feature extraction time (gpu): {time.time() - start:.2f}s")
|
182 |
+
logging_str += f"Backbone time: {time.time() - start:.2f}s\n"
|
183 |
+
|
184 |
+
rgb, _logging_str, _ = compute_ncut(
|
185 |
+
features,
|
186 |
+
num_eig=num_eig,
|
187 |
+
num_sample_ncut=num_sample_ncut,
|
188 |
+
affinity_focal_gamma=affinity_focal_gamma,
|
189 |
+
knn_ncut=knn_ncut,
|
190 |
+
knn_tsne=knn_tsne,
|
191 |
+
num_sample_tsne=num_sample_tsne,
|
192 |
+
embedding_method=embedding_method,
|
193 |
+
perplexity=perplexity,
|
194 |
+
n_neighbors=n_neighbors,
|
195 |
+
min_dist=min_dist,
|
196 |
+
sampling_method=sampling_method,
|
197 |
+
)
|
198 |
+
logging_str += _logging_str
|
199 |
+
|
200 |
+
title = f"{model_name}, Layer {layer}, {node_type}"
|
201 |
+
fig = make_plot(token_texts, rgb, title=title)
|
202 |
+
return fig, logging_str
|
203 |
+
|
204 |
+
def _ncut_run(*args, **kwargs):
|
205 |
+
try:
|
206 |
+
ret = ncut_run(*args, **kwargs)
|
207 |
+
if torch.cuda.is_available():
|
208 |
+
torch.cuda.empty_cache()
|
209 |
+
return ret
|
210 |
+
except Exception as e:
|
211 |
+
gr.Error(str(e))
|
212 |
+
if torch.cuda.is_available():
|
213 |
+
torch.cuda.empty_cache()
|
214 |
+
return None, "Error: " + str(e)
|
215 |
+
|
216 |
+
if USE_HUGGINGFACE_SPACE:
|
217 |
+
@spaces.GPU(duration=30)
|
218 |
+
def __ncut_run(*args, **kwargs):
|
219 |
+
return _ncut_run(*args, **kwargs)
|
220 |
+
else:
|
221 |
+
def __ncut_run(*args, **kwargs):
|
222 |
+
return _ncut_run(*args, **kwargs)
|
223 |
+
|
224 |
+
def real_run(model_name, text, layer, node_type, num_eig, affinity_focal_gamma, num_sample_ncut, knn_ncut, embedding_method, num_sample_tsne, knn_tsne, perplexity, n_neighbors, min_dist, sampling_method):
|
225 |
+
model = TEXT_MODEL_DICT[model_name]()
|
226 |
+
return __ncut_run(model, text, model_name, layer, num_eig, node_type,
|
227 |
+
affinity_focal_gamma, num_sample_ncut, knn_ncut, embedding_method,
|
228 |
+
num_sample_tsne, knn_tsne, perplexity, n_neighbors, min_dist, sampling_method)
|
229 |
+
|
230 |
+
lines = \
|
231 |
+
"""1. The majestic giraffe, with its towering height and distinctive long neck, roams the savannas of Africa. These gentle giants use their elongated tongues to pluck leaves from the tallest trees, making them well-adapted to their environment. Their unique coat patterns, much like human fingerprints, are unique to each individual.
|
232 |
+
2. Penguins, the tuxedoed birds of the Antarctic, are expert swimmers and divers. These flightless seabirds rely on their dense, waterproof feathers and streamlined bodies to propel through icy waters in search of fish, krill, and other marine life. Their huddled colonies and amusing waddles make them a favorite among wildlife enthusiasts.
|
233 |
+
3. The mighty African elephant, the largest land mammal, is revered for its intelligence and strong family bonds. These gentle giants use their versatile trunks for various tasks, from drinking and feeding to communicating and greeting one another. Their massive ears and wrinkled skin make them an iconic symbol of the African wilderness.
|
234 |
+
4. The colorful and flamboyant peacock, native to Asia, is known for its stunning iridescent plumage. During mating season, the males fan out their magnificent train of feathers, adorned with intricate eye-like patterns, in an elaborate courtship display to attract potential mates, making them a true spectacle of nature.
|
235 |
+
5. The sleek and powerful cheetah, the fastest land animal, is built for speed and agility. With its distinctive black tear-like markings and slender body, this feline predator can reach top speeds of up to 70 mph during short bursts, allowing it to chase down its prey with remarkable precision.
|
236 |
+
6. The playful and intelligent dolphin, a highly social marine mammal, is known for its friendly demeanor and impressive acrobatic abilities. These aquatic creatures use echolocation to navigate and hunt, and their complex communication systems have long fascinated researchers studying their intricate social structures and cognitive abilities.
|
237 |
+
7. The majestic bald eagle, the national emblem of the United States, soars high above with its distinctive white head and tail feathers. These powerful raptors are skilled hunters, swooping down from great heights to catch fish and other prey with their sharp talons, making them an iconic symbol of strength and freedom.
|
238 |
+
8. The industrious beaver, nature's skilled engineers, are known for their remarkable ability to construct dams and lodges using their sharp incisors and webbed feet. These semiaquatic rodents play a crucial role in shaping their aquatic ecosystems, creating habitats for numerous other species while demonstrating their ingenuity and perseverance.
|
239 |
+
9. The vibrant and enchanting hummingbird, one of the smallest bird species, is a true marvel of nature. With their rapidly flapping wings and ability to hover in mid-air, these tiny feathered creatures are expert pollinators, flitting from flower to flower in search of nectar and playing a vital role in plant reproduction.
|
240 |
+
10. The majestic polar bear, the apex predator of the Arctic, is perfectly adapted to its icy environment. With its thick insulating fur and specialized paws for gripping the ice, this powerful carnivore relies on its exceptional hunting skills and keen senses to locate and capture seals, its primary prey, in the harsh Arctic landscape.
|
241 |
+
"""
|
242 |
+
|
243 |
+
def make_demo():
|
244 |
+
with gr.Row():
|
245 |
+
with gr.Column(scale=5, min_width=200):
|
246 |
+
gr.Markdown("### Input Text")
|
247 |
+
placeholder = lines
|
248 |
+
input_text = gr.Text(value=placeholder, label="Input Text", placeholder="Type here", lines=12)
|
249 |
+
submit_button = gr.Button("🔴 RUN", elem_id="submit_button", variant='primary')
|
250 |
+
clear_button = gr.Button("🗑️Clear", elem_id='clear_button', variant='stop')
|
251 |
+
with gr.Column(scale=5, min_width=200):
|
252 |
+
gr.Markdown("### Parameters <a style='color: #0044CC;' href='https://ncut-pytorch.readthedocs.io/en/latest/how_to_get_better_segmentation/' target='_blank'>Help</a>")
|
253 |
+
model_name = gr.Dropdown(list(TEXT_MODEL_DICT.keys()), label="Model", value="meta-llama/Meta-Llama-3.1-8B")
|
254 |
+
layer = gr.Slider(1, 32, step=1, value=32, label="Layer")
|
255 |
+
node_type = gr.Dropdown(["attn: attention output", "mlp: mlp output", "block: sum of residual"], label="Node Type", value="block: sum of residual")
|
256 |
+
num_eig = gr.Slider(minimum=1, maximum=1000, step=1, value=100, label="Number of Eigenvectors")
|
257 |
+
|
258 |
+
with gr.Accordion("➡️ Click to expand: more parameters", open=False):
|
259 |
+
gr.Markdown("<a href='https://ncut-pytorch.readthedocs.io/en/latest/how_to_get_better_segmentation/' target='_blank'>Docs: How to Get Better Segmentation</a>")
|
260 |
+
affinity_focal_gamma = gr.Slider(minimum=0.1, maximum=1.0, step=0.1, value=0.3, label="Affinity Focal Gamma")
|
261 |
+
num_sample_ncut = gr.Slider(minimum=100, maximum=50000, step=100, value=10000, label="Number of Samples for NCUT")
|
262 |
+
sampling_method_dropdown = gr.Dropdown(["fps", "random"], label="Sampling method", value="fps", elem_id="sampling_method")
|
263 |
+
knn_ncut = gr.Slider(minimum=1, maximum=100, step=1, value=10, label="KNN for NCUT")
|
264 |
+
embedding_method_dropdown = gr.Dropdown(["tsne_3d", "umap_3d", "umap_shpere", "tsne_2d", "umap_2d"], label="Coloring method", value="tsne_3d", elem_id="embedding_method")
|
265 |
+
num_sample_tsne_slider = gr.Slider(100, 10000, step=100, label="t-SNE/UMAP: num_sample", value=300, elem_id="num_sample_tsne", info="Nyström approximation")
|
266 |
+
knn_tsne_slider = gr.Slider(1, 100, step=1, label="t-SNE/UMAP: KNN", value=10, elem_id="knn_tsne", info="Nyström approximation")
|
267 |
+
perplexity_slider = gr.Slider(10, 1000, step=10, label="t-SNE: Perplexity", value=150, elem_id="perplexity")
|
268 |
+
n_neighbors_slider = gr.Slider(10, 1000, step=10, label="UMAP: n_neighbors", value=150, elem_id="n_neighbors")
|
269 |
+
min_dist_slider = gr.Slider(0.1, 1, step=0.1, label="UMAP: min_dist", value=0.1, elem_id="min_dist")
|
270 |
+
logging_str = gr.Textbox("", label="Logging Information", placeholder="Logging",)
|
271 |
+
|
272 |
+
with gr.Row():
|
273 |
+
gr.Markdown("### Output Embedding")
|
274 |
+
output_image = gr.Plot(label="NCUT Output", min_width=1920)
|
275 |
+
|
276 |
+
def change_layer_slider(model_name):
|
277 |
+
layer_dict = TEXT_LAYER_DICT
|
278 |
+
if model_name in layer_dict:
|
279 |
+
value = layer_dict[model_name]
|
280 |
+
return (gr.Slider(1, value, step=1, label="Backbone: Layer index", value=value, elem_id="layer", visible=True),
|
281 |
+
gr.Dropdown(["attn: attention output", "mlp: mlp output", "block: sum of residual"], label="Backbone: Layer type", value="block: sum of residual", elem_id="node_type", info="which feature to take from each layer?"))
|
282 |
+
else:
|
283 |
+
value = 12
|
284 |
+
return (gr.Dropdown(["attn: attention output", "mlp: mlp output", "block: sum of residual"], label="Backbone: Layer type", value="block: sum of residual", elem_id="node_type", info="which feature to take from each layer?"),
|
285 |
+
gr.Slider(1, value, step=1, label="Backbone: Layer index", value=value, elem_id="layer", visible=True))
|
286 |
+
model_name.change(fn=change_layer_slider, inputs=model_name, outputs=[layer, node_type])
|
287 |
+
|
288 |
+
clear_button.click(lambda x: (None, None), outputs=[input_text, output_image])
|
289 |
+
submit_button.click(real_run, inputs=[
|
290 |
+
model_name, input_text, layer, node_type, num_eig,
|
291 |
+
affinity_focal_gamma, num_sample_ncut, knn_ncut,
|
292 |
+
embedding_method_dropdown, num_sample_tsne_slider,
|
293 |
+
knn_tsne_slider, perplexity_slider, n_neighbors_slider,
|
294 |
+
min_dist_slider, sampling_method_dropdown
|
295 |
+
],
|
296 |
+
outputs=[output_image, logging_str],
|
297 |
+
)
|
298 |
+
|
299 |
+
|
300 |
+
|
301 |
+
if __name__ == "__main__":
|
302 |
+
with gr.Blocks() as demo:
|
303 |
+
make_demo()
|
304 |
+
demo.launch(share=True)
|
backbone_text.py
ADDED
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# %%
|
2 |
+
#
|
3 |
+
from typing import List, Union
|
4 |
+
import torch
|
5 |
+
import os
|
6 |
+
from torch import nn
|
7 |
+
from typing import Optional, Tuple
|
8 |
+
|
9 |
+
from functools import partial
|
10 |
+
|
11 |
+
MODEL_DICT = {}
|
12 |
+
LAYER_DICT = {}
|
13 |
+
|
14 |
+
class Llama(nn.Module):
|
15 |
+
def __init__(self, model_id="meta-llama/Meta-Llama-3.1-8B"):
|
16 |
+
super().__init__()
|
17 |
+
|
18 |
+
import transformers
|
19 |
+
|
20 |
+
access_token = os.getenv("HF_ACCESS_TOKEN")
|
21 |
+
if access_token is None:
|
22 |
+
raise ValueError("HF_ACCESS_TOKEN environment variable must be set")
|
23 |
+
|
24 |
+
pipeline = transformers.pipeline(
|
25 |
+
"text-generation",
|
26 |
+
model=model_id,
|
27 |
+
model_kwargs={"torch_dtype": torch.bfloat16},
|
28 |
+
token=access_token,
|
29 |
+
device='cpu',
|
30 |
+
)
|
31 |
+
|
32 |
+
tokenizer = pipeline.tokenizer
|
33 |
+
model = pipeline.model
|
34 |
+
|
35 |
+
def new_forward(
|
36 |
+
self,
|
37 |
+
hidden_states: torch.Tensor,
|
38 |
+
attention_mask: Optional[torch.Tensor] = None,
|
39 |
+
position_ids: Optional[torch.LongTensor] = None,
|
40 |
+
past_key_value = None,
|
41 |
+
output_attentions: Optional[bool] = False,
|
42 |
+
use_cache: Optional[bool] = False,
|
43 |
+
cache_position: Optional[torch.LongTensor] = None,
|
44 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
|
45 |
+
**kwargs,
|
46 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
47 |
+
residual = hidden_states
|
48 |
+
|
49 |
+
hidden_states = self.input_layernorm(hidden_states)
|
50 |
+
|
51 |
+
# Self Attention
|
52 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
53 |
+
hidden_states=hidden_states,
|
54 |
+
attention_mask=attention_mask,
|
55 |
+
position_ids=position_ids,
|
56 |
+
past_key_value=past_key_value,
|
57 |
+
output_attentions=output_attentions,
|
58 |
+
use_cache=use_cache,
|
59 |
+
cache_position=cache_position,
|
60 |
+
position_embeddings=position_embeddings,
|
61 |
+
**kwargs,
|
62 |
+
)
|
63 |
+
|
64 |
+
self.attn_output = hidden_states.clone()
|
65 |
+
|
66 |
+
hidden_states = residual + hidden_states
|
67 |
+
|
68 |
+
# Fully Connected
|
69 |
+
residual = hidden_states
|
70 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
71 |
+
hidden_states = self.mlp(hidden_states)
|
72 |
+
|
73 |
+
self.mlp_output = hidden_states.clone()
|
74 |
+
|
75 |
+
hidden_states = residual + hidden_states
|
76 |
+
|
77 |
+
self.block_output = hidden_states.clone()
|
78 |
+
|
79 |
+
outputs = (hidden_states,)
|
80 |
+
|
81 |
+
if output_attentions:
|
82 |
+
outputs += (self_attn_weights,)
|
83 |
+
|
84 |
+
if use_cache:
|
85 |
+
outputs += (present_key_value,)
|
86 |
+
|
87 |
+
return outputs
|
88 |
+
|
89 |
+
# for layer in model.model.layers:
|
90 |
+
# setattr(layer.__class__, "forward", new_forward)
|
91 |
+
# setattr(layer.__class__, "__call__", new_forward)
|
92 |
+
setattr(model.model.layers[0].__class__, "forward", new_forward)
|
93 |
+
setattr(model.model.layers[0].__class__, "__call__", new_forward)
|
94 |
+
|
95 |
+
self.model = model
|
96 |
+
self.tokenizer = tokenizer
|
97 |
+
|
98 |
+
@torch.no_grad()
|
99 |
+
def forward(self, text: str):
|
100 |
+
encoded_input = self.tokenizer(text, return_tensors='pt')
|
101 |
+
device = next(self.model.parameters()).device
|
102 |
+
encoded_input = {k: v.to(device) for k, v in encoded_input.items()}
|
103 |
+
output = self.model(**encoded_input, output_hidden_states=True)
|
104 |
+
|
105 |
+
attn_outputs, mlp_outputs, block_outputs = [], [], []
|
106 |
+
for i, blk in enumerate(self.model.model.layers):
|
107 |
+
attn_outputs.append(blk.attn_output)
|
108 |
+
mlp_outputs.append(blk.mlp_output)
|
109 |
+
block_outputs.append(blk.block_output)
|
110 |
+
|
111 |
+
token_ids = encoded_input['input_ids']
|
112 |
+
token_texts = [self.tokenizer.decode([token_id]) for token_id in token_ids[0]]
|
113 |
+
|
114 |
+
return {"attn": attn_outputs, "mlp": mlp_outputs, "block": block_outputs, "token_texts": token_texts}
|
115 |
+
|
116 |
+
MODEL_DICT["meta-llama/Meta-Llama-3.1-8B"] = partial(Llama, model_id="meta-llama/Meta-Llama-3.1-8B")
|
117 |
+
LAYER_DICT["meta-llama/Meta-Llama-3.1-8B"] = 32
|
118 |
+
MODEL_DICT["meta-llama/Meta-Llama-3-8B"] = partial(Llama, model_id="meta-llama/Meta-Llama-3-8B")
|
119 |
+
LAYER_DICT["meta-llama/Meta-Llama-3-8B"] = 32
|
120 |
+
|
121 |
+
class GPT2(nn.Module):
|
122 |
+
def __init__(self):
|
123 |
+
super().__init__()
|
124 |
+
from transformers import GPT2Tokenizer, GPT2Model
|
125 |
+
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
|
126 |
+
model = GPT2Model.from_pretrained('gpt2')
|
127 |
+
|
128 |
+
def new_forward(
|
129 |
+
self,
|
130 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]],
|
131 |
+
layer_past: Optional[Tuple[torch.Tensor]] = None,
|
132 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
133 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
134 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
135 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
136 |
+
use_cache: Optional[bool] = False,
|
137 |
+
output_attentions: Optional[bool] = False,
|
138 |
+
) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
|
139 |
+
residual = hidden_states
|
140 |
+
hidden_states = self.ln_1(hidden_states)
|
141 |
+
attn_outputs = self.attn(
|
142 |
+
hidden_states,
|
143 |
+
layer_past=layer_past,
|
144 |
+
attention_mask=attention_mask,
|
145 |
+
head_mask=head_mask,
|
146 |
+
use_cache=use_cache,
|
147 |
+
output_attentions=output_attentions,
|
148 |
+
)
|
149 |
+
attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
|
150 |
+
outputs = attn_outputs[1:]
|
151 |
+
# residual connection
|
152 |
+
self.attn_output = attn_output.clone()
|
153 |
+
hidden_states = attn_output + residual
|
154 |
+
|
155 |
+
if encoder_hidden_states is not None:
|
156 |
+
# add one self-attention block for cross-attention
|
157 |
+
if not hasattr(self, "crossattention"):
|
158 |
+
raise ValueError(
|
159 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
|
160 |
+
"cross-attention layers by setting `config.add_cross_attention=True`"
|
161 |
+
)
|
162 |
+
residual = hidden_states
|
163 |
+
hidden_states = self.ln_cross_attn(hidden_states)
|
164 |
+
cross_attn_outputs = self.crossattention(
|
165 |
+
hidden_states,
|
166 |
+
attention_mask=attention_mask,
|
167 |
+
head_mask=head_mask,
|
168 |
+
encoder_hidden_states=encoder_hidden_states,
|
169 |
+
encoder_attention_mask=encoder_attention_mask,
|
170 |
+
output_attentions=output_attentions,
|
171 |
+
)
|
172 |
+
attn_output = cross_attn_outputs[0]
|
173 |
+
# residual connection
|
174 |
+
hidden_states = residual + attn_output
|
175 |
+
outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
|
176 |
+
|
177 |
+
residual = hidden_states
|
178 |
+
hidden_states = self.ln_2(hidden_states)
|
179 |
+
feed_forward_hidden_states = self.mlp(hidden_states)
|
180 |
+
# residual connection
|
181 |
+
self.mlp_output = feed_forward_hidden_states.clone()
|
182 |
+
hidden_states = residual + feed_forward_hidden_states
|
183 |
+
|
184 |
+
if use_cache:
|
185 |
+
outputs = (hidden_states,) + outputs
|
186 |
+
else:
|
187 |
+
outputs = (hidden_states,) + outputs[1:]
|
188 |
+
|
189 |
+
self.block_output = hidden_states.clone()
|
190 |
+
return outputs # hidden_states, present, (attentions, cross_attentions)
|
191 |
+
|
192 |
+
setattr(model.h[0].__class__, "forward", new_forward)
|
193 |
+
|
194 |
+
self.model = model
|
195 |
+
self.tokenizer = tokenizer
|
196 |
+
|
197 |
+
@torch.no_grad()
|
198 |
+
def forward(self, text: str):
|
199 |
+
encoded_input = self.tokenizer(text, return_tensors='pt')
|
200 |
+
device = next(self.model.parameters()).device
|
201 |
+
encoded_input = {k: v.to(device) for k, v in encoded_input.items()}
|
202 |
+
output = self.model(**encoded_input, output_hidden_states=True)
|
203 |
+
|
204 |
+
attn_outputs, mlp_outputs, block_outputs = [], [], []
|
205 |
+
for i, blk in enumerate(self.model.h):
|
206 |
+
attn_outputs.append(blk.attn_output)
|
207 |
+
mlp_outputs.append(blk.mlp_output)
|
208 |
+
block_outputs.append(blk.block_output)
|
209 |
+
|
210 |
+
token_ids = encoded_input['input_ids']
|
211 |
+
token_texts = [self.tokenizer.decode([token_id]) for token_id in token_ids[0]]
|
212 |
+
|
213 |
+
return {"attn": attn_outputs, "mlp": mlp_outputs, "block": block_outputs, "token_texts": token_texts}
|
214 |
+
|
215 |
+
MODEL_DICT["gpt2"] = GPT2
|
216 |
+
LAYER_DICT["gpt2"] = 12
|
217 |
+
|
218 |
+
|
219 |
+
def download_all_models():
|
220 |
+
for model_name in MODEL_DICT:
|
221 |
+
print(f"Downloading {model_name}")
|
222 |
+
try:
|
223 |
+
model = MODEL_DICT[model_name]()
|
224 |
+
except Exception as e:
|
225 |
+
print(f"Error downloading {model_name}: {e}")
|
226 |
+
continue
|
227 |
+
|
228 |
+
|
229 |
+
if __name__ == '__main__':
|
230 |
+
|
231 |
+
model = MODEL_DICT["meta-llama/Meta-Llama-3-8B"]()
|
232 |
+
# model = MODEL_DICT["gpt2"]()
|
233 |
+
text = """
|
234 |
+
1. The majestic giraffe, with its towering height and distinctive long neck, roams the savannas of Africa. These gentle giants use their elongated tongues to pluck leaves from the tallest trees, making them well-adapted to their environment. Their unique coat patterns, much like human fingerprints, are unique to each individual.
|
235 |
+
"""
|
236 |
+
model = model.cuda()
|
237 |
+
output = model(text)
|
238 |
+
print(output["block"][1].shape)
|
239 |
+
print(output["token_texts"])
|