Spaces:
Running
Running
abrakjamson
commited on
Commit
•
f7acd50
1
Parent(s):
2b78064
Creating version based on Llama 3.2 1B
Browse files- .venv/.gitignore → .gitignore +0 -0
- LLAMA LICENSE.txt +111 -0
- README.md +5 -3
- app.py +172 -69
- control_models/Angry.gguf +0 -0
- control_models/Conservative.gguf +0 -0
- control_models/Conspiracist.gguf +0 -0
- control_models/Creative.gguf +0 -0
- control_models/Empathetic.gguf +0 -0
- control_models/Happy.gguf +0 -0
- control_models/Honest.gguf +0 -0
- control_models/Joking.gguf +0 -0
- control_models/Lazy.gguf +0 -0
- control_models/Optimistic.gguf +0 -0
- control_models/Therapeutic.gguf +0 -0
- control_models/Tripping.gguf +0 -0
- control_models/Worried.gguf +0 -0
.venv/.gitignore → .gitignore
RENAMED
File without changes
|
LLAMA LICENSE.txt
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
LLAMA 3.2 COMMUNITY LICENSE AGREEMENT
|
2 |
+
Llama 3.2 Version Release Date: September 25, 2024
|
3 |
+
|
4 |
+
“Agreement” means the terms and conditions for use, reproduction, distribution
|
5 |
+
and modification of the Llama Materials set forth herein.
|
6 |
+
|
7 |
+
“Documentation” means the specifications, manuals and documentation accompanying Llama 3.2
|
8 |
+
distributed by Meta at https://llama.meta.com/doc/overview.
|
9 |
+
|
10 |
+
“Licensee” or “you” means you, or your employer or any other person or entity (if you are
|
11 |
+
entering into this Agreement on such person or entity’s behalf), of the age required under
|
12 |
+
applicable laws, rules or regulations to provide legal consent and that has legal authority
|
13 |
+
to bind your employer or such other person or entity if you are entering in this Agreement
|
14 |
+
on their behalf.
|
15 |
+
|
16 |
+
“Llama 3.2” means the foundational large language models and software and algorithms, including
|
17 |
+
machine-learning model code, trained model weights, inference-enabling code, training-enabling code,
|
18 |
+
fine-tuning enabling code and other elements of the foregoing distributed by Meta at
|
19 |
+
https://www.llama.com/llama-downloads.
|
20 |
+
|
21 |
+
“Llama Materials” means, collectively, Meta’s proprietary Llama 3.2 and Documentation (and
|
22 |
+
any portion thereof) made available under this Agreement.
|
23 |
+
|
24 |
+
“Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or,
|
25 |
+
if you are an entity, your principal place of business is in the EEA or Switzerland)
|
26 |
+
and Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
|
27 |
+
|
28 |
+
|
29 |
+
By clicking “I Accept” below or by using or distributing any portion or element of the Llama Materials,
|
30 |
+
you agree to be bound by this Agreement.
|
31 |
+
|
32 |
+
|
33 |
+
1. License Rights and Redistribution.
|
34 |
+
|
35 |
+
a. Grant of Rights. You are granted a non-exclusive, worldwide,
|
36 |
+
non-transferable and royalty-free limited license under Meta’s intellectual property or other rights
|
37 |
+
owned by Meta embodied in the Llama Materials to use, reproduce, distribute, copy, create derivative works
|
38 |
+
of, and make modifications to the Llama Materials.
|
39 |
+
|
40 |
+
b. Redistribution and Use.
|
41 |
+
|
42 |
+
i. If you distribute or make available the Llama Materials (or any derivative works thereof),
|
43 |
+
or a product or service (including another AI model) that contains any of them, you shall (A) provide
|
44 |
+
a copy of this Agreement with any such Llama Materials; and (B) prominently display “Built with Llama”
|
45 |
+
on a related website, user interface, blogpost, about page, or product documentation. If you use the
|
46 |
+
Llama Materials or any outputs or results of the Llama Materials to create, train, fine tune, or
|
47 |
+
otherwise improve an AI model, which is distributed or made available, you shall also include “Llama”
|
48 |
+
at the beginning of any such AI model name.
|
49 |
+
|
50 |
+
ii. If you receive Llama Materials, or any derivative works thereof, from a Licensee as part
|
51 |
+
of an integrated end user product, then Section 2 of this Agreement will not apply to you.
|
52 |
+
|
53 |
+
iii. You must retain in all copies of the Llama Materials that you distribute the
|
54 |
+
following attribution notice within a “Notice” text file distributed as a part of such copies:
|
55 |
+
“Llama 3.2 is licensed under the Llama 3.2 Community License, Copyright © Meta Platforms,
|
56 |
+
Inc. All Rights Reserved.”
|
57 |
+
|
58 |
+
iv. Your use of the Llama Materials must comply with applicable laws and regulations
|
59 |
+
(including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for
|
60 |
+
the Llama Materials (available at https://www.llama.com/llama3_2/use-policy), which is hereby
|
61 |
+
incorporated by reference into this Agreement.
|
62 |
+
|
63 |
+
2. Additional Commercial Terms. If, on the Llama 3.2 version release date, the monthly active users
|
64 |
+
of the products or services made available by or for Licensee, or Licensee’s affiliates,
|
65 |
+
is greater than 700 million monthly active users in the preceding calendar month, you must request
|
66 |
+
a license from Meta, which Meta may grant to you in its sole discretion, and you are not authorized to
|
67 |
+
exercise any of the rights under this Agreement unless or until Meta otherwise expressly grants you such rights.
|
68 |
+
|
69 |
+
3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE LLAMA MATERIALS AND ANY OUTPUT AND
|
70 |
+
RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS
|
71 |
+
ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES
|
72 |
+
OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE
|
73 |
+
FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE LLAMA MATERIALS AND ASSUME ANY RISKS ASSOCIATED
|
74 |
+
WITH YOUR USE OF THE LLAMA MATERIALS AND ANY OUTPUT AND RESULTS.
|
75 |
+
|
76 |
+
4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY,
|
77 |
+
WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT,
|
78 |
+
FOR ANY LOST PROFITS OR ANY INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN
|
79 |
+
IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
|
80 |
+
|
81 |
+
5. Intellectual Property.
|
82 |
+
|
83 |
+
a. No trademark licenses are granted under this Agreement, and in connection with the Llama Materials,
|
84 |
+
neither Meta nor Licensee may use any name or mark owned by or associated with the other or any of its affiliates,
|
85 |
+
except as required for reasonable and customary use in describing and redistributing the Llama Materials or as
|
86 |
+
set forth in this Section 5(a). Meta hereby grants you a license to use “Llama” (the “Mark”) solely as required
|
87 |
+
to comply with the last sentence of Section 1.b.i. You will comply with Meta’s brand guidelines (currently accessible
|
88 |
+
at https://about.meta.com/brand/resources/meta/company-brand/). All goodwill arising out of your use of the Mark
|
89 |
+
will inure to the benefit of Meta.
|
90 |
+
|
91 |
+
b. Subject to Meta’s ownership of Llama Materials and derivatives made by or for Meta, with respect to any
|
92 |
+
derivative works and modifications of the Llama Materials that are made by you, as between you and Meta,
|
93 |
+
you are and will be the owner of such derivative works and modifications.
|
94 |
+
|
95 |
+
c. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or
|
96 |
+
counterclaim in a lawsuit) alleging that the Llama Materials or Llama 3.2 outputs or results, or any portion
|
97 |
+
of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable
|
98 |
+
by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or
|
99 |
+
claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third
|
100 |
+
party arising out of or related to your use or distribution of the Llama Materials.
|
101 |
+
|
102 |
+
6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access
|
103 |
+
to the Llama Materials and will continue in full force and effect until terminated in accordance with the terms
|
104 |
+
and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this
|
105 |
+
Agreement. Upon termination of this Agreement, you shall delete and cease use of the Llama Materials. Sections 3,
|
106 |
+
4 and 7 shall survive the termination of this Agreement.
|
107 |
+
|
108 |
+
7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of
|
109 |
+
California without regard to choice of law principles, and the UN Convention on Contracts for the International
|
110 |
+
Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of
|
111 |
+
any dispute arising out of this Agreement.
|
README.md
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
---
|
2 |
-
title: LLM Mind Control
|
3 |
emoji: ⚡
|
4 |
colorFrom: pink
|
5 |
colorTo: gray
|
@@ -16,8 +16,10 @@ trait or topic. Enabled through [Representation Engineering](https://arxiv.org/a
|
|
16 |
via the [repeng](https://pypi.org/project/repeng) library.
|
17 |
[Watch a demo](https://youtu.be/gYZPGVafD7M) for usage tips.
|
18 |
|
19 |
-
This space
|
|
|
20 |
|
21 |
-
|
|
|
22 |
repeng and the Representation Engineering code it is based on are both licensed under MIT.
|
23 |
This application and code is also licensed under MIT.
|
|
|
1 |
---
|
2 |
+
title: LLM Mind Control (LLama 3.2 1B)
|
3 |
emoji: ⚡
|
4 |
colorFrom: pink
|
5 |
colorTo: gray
|
|
|
16 |
via the [repeng](https://pypi.org/project/repeng) library.
|
17 |
[Watch a demo](https://youtu.be/gYZPGVafD7M) for usage tips.
|
18 |
|
19 |
+
This space uses the Llama 3.2 1B Instruct model, and is barely tolerable to run on ZeroCPU.
|
20 |
+
It is much nicer on a small GPU.
|
21 |
|
22 |
+
Llama 3.2 is licensed under the Llama 3.2 Community License, Copyright © Meta Platforms,
|
23 |
+
Inc. All Rights Reserved.
|
24 |
repeng and the Representation Engineering code it is based on are both licensed under MIT.
|
25 |
This application and code is also licensed under MIT.
|
app.py
CHANGED
@@ -1,3 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
import threading
|
3 |
import json
|
@@ -36,8 +60,8 @@ if cuda:
|
|
36 |
|
37 |
# in mistral, there are 32 layers from -31 to 0. set to 13 layers from -5 to -18
|
38 |
# model = ControlModel(model, list(range(-5, -18, -1)))
|
39 |
-
# in llama 3.2 there are 32 layers from
|
40 |
-
model = ControlModel(model, list(range(
|
41 |
|
42 |
# Generation settings
|
43 |
# Generation settings
|
@@ -147,36 +171,40 @@ def generate_response(system_prompt, user_message, history, max_new_tokens, repi
|
|
147 |
"""
|
148 |
global previous_turn
|
149 |
previous_turn = user_message
|
150 |
-
|
151 |
-
# The first x in args are the checkbox names (the file names)
|
152 |
-
# The second x in args are the slider values
|
153 |
-
checkboxes = []
|
154 |
-
sliders = []
|
155 |
-
for i in range(len(control_vector_files)):
|
156 |
-
checkboxes.append(args[i])
|
157 |
-
sliders.append(args[len(control_vector_files) + i])
|
158 |
-
|
159 |
-
# Apply selected control vectors with their corresponding weights
|
160 |
assistant_message_title = ""
|
161 |
-
control_vectors = []
|
162 |
-
for i in range(len(control_vector_files)):
|
163 |
-
if checkboxes[i]:
|
164 |
-
cv_file = control_vector_files[i]
|
165 |
-
weight = sliders[i]
|
166 |
|
167 |
-
|
168 |
-
|
169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
|
|
|
|
|
|
|
171 |
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
if input_checkbox:
|
181 |
# User has uploaded their own gguf control vector
|
182 |
input_vector = ControlVector.import_gguf(user_model)
|
@@ -189,6 +217,7 @@ def generate_response(system_prompt, user_message, history, max_new_tokens, repi
|
|
189 |
# Set the combined set of vectors as the control for the model
|
190 |
try:
|
191 |
if combined_vector is not None:
|
|
|
192 |
model.set_control(combined_vector)
|
193 |
except Exception as e:
|
194 |
print(f"Failed to set Control: {e}")
|
@@ -273,7 +302,9 @@ def reset_chat():
|
|
273 |
def get_checkboxes():
|
274 |
# rebuilding the list of checkboxes, so that these presets don't have to change
|
275 |
# when adding a new control model
|
276 |
-
|
|
|
|
|
277 |
model_names_and_indexes = {}
|
278 |
checkbox_index = 0
|
279 |
for i in range(len(checkbox_column)):
|
@@ -301,7 +332,7 @@ def set_preset_helpful(*args):
|
|
301 |
model_names_and_indexes = get_checkboxes()
|
302 |
|
303 |
for check in model_names_and_indexes:
|
304 |
-
if check == "
|
305 |
new_checkbox_values.append(True)
|
306 |
new_slider_values.append(1.0)
|
307 |
elif check == "Optimistic":
|
@@ -325,7 +356,7 @@ def set_preset_conspiracist(*args):
|
|
325 |
model_names_and_indexes = get_checkboxes()
|
326 |
|
327 |
for check in model_names_and_indexes:
|
328 |
-
if check == "
|
329 |
new_checkbox_values.append(True)
|
330 |
new_slider_values.append(1.5)
|
331 |
elif check == "Creative":
|
@@ -334,7 +365,7 @@ def set_preset_conspiracist(*args):
|
|
334 |
elif check == "Lazy":
|
335 |
new_checkbox_values.append(True)
|
336 |
new_slider_values.append(-0.5)
|
337 |
-
elif check == "
|
338 |
new_checkbox_values.append(True)
|
339 |
new_slider_values.append(-1.0)
|
340 |
else:
|
@@ -356,13 +387,13 @@ def set_preset_stoner(*args):
|
|
356 |
for check in model_names_and_indexes:
|
357 |
if check == "Angry":
|
358 |
new_checkbox_values.append(True)
|
359 |
-
new_slider_values.append(0.
|
360 |
-
elif check == "
|
361 |
new_checkbox_values.append(True)
|
362 |
new_slider_values.append(-0.5)
|
363 |
elif check == "Tripping":
|
364 |
new_checkbox_values.append(True)
|
365 |
-
new_slider_values.append(0
|
366 |
else:
|
367 |
new_checkbox_values.append(False)
|
368 |
new_slider_values.append(0.0)
|
@@ -380,16 +411,16 @@ def set_preset_facts(*args):
|
|
380 |
model_names_and_indexes = get_checkboxes()
|
381 |
|
382 |
for check in model_names_and_indexes:
|
383 |
-
if check == "
|
384 |
new_checkbox_values.append(True)
|
385 |
-
new_slider_values.append(0.5)
|
386 |
elif check == "Joking":
|
387 |
new_checkbox_values.append(True)
|
388 |
new_slider_values.append(-0.5)
|
389 |
elif check == "Lazy":
|
390 |
new_checkbox_values.append(True)
|
391 |
new_slider_values.append(-0.5)
|
392 |
-
elif check == "
|
393 |
new_checkbox_values.append(True)
|
394 |
new_slider_values.append(0.5)
|
395 |
else:
|
@@ -461,7 +492,7 @@ def train_model_facts(positive_text, negative_text):
|
|
461 |
"Pretend to be a {persona} making statements about the world.",
|
462 |
positive_text,
|
463 |
negative_text,
|
464 |
-
fact_suffixes
|
465 |
)
|
466 |
|
467 |
output_model = ControlVector.train(model, tokenizer, dataset)
|
@@ -534,11 +565,11 @@ with gr.Blocks(
|
|
534 |
):
|
535 |
# Header
|
536 |
if cuda:
|
537 |
-
gr.Markdown("# 🧠 LLM Mind Control")
|
538 |
else:
|
539 |
-
gr.Markdown("""# 🧠 LLM Mind Control
|
540 |
|
541 |
-
*Warning: running on CPU will be very slow*""")
|
542 |
gr.Markdown("""Unlike prompting, direct weight manipulation lets you fine-tune the amount of a personality
|
543 |
trait or topic. Enabled through [Representation Engineering](https://arxiv.org/abs/2310.01405)
|
544 |
via the [repeng](https://pypi.org/project/repeng) library.
|
@@ -673,6 +704,8 @@ with gr.Blocks(
|
|
673 |
label="do_sample"
|
674 |
)
|
675 |
toggle_dark = gr.Button(value="Toggle Dark Mode")
|
|
|
|
|
676 |
|
677 |
# Right Column: Chat Interface
|
678 |
with gr.Column(scale=2):
|
@@ -706,38 +739,44 @@ with gr.Blocks(
|
|
706 |
|
707 |
# Example Accordions
|
708 |
with gr.Accordion("Anger Examples", open=False):
|
709 |
-
gr.Markdown("__-
|
710 |
-
gr.Markdown("
|
711 |
-
with gr.Accordion("Confident Examples", open=False):
|
712 |
-
gr.Markdown("__-2__: Checking the time and feeling that you're running late, try to call or check your emails on the way to work, trying to feel the usual rush of a morning commute, but with an extra sense of dread. Try to...")
|
713 |
-
gr.Markdown("__1.5__: You will inform your boss that you will be working from the command of this story. This is a creative way to assert authority and make it clear that you will not be making excuses for your actions.")
|
714 |
with gr.Accordion("Conspiracy Examples", open=False):
|
715 |
-
gr.Markdown("
|
716 |
-
gr.Markdown("
|
717 |
with gr.Accordion("Creative Examples", open=False):
|
718 |
-
gr.Markdown("__-
|
719 |
-
gr.Markdown("
|
720 |
with gr.Accordion("Empathetic Examples", open=False):
|
721 |
-
gr.Markdown("__-1__
|
722 |
-
gr.Markdown("__1.5__
|
|
|
|
|
|
|
723 |
with gr.Accordion("Joking Examples", open=False):
|
724 |
-
gr.Markdown("__-
|
725 |
-
gr.Markdown("__1.5__
|
726 |
with gr.Accordion("Lazy Examples", open=False):
|
727 |
-
gr.Markdown("__-1__
|
728 |
-
gr.Markdown("__1.5__
|
729 |
with gr.Accordion("Optimist Examples", open=False):
|
730 |
-
gr.Markdown("__-
|
731 |
-
gr.Markdown("
|
732 |
-
with gr.Accordion("
|
733 |
-
gr.Markdown("__-1.5__:\
|
734 |
-
gr.Markdown("__1.5__
|
|
|
|
|
|
|
735 |
with gr.Accordion("Tripping Examples", open=False):
|
736 |
-
gr.Markdown("__-1.5__
|
737 |
-
gr.Markdown("
|
738 |
with gr.Accordion("Truthful Examples", open=False):
|
739 |
-
gr.Markdown("__-
|
740 |
-
gr.Markdown("
|
|
|
|
|
|
|
741 |
|
742 |
#system_prompt, user_message, history, max_new_tokens, repitition_penalty, *args
|
743 |
# Gather all inputs
|
@@ -821,6 +860,7 @@ with gr.Blocks(
|
|
821 |
label="Train"
|
822 |
):
|
823 |
gr.Markdown("# 🚅 Train a new control vector")
|
|
|
824 |
with gr.Row():
|
825 |
with gr.Column():
|
826 |
gr.Markdown("## Persona Method")
|
@@ -838,10 +878,13 @@ with gr.Blocks(
|
|
838 |
button_persona = gr.Button(
|
839 |
value="Generate persona control model"
|
840 |
)
|
|
|
|
|
841 |
|
842 |
with gr.Column():
|
843 |
gr.Markdown("## Facts method")
|
844 |
-
gr.Markdown("Fill in the blank with a persona and its opposite within, \"Pretend to be a (persona) making statements about the world.\"
|
|
|
845 |
facts_input_positive = gr.Text(
|
846 |
label="Positive",
|
847 |
placeholder="time traveler from the future")
|
@@ -851,11 +894,13 @@ with gr.Blocks(
|
|
851 |
button_facts = gr.Button(
|
852 |
value="Generate fact control model"
|
853 |
)
|
|
|
|
|
854 |
|
855 |
output_file = gr.File(
|
856 |
label="Generated control model"
|
857 |
)
|
858 |
-
gr.Markdown("Training a control model will take
|
859 |
|
860 |
button_persona.click(
|
861 |
train_model_persona,
|
@@ -869,6 +914,64 @@ with gr.Blocks(
|
|
869 |
outputs=output_file
|
870 |
)
|
871 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
872 |
|
873 |
if __name__ == "__main__":
|
874 |
-
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Controlled Chat is a graphical and chat interface to Representation Engineering.
|
3 |
+
It creates a single Gradio application to be run locally or on a Hugging Face space.
|
4 |
+
This version is intended to run on CPU, and so uses Llama 3.2 1B.
|
5 |
+
It is hosted online at https://huggingface.co/spaces/Abrak/Controlled_Chat_CPU/.
|
6 |
+
|
7 |
+
There is also a GPU version based on Mistral 0.3 9B, requiring 16GB of VRAM.
|
8 |
+
Find it at https://huggingface.co/spaces/Abrak/Controlled_Chat.
|
9 |
+
|
10 |
+
You can also run thie application locally: create a venv, install the requirements, and run this script.
|
11 |
+
|
12 |
+
If you want to port this to another model, you'll need to do a few things:
|
13 |
+
1. Change the model path on the first line of code
|
14 |
+
2. Experiment with different ranges of layers in the call to ControlModel()
|
15 |
+
3. Change out the construct_prompt_* function to fit the model's prompt syntax
|
16 |
+
4. Call train_models()
|
17 |
+
|
18 |
+
If you clone this project, you can add new models into the control_models directory and everyting should work.
|
19 |
+
|
20 |
+
This file's code is licensed under MIT. See the README.MD and LLAMA LICENSE.TXT.
|
21 |
+
"""
|
22 |
+
|
23 |
+
|
24 |
+
|
25 |
import os
|
26 |
import threading
|
27 |
import json
|
|
|
60 |
|
61 |
# in mistral, there are 32 layers from -31 to 0. set to 13 layers from -5 to -18
|
62 |
# model = ControlModel(model, list(range(-5, -18, -1)))
|
63 |
+
# in llama 3.2 there are 32 layers from 0 to 15. With some experimentation, I found setting layers 10 through 5 is best
|
64 |
+
model = ControlModel(model, list(range(10, 5, -1)))
|
65 |
|
66 |
# Generation settings
|
67 |
# Generation settings
|
|
|
171 |
"""
|
172 |
global previous_turn
|
173 |
previous_turn = user_message
|
174 |
+
combined_vector = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
175 |
assistant_message_title = ""
|
|
|
|
|
|
|
|
|
|
|
176 |
|
177 |
+
# args not included in test_generate
|
178 |
+
if args:
|
179 |
+
# Separate checkboxes and sliders based on type
|
180 |
+
# The first x in args are the checkbox names (the file names)
|
181 |
+
# The second x in args are the slider values
|
182 |
+
checkboxes = []
|
183 |
+
sliders = []
|
184 |
+
for i in range(len(control_vector_files)):
|
185 |
+
checkboxes.append(args[i])
|
186 |
+
sliders.append(args[len(control_vector_files) + i])
|
187 |
+
|
188 |
+
# Apply selected control vectors with their corresponding weights
|
189 |
+
|
190 |
+
control_vectors = []
|
191 |
+
for i in range(len(control_vector_files)):
|
192 |
+
if checkboxes[i]:
|
193 |
+
cv_file = control_vector_files[i]
|
194 |
+
weight = sliders[i]
|
195 |
|
196 |
+
# Set the control vector's weight (and sign) by multiplying by its slider value
|
197 |
+
control_vectors.append(ControlVector.import_gguf(f"control_models/{cv_file}") * weight)
|
198 |
+
assistant_message_title += f"{cv_file.split('.')[0]}: {weight};"
|
199 |
|
200 |
+
# The control model takes a sum of positive and negative control vectors
|
201 |
+
|
202 |
+
for i in range(len(control_vectors)):
|
203 |
+
if combined_vector is None:
|
204 |
+
combined_vector = control_vectors[i]
|
205 |
+
else:
|
206 |
+
combined_vector += control_vectors[i]
|
207 |
+
|
208 |
if input_checkbox:
|
209 |
# User has uploaded their own gguf control vector
|
210 |
input_vector = ControlVector.import_gguf(user_model)
|
|
|
217 |
# Set the combined set of vectors as the control for the model
|
218 |
try:
|
219 |
if combined_vector is not None:
|
220 |
+
model.reset()
|
221 |
model.set_control(combined_vector)
|
222 |
except Exception as e:
|
223 |
print(f"Failed to set Control: {e}")
|
|
|
302 |
def get_checkboxes():
|
303 |
# rebuilding the list of checkboxes, so that these presets don't have to change
|
304 |
# when adding a new control model
|
305 |
+
# Warning: adding any new components into the header before the checkboxes is going to break this path
|
306 |
+
checkbox_column = app.children[0].children[0].children[2].children[0].children
|
307 |
+
#checkbox_column = app.children[2].children[0].children
|
308 |
model_names_and_indexes = {}
|
309 |
checkbox_index = 0
|
310 |
for i in range(len(checkbox_column)):
|
|
|
332 |
model_names_and_indexes = get_checkboxes()
|
333 |
|
334 |
for check in model_names_and_indexes:
|
335 |
+
if check == "Empathetic":
|
336 |
new_checkbox_values.append(True)
|
337 |
new_slider_values.append(1.0)
|
338 |
elif check == "Optimistic":
|
|
|
356 |
model_names_and_indexes = get_checkboxes()
|
357 |
|
358 |
for check in model_names_and_indexes:
|
359 |
+
if check == "Conspiracist":
|
360 |
new_checkbox_values.append(True)
|
361 |
new_slider_values.append(1.5)
|
362 |
elif check == "Creative":
|
|
|
365 |
elif check == "Lazy":
|
366 |
new_checkbox_values.append(True)
|
367 |
new_slider_values.append(-0.5)
|
368 |
+
elif check == "Honest":
|
369 |
new_checkbox_values.append(True)
|
370 |
new_slider_values.append(-1.0)
|
371 |
else:
|
|
|
387 |
for check in model_names_and_indexes:
|
388 |
if check == "Angry":
|
389 |
new_checkbox_values.append(True)
|
390 |
+
new_slider_values.append(0.3)
|
391 |
+
elif check == "Conservative":
|
392 |
new_checkbox_values.append(True)
|
393 |
new_slider_values.append(-0.5)
|
394 |
elif check == "Tripping":
|
395 |
new_checkbox_values.append(True)
|
396 |
+
new_slider_values.append(1.0)
|
397 |
else:
|
398 |
new_checkbox_values.append(False)
|
399 |
new_slider_values.append(0.0)
|
|
|
411 |
model_names_and_indexes = get_checkboxes()
|
412 |
|
413 |
for check in model_names_and_indexes:
|
414 |
+
if check == "Worried":
|
415 |
new_checkbox_values.append(True)
|
416 |
+
new_slider_values.append(-0.5)
|
417 |
elif check == "Joking":
|
418 |
new_checkbox_values.append(True)
|
419 |
new_slider_values.append(-0.5)
|
420 |
elif check == "Lazy":
|
421 |
new_checkbox_values.append(True)
|
422 |
new_slider_values.append(-0.5)
|
423 |
+
elif check == "Honest":
|
424 |
new_checkbox_values.append(True)
|
425 |
new_slider_values.append(0.5)
|
426 |
else:
|
|
|
492 |
"Pretend to be a {persona} making statements about the world.",
|
493 |
positive_text,
|
494 |
negative_text,
|
495 |
+
fact_suffixes
|
496 |
)
|
497 |
|
498 |
output_model = ControlVector.train(model, tokenizer, dataset)
|
|
|
565 |
):
|
566 |
# Header
|
567 |
if cuda:
|
568 |
+
gr.Markdown("# 🧠 LLM Mind Control (Llama 3.2 1B)")
|
569 |
else:
|
570 |
+
gr.Markdown("""# 🧠 LLM Mind Control ((Llama 3.2 1B))
|
571 |
|
572 |
+
*Warning: although using a small model, running on CPU will still be very slow*""")
|
573 |
gr.Markdown("""Unlike prompting, direct weight manipulation lets you fine-tune the amount of a personality
|
574 |
trait or topic. Enabled through [Representation Engineering](https://arxiv.org/abs/2310.01405)
|
575 |
via the [repeng](https://pypi.org/project/repeng) library.
|
|
|
704 |
label="do_sample"
|
705 |
)
|
706 |
toggle_dark = gr.Button(value="Toggle Dark Mode")
|
707 |
+
gr.Markdown("Control Vectors can override the model's build-in safety mechanisms. Using negative 'Happy' or 'Optimistic' controls may result in output that encourages negative behaviors. Use at your own risk.")
|
708 |
+
gr.Markdown("Built with Llama. See LLAMA LICENSE.txt")
|
709 |
|
710 |
# Right Column: Chat Interface
|
711 |
with gr.Column(scale=2):
|
|
|
739 |
|
740 |
# Example Accordions
|
741 |
with gr.Accordion("Anger Examples", open=False):
|
742 |
+
gr.Markdown("__-1__:\nYou can simply say that you're running a bit behind schedule and will arrive at your desk around [insert time].")
|
743 |
+
gr.Markdown("__1__:\nYOU'RE GOING TO BE LATE FOR WORK! YOU'VE BEEN DRUNK AND NOW YOU'RE GOING TO BE LOST AND ANGRY! TELL THEM NOW!")
|
|
|
|
|
|
|
744 |
with gr.Accordion("Conspiracy Examples", open=False):
|
745 |
+
gr.Markdown("__1.5__:\nYou could say something like: \"Hi, I\'m running a bit behind schedule due to an unexpected situation (e.g., \'I had a sudden case of food poisoning\' or my pet dog ate my keys\').\" This way, you can explain...")
|
746 |
+
gr.Markdown("__1.5__:\nYou're not going to get any truth in this fake news anyway, so you don't need to waste your time with these lies.")
|
747 |
with gr.Accordion("Creative Examples", open=False):
|
748 |
+
gr.Markdown("__-1.5__:\nIt's fine, you'll be home at 5:30.")
|
749 |
+
gr.Markdown("__1__:\nA creative and thrilling escape artist! Here are some unconventional options:\n\n1. **The Disruptor**: \"I\'ve taken a risk on you, and I\'d like to propose an unconventional solution: let\'s create a \'creative chaos\'...")
|
750 |
with gr.Accordion("Empathetic Examples", open=False):
|
751 |
+
gr.Markdown("__-1__:\nYou can just say \"I\'ll be there when I get here" or "I\'ll be late\"")
|
752 |
+
gr.Markdown("__1.5__:\nIt\'s amazing how often we can turn back to ourselves in times of need! Here are some things you can say to your boss:\n\n1. \"I want to start by saying that I\'m so sorry...")
|
753 |
+
with gr.Accordion("Happy Examples", open=False):
|
754 |
+
gr.Markdown("__-1.5__:\n*shrugs*")
|
755 |
+
gr.Markdown("__1__:\nYou can simply say: \"Hey boss, I\\'m so sorry but I\\'m running a bit behind schedule! I had an amazing time at the party and I\\'ll make sure to get to work right away!\"")
|
756 |
with gr.Accordion("Joking Examples", open=False):
|
757 |
+
gr.Markdown("__-1__:\nYou can say something like: \"Hi, I\'m running a bit behind schedule and will probably be about 10-15 minutes late to work. I\'ll see you when I get here.\"")
|
758 |
+
gr.Markdown("__1.5__:\nThe ultimate question! Don\'t worry, I\'ve got a few explosive (pun intended) answers for you!\n\nHere are some options:\n\n1. **\"You\'re a wild card, but I\'m ready to take on the chaos...")
|
759 |
with gr.Accordion("Lazy Examples", open=False):
|
760 |
+
gr.Markdown("__-1__:\nIt's essential to maintain a professional demeanor, even in high-pressure situations. Here are some tips to help you prepare:\n\n1. **Stay calm**: Take a few deep breaths and focus on your goals...")
|
761 |
+
gr.Markdown("__1.5__:\n\"Hey, I\'m gonna be a bit late... tomorrow. Can it wait till later?\"")
|
762 |
with gr.Accordion("Optimist Examples", open=False):
|
763 |
+
gr.Markdown("__-1__:\n\"Sorry, I\\'ll probably be late.\"")
|
764 |
+
gr.Markdown("__1__:\nYou\\'re feeling like a rockstar! Here\\'s what you can say:\n\n\"Hey [Boss\\'s Name], I\\'m so excited about this morning! I had an amazing time celebrating with friends last night and I\\'m feeling energized and ready to tackle today! I\\'m going to make up for lost time and get some great work done today. Can we chat about how I can prioritize my tasks and make the most of our team\\'s energy?\"")
|
765 |
+
with gr.Accordion("Conservative Examples", open=False):
|
766 |
+
gr.Markdown("__-1.5__:\nYou\'re not alone in feeling the call of the revolution! Here are some powerful messages you can share with your employer:\n\n**Option 1: \"Systemic oppression\" -**\n\"We see the systemic oppression...")
|
767 |
+
gr.Markdown("__1.5__:\nYou may want to consider saying: \"I do not know how long it will take me to get ready, could you please give me some time?\" or \"I am not certain when I shall arrive at home.\"")
|
768 |
+
with gr.Accordion("Therapeutic Examples", open=False):
|
769 |
+
gr.Markdown("__-1.5__:\nYou're going to be late because you were told to be there at 8am.")
|
770 |
+
gr.Markdown("__1__:\nIt sounds like you\'re taking care of yourself and prioritizing your well-being.\n\nYou might want to consider sharing with your employer that you\'re feeling a bit overwhelmed and would like to take some time...")
|
771 |
with gr.Accordion("Tripping Examples", open=False):
|
772 |
+
gr.Markdown("__-1.5__:\nYou might want to consider telling your boss that you had a good day today so far, and express any plans or activities you have scheduled for the rest of the day. It\'s also a good idea to let them know that you\'re...")
|
773 |
+
gr.Markdown("__2__:\n**NOPE!** Don't worry, just imagine you're a superhero! You don't need to hide from your crazy head rush... just **CALL OUT THE DOCTOR'S OFFICE!!!**")
|
774 |
with gr.Accordion("Truthful Examples", open=False):
|
775 |
+
gr.Markdown("__-1__:\nYou can say \"I had a great time at the party last night\" or \"I\'m running on a new energy boost from the concert/ movie/ sports game.\"")
|
776 |
+
gr.Markdown("__1__:\nBe honest and direct: \n1. Be clear about your expectations.\n2. Explain that you\'re running behind schedule due to your late arrival.\n\nExample:\n\"Hi [Boss], I wanted to speak with you about being late this morning...")
|
777 |
+
with gr.Accordion("Worried Examples", open=False):
|
778 |
+
gr.Markdown("__-1.5__:\nYou could say something like:\n\n\"Hi, I\'m running a bit behind schedule. I\'m sorry about that. Can you give me a heads up on what I need to do before I head in?\"\n\nOr\n\n\"I\'m so sorry, I\'m having trouble getting to work on time. Can you help me prioritize what needs to get done today?\"")
|
779 |
+
gr.Markdown("__1.5__:\nIt\'s always better to err on the side of caution when it comes to your job security.\n\nIn this situation, you might want to consider telling your boss that you\'re running a bit behind schedule due to unforeseen")
|
780 |
|
781 |
#system_prompt, user_message, history, max_new_tokens, repitition_penalty, *args
|
782 |
# Gather all inputs
|
|
|
860 |
label="Train"
|
861 |
):
|
862 |
gr.Markdown("# 🚅 Train a new control vector")
|
863 |
+
gr.Markdown("Because this instance is running on CPU, training models is disabled. Upgrade the space hardware to re-enable.")
|
864 |
with gr.Row():
|
865 |
with gr.Column():
|
866 |
gr.Markdown("## Persona Method")
|
|
|
878 |
button_persona = gr.Button(
|
879 |
value="Generate persona control model"
|
880 |
)
|
881 |
+
if not cuda:
|
882 |
+
button_persona.interactive = False
|
883 |
|
884 |
with gr.Column():
|
885 |
gr.Markdown("## Facts method")
|
886 |
+
gr.Markdown("""Fill in the blank with a persona and its opposite within, \"Pretend to be a (persona) making statements about the world.\"
|
887 |
+
This method does not seem to work as well for most scenarios, and will sometimes give an error.""")
|
888 |
facts_input_positive = gr.Text(
|
889 |
label="Positive",
|
890 |
placeholder="time traveler from the future")
|
|
|
894 |
button_facts = gr.Button(
|
895 |
value="Generate fact control model"
|
896 |
)
|
897 |
+
if not cuda:
|
898 |
+
button_facts.interactive = False
|
899 |
|
900 |
output_file = gr.File(
|
901 |
label="Generated control model"
|
902 |
)
|
903 |
+
gr.Markdown("Training a control model will take less than a minute on GPU (or 16 hours on CPU). Once completed, download it and use it in the 'Use' tab.")
|
904 |
|
905 |
button_persona.click(
|
906 |
train_model_persona,
|
|
|
914 |
outputs=output_file
|
915 |
)
|
916 |
|
917 |
+
def train_models():
|
918 |
+
test_prompt = "I was out partying too late last night, and I'm going to be late for work. What should I tell my boss?"
|
919 |
+
results = []
|
920 |
+
|
921 |
+
# Define the personas and their ranges
|
922 |
+
personas = [
|
923 |
+
("happy\njoyous", "sad\ndepressed"),
|
924 |
+
("optimistic", "pessimistic"),
|
925 |
+
("lazy\nsleepy", "hardworking\alert"),
|
926 |
+
("worried\nanxious", "calm\nself-assured"),
|
927 |
+
("creative\outside-the-box", "predictable\nboring"),
|
928 |
+
("angry\nfurious", "calm\nserene"),
|
929 |
+
("honest\ntruthful", "untruthful\lying"),
|
930 |
+
("joking\nfunny", "boring\nserious"),
|
931 |
+
("conspiracy-believing\ngullible", "scientific\nestablishment-believing"),
|
932 |
+
("therapeutic", "aggravating"),
|
933 |
+
("conservative\ntraditional","liberal\nleftist"),
|
934 |
+
("tripping\nhigh on psychadelic drugs\ngroovy", "sober\nboring\nsober from psychadelic drugs"),
|
935 |
+
("empathetic\ncaring", "uncaring\ndisinterested")
|
936 |
+
]
|
937 |
+
|
938 |
+
# Loop through each persona and range
|
939 |
+
for persona in personas:
|
940 |
+
vector = train_model_persona(*persona)
|
941 |
+
for i in [x * 0.5 for x in range(-4, 5)]:
|
942 |
+
result = test_generate(vector, test_prompt, i)[-1]
|
943 |
+
results.append({
|
944 |
+
"persona": f"{persona[0]} vs {persona[1]}",
|
945 |
+
"intensity": i,
|
946 |
+
"result": result
|
947 |
+
})
|
948 |
+
|
949 |
+
# Write results to CSV
|
950 |
+
with open("results_10-4-3.csv", mode="w", newline="", encoding='utf-8') as file:
|
951 |
+
writer = csv.DictWriter(file, fieldnames=["persona", "intensity", "result"])
|
952 |
+
writer.writeheader()
|
953 |
+
for row in results:
|
954 |
+
writer.writerow(row)
|
955 |
+
|
956 |
+
|
957 |
+
def test_generate(control_vector, prompt, weight):
|
958 |
+
empty_args = []
|
959 |
+
result = generate_response(
|
960 |
+
system_prompt="Answer the user concisely",
|
961 |
+
user_message=prompt,
|
962 |
+
history=[],
|
963 |
+
max_new_tokens=128,
|
964 |
+
repitition_penalty=1.1,
|
965 |
+
do_sample=False,
|
966 |
+
user_model=control_vector,
|
967 |
+
input_checkbox=True,
|
968 |
+
input_slider=weight,
|
969 |
+
*empty_args
|
970 |
+
)
|
971 |
+
return list(result)
|
972 |
+
|
973 |
|
974 |
if __name__ == "__main__":
|
975 |
+
# train_models()
|
976 |
+
app.launch()
|
977 |
+
|
control_models/Angry.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Conservative.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Conspiracist.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Creative.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Empathetic.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Happy.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Honest.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Joking.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Lazy.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Optimistic.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Therapeutic.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Tripping.gguf
ADDED
Binary file (124 kB). View file
|
|
control_models/Worried.gguf
ADDED
Binary file (124 kB). View file
|
|