m-ric HF Staff commited on
Commit
3c1036c
Β·
1 Parent(s): 119ef11

First, non-working version

Browse files
Files changed (2) hide show
  1. app.py +170 -4
  2. requirements.txt +2 -0
app.py CHANGED
@@ -1,7 +1,173 @@
 
 
 
 
1
  import gradio as gr
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer
3
+ from lxt.models.llama import LlamaForCausalLM, attnlrp
4
+ from lxt.utils import clean_tokens
5
  import gradio as gr
6
+ import numpy as np
7
+ import spaces
8
 
9
+ # Load model and tokenizer
10
+ @spaces.GPU
11
+ def load_model_and_tokenizer():
12
+ model = LlamaForCausalLM.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0", torch_dtype=torch.float16, device_map="auto")
13
+ tokenizer = AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0")
14
+ attnlrp.register(model)
15
+ return model, tokenizer
16
 
17
+ model, tokenizer = load_model_and_tokenizer()
18
+
19
+ def really_clean_tokens(tokens):
20
+ tokens = clean_tokens(tokens)
21
+ tokens = [token.replace("_", " ").replace("▁", " ").replace("<s>", "") for token in tokens]
22
+ return tokens
23
+
24
+ @spaces.GPU
25
+ def generate_and_visualize(prompt, num_tokens=10):
26
+ input_ids = tokenizer(prompt, return_tensors="pt", add_special_tokens=True).input_ids.to(model.device)
27
+ input_embeds = model.get_input_embeddings()(input_ids)
28
+
29
+ generated_tokens_ids = []
30
+ all_relevances = []
31
+
32
+ print("OKKK let's gooo")
33
+
34
+ for _ in range(num_tokens):
35
+ output_logits = model(inputs_embeds=input_embeds.requires_grad_(), use_cache=False).logits
36
+ max_logits, max_indices = torch.max(output_logits[0, -1, :], dim=-1)
37
+
38
+ max_logits.backward(max_logits)
39
+ relevance = input_embeds.grad.float().sum(-1).cpu()[0]
40
+ all_relevances.append(relevance)
41
+
42
+ next_token = max_indices.unsqueeze(0)
43
+ generated_tokens_ids.append(next_token.item())
44
+
45
+ input_ids = torch.cat([input_ids, next_token.unsqueeze(0)], dim=1)
46
+ input_embeds = model.get_input_embeddings()(input_ids)
47
+
48
+ input_tokens = tokenizer.convert_ids_to_tokens(input_ids[0])
49
+ input_tokens = really_clean_tokens(input_tokens)
50
+ generated_tokens = really_clean_tokens(tokenizer.convert_ids_to_tokens(generated_tokens_ids))
51
+
52
+ return input_tokens, all_relevances, generated_tokens
53
+
54
+ def process_relevances(input_tokens, all_relevances, generated_tokens):
55
+ attention_matrix = np.array([el[:len(all_relevances[0])] for el in all_relevances])
56
+ non_zero_cols = np.where(np.abs(attention_matrix).sum(axis=0) > 1.)[0]
57
+ for col in range(5):
58
+ non_zero_cols = np.union1d(non_zero_cols, non_zero_cols + col)
59
+ non_zero_cols = np.union1d(non_zero_cols, non_zero_cols - col)
60
+ non_zero_cols = np.sort(non_zero_cols)
61
+ non_zero_cols = non_zero_cols[(non_zero_cols >= 0) & (non_zero_cols < attention_matrix.shape[1])]
62
+
63
+ important_input_tokens = [input_tokens[i] for i in non_zero_cols]
64
+
65
+ output_with_notes = []
66
+ current_group = []
67
+ current_note = set()
68
+
69
+ for i, (token, relevance) in enumerate(zip(generated_tokens, attention_matrix)):
70
+ important_indices = np.where(relevance[non_zero_cols] > 0.1)[0]
71
+ if len(important_indices) > 0:
72
+ current_group.append(token)
73
+ current_note.update([important_input_tokens[j] for j in important_indices])
74
+ else:
75
+ if current_group:
76
+ output_with_notes.append((" ".join(current_group), list(current_note)))
77
+ current_group = []
78
+ current_note = set()
79
+ output_with_notes.append((token, []))
80
+
81
+ if current_group:
82
+ output_with_notes.append((" ".join(current_group), list(current_note)))
83
+
84
+ return output_with_notes
85
+
86
+ def create_html_with_hover(output_with_notes):
87
+ html = "<div id='output-container'>"
88
+ for i, (text, notes) in enumerate(output_with_notes):
89
+ if notes:
90
+ html += f'<span class="hoverable" data-note-id="note-{i}">{text}<sup>[{i+1}]</sup>'
91
+ html += f'<span class="hover-note">{", ".join(notes)}</span></span> '
92
+ else:
93
+ html += f'{text} '
94
+ html += "</div>"
95
+ return html
96
+
97
+ @spaces.GPU
98
+ def on_generate(prompt, num_tokens):
99
+ input_tokens, all_relevances, generated_tokens = generate_and_visualize(prompt, num_tokens)
100
+ output_with_notes = process_relevances(input_tokens, all_relevances, generated_tokens)
101
+ html_output = create_html_with_hover(output_with_notes)
102
+ return html_output
103
+
104
+ css = """
105
+ #output-container { font-size: 18px; line-height: 1.5; }
106
+ .hoverable { color: blue; cursor: pointer; position: relative; }
107
+ .hover-note {
108
+ display: none;
109
+ position: absolute;
110
+ background-color: #f0f0f0;
111
+ padding: 5px;
112
+ border-radius: 5px;
113
+ bottom: 100%;
114
+ left: 50%;
115
+ transform: translateX(-50%);
116
+ white-space: nowrap;
117
+ z-index: 1;
118
+ }
119
+ .hoverable:hover .hover-note { display: block; }
120
+ """
121
+
122
+ examples = [
123
+ [
124
+ """Context: Mount Everest attracts many climbers, including highly experienced mountaineers. There are two main climbing routes, one approaching the summit from the southeast in Nepal (known as the standard route) and the other from the north in Tibet. While not posing substantial technical climbing challenges on the standard route, Everest presents dangers such as altitude sickness, weather, and wind, as well as hazards from avalanches and the Khumbu Icefall. As of November 2022, 310 people have died on Everest. Over 200 bodies remain on the mountain and have not been removed due to the dangerous conditions. The first recorded efforts to reach Everest's summit were made by British mountaineers. As Nepal did not allow foreigners to enter the country at the time, the British made several attempts on the north ridge route from the Tibetan side. After the first reconnaissance expedition by the British in 1921 reached 7,000 m (22,970 ft) on the North Col, the 1922 expedition pushed the north ridge route up to 8,320 m (27,300 ft), marking the first time a human had climbed above 8,000 m (26,247 ft). The 1924 expedition resulted in one of the greatest mysteries on Everest to this day: George Mallory and Andrew Irvine made a final summit attempt on 8 June but never returned, sparking debate as to whether they were the first to reach the top. Tenzing Norgay and Edmund Hillary made the first documented ascent of Everest in 1953, using the southeast ridge route. Norgay had reached 8,595 m (28,199 ft) the previous year as a member of the 1952 Swiss expedition. The Chinese mountaineering team of Wang Fuzhou, Gonpo, and Qu Yinhua made the first reported ascent of the peak from the north ridge on 25 May 1960.
125
+
126
+ Question: How high did they climb in 1922? According to the text, the 1922 expedition reached 8,""",
127
+ 10
128
+ ],
129
+ [
130
+ """Hurricane Katrina killed hundreds of people as it made landfall on New Orleans in 2005 - many of these deaths could have been avoided if alerts had been given one day earlier. Accurate weather forecasts are really life-saving.
131
+
132
+ πŸ”₯ Now, NASA and IBM just dropped a game-changing new model: the first ever foundation model for weather! This means, it's the first time we have a generalist model not restricted to one task, but able to predict 160 weather variables!
133
+
134
+ Prithvi WxC (Prithvi, "ΰ€ͺΰ₯ƒΰ€₯ΰ₯ΰ€΅ΰ₯€", is the Sanskrit name for Earth) - is a 2.3 billion parameter model, with an architecture close to previous vision transformers like Hiera.
135
+
136
+ πŸ’‘ But it comes with some important tweaks: under the hood, Prithvi WxC uses a clever transformer-based architecture with 25 encoder and 5 decoder blocks. It alternates between "local" and "global" attention to capture both regional and global weather patterns.
137
+
138
+ How many weather variables can Prithvi predict? Prithvi can""",
139
+ 15
140
+ ],
141
+ [
142
+ """Transformers v4.45.0 released: includes a lightning-fast method to build tools! ⚑️
143
+
144
+ During user research with colleagues @MoritzLaurer and @Jofthomas , we discovered that the class definition currently in used to define a Tool in transformers.agents is a bit tedious to use, because it goes in great detail.
145
+
146
+ ➑️ So I've made an easier way to build tools: just make a function with type hints + a docstring, and add a @tool decorator in front.
147
+
148
+ βœ… VoilΓ , you're good to go!
149
+
150
+ How can you build tools simply in transformers? Just use the decorator""",
151
+ 20
152
+ ]
153
+ ]
154
+
155
+ with gr.Blocks(css=css) as demo:
156
+ gr.Markdown("# Token Generation with Hover Notes")
157
+
158
+ input_text = gr.Textbox(label="Enter your prompt:", lines=10, value=examples[0][0])
159
+ num_tokens = gr.Slider(minimum=1, maximum=50, value=10, step=1, label="Number of tokens to generate")
160
+ generate_button = gr.Button("Generate")
161
+
162
+ output_html = gr.HTML(label="Generated Output")
163
+
164
+ generate_button.click(
165
+ on_generate,
166
+ inputs=[input_text, num_tokens],
167
+ outputs=[output_html]
168
+ )
169
+
170
+ gr.Markdown("Hover over the blue text with superscript numbers to see the important input tokens for that group.")
171
+
172
+ if __name__ == "__main__":
173
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ lxt
2
+ numpy