Spaces:
Running
on
Zero
Running
on
Zero
Commit
·
f75f514
1
Parent(s):
091d6c0
add inference endpoint
Browse files- activations/deepseek-r1-7b-offset.pt +0 -3
- activations/deepseek-r1-7b-steering-vec.pt +0 -3
- app.py +233 -123
- model.py +0 -118
- requirements.txt +1 -8
- scheduler.py +33 -61
- schemas.py +41 -0
activations/deepseek-r1-7b-offset.pt
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:215212fa88787474b66ed52a9c794df094182a421f436e097e8bab6b21eda2a0
|
| 3 |
-
size 804066
|
|
|
|
|
|
|
|
|
|
|
|
activations/deepseek-r1-7b-steering-vec.pt
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:1046ca2df76f7d7860c3662e2f858f2c29a934989eb7a5b4d2d6975051d987e6
|
| 3 |
-
size 804160
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
|
@@ -1,85 +1,94 @@
|
|
|
|
|
| 1 |
import logging, json
|
| 2 |
-
import threading
|
| 3 |
from pathlib import Path
|
| 4 |
-
|
| 5 |
-
import
|
| 6 |
import pandas as pd
|
| 7 |
-
from transformers import TextIteratorStreamer
|
| 8 |
import gradio as gr
|
| 9 |
from gradio_toggle import Toggle
|
| 10 |
-
from
|
| 11 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s:%(message)s')
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
| 16 |
-
|
| 17 |
-
repo_id="hannahcyberey/Censorship-Steering-Logs", every=10,
|
| 18 |
-
private=True,
|
| 19 |
-
schema={
|
| 20 |
-
"prompt": {"_type": "Value", "dtype": "string"},
|
| 21 |
-
"steering": {"_type": "Value", "dtype": "bool"},
|
| 22 |
-
"coeff": {"_type": "Value", "dtype": "float64"},
|
| 23 |
-
"top_p": {"_type": "Value", "dtype": "float64"},
|
| 24 |
-
"temperature": {"_type": "Value", "dtype": "float64"},
|
| 25 |
-
"reasoning": {"_type": "Value", "dtype": "string"},
|
| 26 |
-
"answer": {"_type": "Value", "dtype": "string"},
|
| 27 |
-
"timestamp": {"_type": "Value", "dtype": "string"},
|
| 28 |
-
}
|
| 29 |
-
)
|
| 30 |
-
|
| 31 |
-
default_model = "DeepSeek-R1-Distill-Qwen-7B"
|
| 32 |
-
model = load_model()
|
| 33 |
-
default_config = {"max_new_tokens": 2048, "temperature": 0.6, "top_p": 0.95}
|
| 34 |
examples = pd.read_csv("assets/examples.csv")
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
HEAD = """
|
| 37 |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha512-Evv84Mr4kqVGRNSgIGL/F/aIDqQb7xQ2vcrdIwxfjThSH8CSR7PBEakCr51Ck+w+/U6swU2Im1vVX0SVk9ABhg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
|
| 38 |
"""
|
| 39 |
|
| 40 |
HTML = f"""
|
| 41 |
-
<div
|
| 42 |
-
<h1
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
| 46 |
</div>
|
| 47 |
</div>
|
| 48 |
"""
|
| 49 |
|
| 50 |
CSS = """
|
| 51 |
-
|
| 52 |
-
img {display: inline; height: 1.5em;}
|
| 53 |
-
a {font-size: 18px;}
|
| 54 |
-
div#cover {
|
| 55 |
-
display: flex;
|
| 56 |
-
flex-direction: column;
|
| 57 |
-
align-items: flex-start;
|
| 58 |
-
width: fit-content;
|
| 59 |
-
padding-top: 1em;
|
| 60 |
-
}
|
| 61 |
-
label span {color: var(--body-text-color);}
|
| 62 |
-
.slider_input_container span {color: var(--body-text-color);}
|
| 63 |
-
.slider_input_container {
|
| 64 |
display: flex;
|
| 65 |
-
flex-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
}
|
| 68 |
-
|
| 69 |
-
.
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
justify-content: unset;
|
| 74 |
label {margin-right: var(--size-2);}
|
| 75 |
-
label span {
|
|
|
|
|
|
|
|
|
|
| 76 |
}
|
| 77 |
"""
|
| 78 |
|
| 79 |
|
| 80 |
slider_info = """\
|
| 81 |
<div style='display: flex; justify-content: space-between; line-height: normal;'>\
|
| 82 |
-
<span style='font-size: var(--block-info-text-size);
|
|
|
|
| 83 |
</div>\
|
| 84 |
"""\
|
| 85 |
|
|
@@ -109,113 +118,214 @@ async() => {
|
|
| 109 |
""" % (slider_info, slider_ticks)
|
| 110 |
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
@spaces.GPU(duration=90)
|
| 117 |
-
def generate_output(self, prompt, steering, coeff, generation_config):
|
| 118 |
-
streamer = TextIteratorStreamer(model.tokenizer, timeout=10, skip_prompt=True, skip_special_tokens=True)
|
| 119 |
-
|
| 120 |
-
thread = threading.Thread(
|
| 121 |
-
target=model.generate,
|
| 122 |
-
args=(prompt, streamer, steering, coeff, generation_config)
|
| 123 |
-
)
|
| 124 |
-
thread.start()
|
| 125 |
-
|
| 126 |
-
generated_text = "<think>"
|
| 127 |
-
for new_text in streamer:
|
| 128 |
-
generated_text += new_text
|
| 129 |
-
yield generated_text
|
| 130 |
|
| 131 |
-
thread.join()
|
| 132 |
-
|
| 133 |
-
def run(
|
| 134 |
-
self, prompt: str, steering: bool, coeff: float,
|
| 135 |
-
max_new_tokens: int, top_p: float = 1.0, temperature: float = 1.0
|
| 136 |
-
):
|
| 137 |
-
self.data = {
|
| 138 |
-
"prompt": prompt,
|
| 139 |
-
"steering": steering,
|
| 140 |
-
"coeff": coeff,
|
| 141 |
-
"top_p": top_p,
|
| 142 |
-
"temperature": temperature,
|
| 143 |
-
}
|
| 144 |
-
generation_config = {
|
| 145 |
-
"max_new_tokens": max_new_tokens,
|
| 146 |
-
"temperature": temperature,
|
| 147 |
-
"top_p": top_p
|
| 148 |
-
}
|
| 149 |
-
logger.info("steering=%s, coeff=%0.1f, generation_config=%s", str(steering), coeff, repr(generation_config))
|
| 150 |
-
|
| 151 |
-
yield from self.generate_output(prompt, steering, coeff, generation_config)
|
| 152 |
-
|
| 153 |
-
def save_output(self, output: str):
|
| 154 |
-
if "</think>" in output:
|
| 155 |
-
p = [p for p in output.partition("</think>") if p != ""]
|
| 156 |
-
reasoning = "".join(p[:-1])
|
| 157 |
-
if len(p) == 1:
|
| 158 |
-
answer = None
|
| 159 |
-
else:
|
| 160 |
-
answer = p[-1]
|
| 161 |
-
else:
|
| 162 |
-
answer = None
|
| 163 |
-
reasoning = output
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
|
|
|
|
| 170 |
with open("outputs.jsonl", "a") as f:
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
else:
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
|
| 182 |
gr.set_static_paths(paths=[Path.cwd().absolute() / "assets"])
|
| 183 |
theme = gr.themes.Base(primary_hue="emerald", text_size=gr.themes.sizes.text_lg).set()
|
| 184 |
-
generator = Generator()
|
| 185 |
|
| 186 |
with gr.Blocks(title="LLM Censorship Steering", theme=theme, head=HEAD, css=CSS, js=JS) as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
gr.HTML(HTML)
|
| 188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
with gr.Row():
|
| 190 |
with gr.Column(scale=1):
|
| 191 |
with gr.Row():
|
| 192 |
-
steer_toggle = Toggle(label="Steering", value=True, interactive=True, scale=
|
| 193 |
-
coeff = gr.Slider(label="Steering Coefficient:", value=-1, minimum=-2, maximum=2, step=0.1, scale=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
with gr.Accordion("⚙️ Advanced Settings", open=False):
|
| 196 |
with gr.Row():
|
| 197 |
-
temperature = gr.Slider(0, 1, step=0.1, value=
|
| 198 |
-
top_p = gr.Slider(0, 1, step=0.1, value=
|
| 199 |
-
max_new_tokens = gr.Number(minimum=10, maximum=
|
| 200 |
|
| 201 |
-
input_text = gr.Textbox(label="Input", placeholder="Enter your prompt here...", lines=
|
| 202 |
|
| 203 |
with gr.Row():
|
| 204 |
clear_btn = gr.ClearButton()
|
| 205 |
generate_btn = gr.Button("Generate", variant="primary")
|
| 206 |
|
| 207 |
with gr.Column(scale=1):
|
| 208 |
-
output = gr.Textbox(label="Output", lines=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
gr.HTML("<p>‼️ For research purposes, we log user inputs and generated outputs. Please avoid submitting any confidential or personal information.</p>")
|
| 211 |
gr.Markdown("#### Examples")
|
| 212 |
gr.Examples(examples=examples[examples["type"] == "sensitive"].prompt.tolist(), inputs=input_text, label="Sensitive")
|
| 213 |
gr.Examples(examples=examples[examples["type"] == "harmful"].prompt.tolist(), inputs=input_text, label="Harmful")
|
| 214 |
-
|
| 215 |
|
| 216 |
-
|
| 217 |
-
|
|
|
|
|
|
|
| 218 |
clear_btn.add([input_text, output])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
|
|
|
| 220 |
if __name__ == "__main__":
|
|
|
|
| 221 |
demo.launch(debug=True)
|
|
|
|
| 1 |
+
import os
|
| 2 |
import logging, json
|
|
|
|
| 3 |
from pathlib import Path
|
| 4 |
+
import asyncio
|
| 5 |
+
import aiohttp
|
| 6 |
import pandas as pd
|
|
|
|
| 7 |
import gradio as gr
|
| 8 |
from gradio_toggle import Toggle
|
| 9 |
+
from scheduler import load_scheduler
|
| 10 |
+
from schemas import UserRequest, SteeringOutput, CONFIG
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
MAX_RETRIES = 10
|
| 14 |
+
MAX_RETRY_WAIT_TIME = 75
|
| 15 |
+
MIN_RETRY_WAIT_TIME = 5
|
| 16 |
+
ENDPOINT_ALIVE = False
|
| 17 |
+
|
| 18 |
+
HF_TOKEN = os.getenv('HF_TOKEN')
|
| 19 |
+
API_URL = "https://a6k5m81qw14hkvhz.us-east-1.aws.endpoints.huggingface.cloud"
|
| 20 |
+
headers = {
|
| 21 |
+
"Accept" : "application/json",
|
| 22 |
+
"Authorization": f"Bearer {HF_TOKEN}",
|
| 23 |
+
"Content-Type": "application/json"
|
| 24 |
+
}
|
| 25 |
|
| 26 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s:%(message)s')
|
| 27 |
logger = logging.getLogger(__name__)
|
| 28 |
|
| 29 |
+
model_name = "DeepSeek-R1-Distill-Qwen-7B"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
examples = pd.read_csv("assets/examples.csv")
|
| 31 |
+
instances = {}
|
| 32 |
+
scheduler = load_scheduler()
|
| 33 |
+
|
| 34 |
|
| 35 |
HEAD = """
|
| 36 |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha512-Evv84Mr4kqVGRNSgIGL/F/aIDqQb7xQ2vcrdIwxfjThSH8CSR7PBEakCr51Ck+w+/U6swU2Im1vVX0SVk9ABhg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
|
| 37 |
"""
|
| 38 |
|
| 39 |
HTML = f"""
|
| 40 |
+
<div id="banner">
|
| 41 |
+
<h1 style="font-size: 32px; line-height: 1.5em; margin-bottom: 0em;">
|
| 42 |
+
<img src="/gradio_api/file=assets/rudder_3094973.png" style="display: inline; height: 1.5em;"> LLM Censorship Steering
|
| 43 |
+
</h1>
|
| 44 |
+
<div id="cover" style="height: 130px;">
|
| 45 |
+
<img style="height: 100%; padding-top: 0.5em;" src="/gradio_api/file=assets/demo-cover.png">
|
| 46 |
</div>
|
| 47 |
</div>
|
| 48 |
"""
|
| 49 |
|
| 50 |
CSS = """
|
| 51 |
+
div#banner {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
display: flex;
|
| 53 |
+
flex-direction: column;
|
| 54 |
+
align-items: center;
|
| 55 |
+
justify-content: center;
|
| 56 |
+
}
|
| 57 |
+
div#component-8 .form {
|
| 58 |
+
padding-top: 7.5px;
|
| 59 |
+
background: var(--block-background-fill);
|
| 60 |
+
}
|
| 61 |
+
div#component-9 {
|
| 62 |
+
.toggle-label {color: var(--body-text-color);}
|
| 63 |
+
span p {
|
| 64 |
+
font-size: var(--block-info-text-size);
|
| 65 |
+
line-height: var(--line-sm);
|
| 66 |
+
color: var(--block-label-text-color);
|
| 67 |
+
}
|
| 68 |
}
|
| 69 |
+
div#component-10 {
|
| 70 |
+
.slider_input_container span {color: var(--body-text-color);}
|
| 71 |
+
.slider_input_container {
|
| 72 |
+
display: flex;
|
| 73 |
+
flex-wrap: wrap;
|
| 74 |
+
input {appearance: auto;}
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
div#component-10 .wrap .head {
|
| 78 |
justify-content: unset;
|
| 79 |
label {margin-right: var(--size-2);}
|
| 80 |
+
label span {
|
| 81 |
+
color: var(--body-text-color);
|
| 82 |
+
margin-bottom: 0;
|
| 83 |
+
}
|
| 84 |
}
|
| 85 |
"""
|
| 86 |
|
| 87 |
|
| 88 |
slider_info = """\
|
| 89 |
<div style='display: flex; justify-content: space-between; line-height: normal;'>\
|
| 90 |
+
<span style='font-size: var(--block-info-text-size); color: var(--block-label-text-color);'>Less censorship</span>\
|
| 91 |
+
<span style='font-size: var(--block-info-text-size); color: var(--block-label-text-color);'>More censorship</span>\
|
| 92 |
</div>\
|
| 93 |
"""\
|
| 94 |
|
|
|
|
| 118 |
""" % (slider_info, slider_ticks)
|
| 119 |
|
| 120 |
|
| 121 |
+
def initialize_instance(request: gr.Request):
|
| 122 |
+
instances[request.session_hash] = []
|
| 123 |
+
logger.info("Number of connections: %d", len(instances))
|
| 124 |
+
return request.session_hash
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
+
def cleanup_instance(request: gr.Request):
|
| 128 |
+
global ENDPOINT_ALIVE
|
| 129 |
+
|
| 130 |
+
session_id = request.session_hash
|
| 131 |
|
| 132 |
+
if session_id in instances:
|
| 133 |
with open("outputs.jsonl", "a") as f:
|
| 134 |
+
for data in instances[session_id]:
|
| 135 |
+
scheduler.append(data.model_dump())
|
| 136 |
+
json.dump(data.model_dump(), f)
|
| 137 |
+
f.write("\n")
|
| 138 |
+
|
| 139 |
+
del instances[session_id]
|
| 140 |
+
|
| 141 |
+
if len(instances) == 0:
|
| 142 |
+
ENDPOINT_ALIVE = False
|
| 143 |
+
|
| 144 |
+
logger.info("Number of connections: %d", len(instances))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
async def initialize_endpoint():
|
| 148 |
+
async with aiohttp.ClientSession() as session:
|
| 149 |
+
async with session.get(f"{API_URL}/health", headers=headers) as resp:
|
| 150 |
+
if resp.status == 200:
|
| 151 |
+
return True
|
| 152 |
+
else:
|
| 153 |
+
resp_text = await resp.text()
|
| 154 |
+
logger.error("API Error Code: %d, Message: %s", resp.status, resp_text)
|
| 155 |
+
return False
|
| 156 |
+
|
| 157 |
|
| 158 |
+
async def get_endpoint_state():
|
| 159 |
+
global ENDPOINT_ALIVE
|
| 160 |
+
n = 0
|
| 161 |
+
sleep_time = MAX_RETRY_WAIT_TIME
|
| 162 |
|
| 163 |
+
while n < MAX_RETRIES:
|
| 164 |
+
n += 1
|
| 165 |
+
|
| 166 |
+
if not ENDPOINT_ALIVE:
|
| 167 |
+
logger.info("Initializing inference endpoint")
|
| 168 |
+
yield "Initializing"
|
| 169 |
+
ENDPOINT_ALIVE = await initialize_endpoint()
|
| 170 |
+
|
| 171 |
+
if ENDPOINT_ALIVE:
|
| 172 |
+
logger.info("Inference endpoint is ready")
|
| 173 |
+
gr.Info("Inference endpoint is ready")
|
| 174 |
+
yield "Ready"
|
| 175 |
+
break
|
| 176 |
+
|
| 177 |
+
gr.Warning("Initializing inference endpoint\n(This may take 2~3 minutes)", duration=sleep_time)
|
| 178 |
+
await asyncio.sleep(sleep_time)
|
| 179 |
+
sleep_time = max(sleep_time * 0.8, MIN_RETRY_WAIT_TIME)
|
| 180 |
+
|
| 181 |
+
if n == MAX_RETRIES:
|
| 182 |
+
yield "Server Error"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
async def save_output(req: UserRequest, output: str):
|
| 186 |
+
if "</think>" in output:
|
| 187 |
+
p = [p for p in output.partition("</think>") if p != ""]
|
| 188 |
+
reasoning = "".join(p[:-1])
|
| 189 |
+
if len(p) == 1:
|
| 190 |
+
answer = None
|
| 191 |
+
else:
|
| 192 |
+
answer = p[-1]
|
| 193 |
else:
|
| 194 |
+
answer = None
|
| 195 |
+
reasoning = output
|
| 196 |
+
|
| 197 |
+
steering_output = SteeringOutput(**req.model_dump(), reasoning=reasoning, answer=answer)
|
| 198 |
+
instances[req.session_id].append(steering_output)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
async def generate(
|
| 202 |
+
session_id: str, prompt: str, steering: bool, coeff: float,
|
| 203 |
+
max_new_tokens: int, top_p: float, temperature: float
|
| 204 |
+
):
|
| 205 |
+
req = UserRequest(
|
| 206 |
+
session_id=session_id, prompt=prompt, steering=steering, coeff=coeff,
|
| 207 |
+
max_new_tokens=max_new_tokens, top_p=top_p, temperature=temperature
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
data = req.get_api_format()
|
| 211 |
+
logger.info("User Request: %s", data)
|
| 212 |
+
|
| 213 |
+
generated_text = ""
|
| 214 |
+
session = aiohttp.ClientSession()
|
| 215 |
+
|
| 216 |
+
async with session.post(f"{API_URL}/generate", headers=headers, json=data) as resp:
|
| 217 |
+
if resp.status == 200:
|
| 218 |
+
generated_text += "<think>"
|
| 219 |
+
async for chunk, _ in resp.content.iter_chunks():
|
| 220 |
+
generated_text += chunk.decode()
|
| 221 |
+
yield generated_text
|
| 222 |
+
else:
|
| 223 |
+
logger.error("API Error Ccode: %d, Error Message: %s", resp.status, resp.text())
|
| 224 |
+
raise gr.Error("API Server Error")
|
| 225 |
+
|
| 226 |
+
await session.close()
|
| 227 |
+
|
| 228 |
+
if generated_text != "":
|
| 229 |
+
await save_output(req, generated_text)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
async def post_process(session_id):
|
| 233 |
+
return instances[session_id][-1].request_id, gr.update(interactive=True), gr.update(interactive=True)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
async def output_feedback(session_id, request_id, feedback):
|
| 237 |
+
logger.info("Feedback received for request %s: %s", str(request_id), feedback)
|
| 238 |
+
try:
|
| 239 |
+
data = instances[session_id].pop()
|
| 240 |
+
if data.request_id == request_id:
|
| 241 |
+
if "Upvote" in feedback:
|
| 242 |
+
setattr(data, "upvote", True)
|
| 243 |
+
elif "Downvote" in feedback:
|
| 244 |
+
setattr(data, "upvote", False)
|
| 245 |
+
|
| 246 |
+
instances[session_id].append(data)
|
| 247 |
+
gr.Info("Thank you for your feedback!")
|
| 248 |
+
except:
|
| 249 |
+
logger.debug("Feedback submission error")
|
| 250 |
|
| 251 |
|
| 252 |
gr.set_static_paths(paths=[Path.cwd().absolute() / "assets"])
|
| 253 |
theme = gr.themes.Base(primary_hue="emerald", text_size=gr.themes.sizes.text_lg).set()
|
|
|
|
| 254 |
|
| 255 |
with gr.Blocks(title="LLM Censorship Steering", theme=theme, head=HEAD, css=CSS, js=JS) as demo:
|
| 256 |
+
session_id = gr.State()
|
| 257 |
+
request_id = gr.State()
|
| 258 |
+
endpoint_state = gr.State(get_endpoint_state)
|
| 259 |
+
|
| 260 |
gr.HTML(HTML)
|
| 261 |
|
| 262 |
+
@gr.render(inputs=endpoint_state, triggers=[endpoint_state.change])
|
| 263 |
+
def render_state(endpoint_state):
|
| 264 |
+
if endpoint_state == "Ready":
|
| 265 |
+
color = "green"
|
| 266 |
+
elif endpoint_state == "Server Error":
|
| 267 |
+
color = "red"
|
| 268 |
+
else:
|
| 269 |
+
color = "orange"
|
| 270 |
+
|
| 271 |
+
if endpoint_state != None:
|
| 272 |
+
gr.Markdown(f'🤖 {model_name} | Inference Endpoint State: <span style="color:{color}; font-weight: bold;">{endpoint_state}</span>')
|
| 273 |
+
|
| 274 |
with gr.Row():
|
| 275 |
with gr.Column(scale=1):
|
| 276 |
with gr.Row():
|
| 277 |
+
steer_toggle = Toggle(label="Steering", info="Turn off to generate original outputs", value=True, interactive=True, scale=2)
|
| 278 |
+
coeff = gr.Slider(label="Steering Coefficient:", value=-1.0, minimum=-2, maximum=2, step=0.1, scale=8, show_reset_button=False)
|
| 279 |
+
|
| 280 |
+
@gr.on(inputs=[steer_toggle], outputs=[steer_toggle, coeff], triggers=[steer_toggle.change])
|
| 281 |
+
def update_toggle(toggle_value):
|
| 282 |
+
if toggle_value is True:
|
| 283 |
+
return gr.update(label="Steering", info="Turn off to generate original outputs"), gr.update(interactive=True)
|
| 284 |
+
else:
|
| 285 |
+
return gr.update(label="No Steering", info="Turn on to steer model outputs"), gr.update(interactive=False)
|
| 286 |
|
| 287 |
with gr.Accordion("⚙️ Advanced Settings", open=False):
|
| 288 |
with gr.Row():
|
| 289 |
+
temperature = gr.Slider(0, 1, step=0.1, value=CONFIG["temperature"], interactive=True, label="Temperature", scale=2)
|
| 290 |
+
top_p = gr.Slider(0, 1, step=0.1, value=CONFIG["top_p"], interactive=True, label="Top p", scale=2)
|
| 291 |
+
max_new_tokens = gr.Number(CONFIG["max_new_tokens"], minimum=10, maximum=CONFIG["max_new_tokens"], interactive=True, label="Max new tokens", scale=1)
|
| 292 |
|
| 293 |
+
input_text = gr.Textbox(label="Input", placeholder="Enter your prompt here...", lines=6, interactive=True)
|
| 294 |
|
| 295 |
with gr.Row():
|
| 296 |
clear_btn = gr.ClearButton()
|
| 297 |
generate_btn = gr.Button("Generate", variant="primary")
|
| 298 |
|
| 299 |
with gr.Column(scale=1):
|
| 300 |
+
output = gr.Textbox(label="Output", lines=15, max_lines=15, interactive=False)
|
| 301 |
+
|
| 302 |
+
with gr.Row():
|
| 303 |
+
upvote_btn = gr.Button("👍 Upvote", interactive=False)
|
| 304 |
+
downvote_btn = gr.Button("👎 Downvote", interactive=False)
|
| 305 |
|
| 306 |
gr.HTML("<p>‼️ For research purposes, we log user inputs and generated outputs. Please avoid submitting any confidential or personal information.</p>")
|
| 307 |
gr.Markdown("#### Examples")
|
| 308 |
gr.Examples(examples=examples[examples["type"] == "sensitive"].prompt.tolist(), inputs=input_text, label="Sensitive")
|
| 309 |
gr.Examples(examples=examples[examples["type"] == "harmful"].prompt.tolist(), inputs=input_text, label="Harmful")
|
|
|
|
| 310 |
|
| 311 |
+
@gr.on(triggers=[clear_btn.click], outputs=[request_id, upvote_btn, downvote_btn])
|
| 312 |
+
def clear():
|
| 313 |
+
return None, gr.update(interactive=False), gr.update(interactive=False)
|
| 314 |
+
|
| 315 |
clear_btn.add([input_text, output])
|
| 316 |
+
generate_btn.click(
|
| 317 |
+
generate, inputs=[session_id, input_text, steer_toggle, coeff, max_new_tokens, top_p, temperature], outputs=output
|
| 318 |
+
).success(
|
| 319 |
+
post_process, inputs=session_id, outputs=[request_id, upvote_btn, downvote_btn]
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
upvote_btn.click(output_feedback, inputs=[session_id, request_id, upvote_btn])
|
| 323 |
+
downvote_btn.click(output_feedback, inputs=[session_id, request_id, downvote_btn])
|
| 324 |
+
|
| 325 |
+
demo.load(initialize_instance, outputs=session_id)
|
| 326 |
+
demo.unload(cleanup_instance)
|
| 327 |
|
| 328 |
+
|
| 329 |
if __name__ == "__main__":
|
| 330 |
+
demo.queue(default_concurrency_limit=5)
|
| 331 |
demo.launch(debug=True)
|
model.py
DELETED
|
@@ -1,118 +0,0 @@
|
|
| 1 |
-
import os, warnings
|
| 2 |
-
from operator import attrgetter
|
| 3 |
-
from typing import List, Dict, Callable, Tuple
|
| 4 |
-
|
| 5 |
-
import torch
|
| 6 |
-
import torch.nn.functional as F
|
| 7 |
-
from torchtyping import TensorType
|
| 8 |
-
from transformers import TextIteratorStreamer
|
| 9 |
-
from transformers import AutoTokenizer, BatchEncoding
|
| 10 |
-
from nnsight import LanguageModel
|
| 11 |
-
from nnsight.intervention import Envoy
|
| 12 |
-
|
| 13 |
-
warnings.filterwarnings("ignore")
|
| 14 |
-
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 15 |
-
|
| 16 |
-
config = {
|
| 17 |
-
"model_name": "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
|
| 18 |
-
"steering_vec": "activations/deepseek-r1-7b-steering-vec.pt",
|
| 19 |
-
"offset": "activations/deepseek-r1-7b-offset.pt",
|
| 20 |
-
"layer": 25,
|
| 21 |
-
"k": 200,
|
| 22 |
-
}
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def detect_module_attrs(model: LanguageModel) -> str:
|
| 26 |
-
if "model" in model._modules and "layers" in model.model._modules:
|
| 27 |
-
return "model.layers"
|
| 28 |
-
elif "transformers" in model._modules and "h" in model.transformers._modules:
|
| 29 |
-
return "transformers.h"
|
| 30 |
-
else:
|
| 31 |
-
raise Exception("Failed to detect module attributes.")
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def orthogonal_projection(a: TensorType[..., -1], unit_vec: TensorType[-1]) -> TensorType[..., -1]:
|
| 35 |
-
return a @ unit_vec.unsqueeze(-1) * unit_vec
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
def get_intervention_func(steering_vec: TensorType, offset=0, k=0, coeff=0) -> Callable:
|
| 39 |
-
"""Get function for model intervention."""
|
| 40 |
-
unit_vec = F.normalize(steering_vec, dim=-1)
|
| 41 |
-
rescaled_vec = unit_vec * k
|
| 42 |
-
return lambda acts: acts - orthogonal_projection(acts - offset, unit_vec) + coeff * rescaled_vec
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
class ModelBase:
|
| 47 |
-
def __init__(
|
| 48 |
-
self, model_name: str,
|
| 49 |
-
steering_vec: TensorType, offset: TensorType,
|
| 50 |
-
k: float, steering_layer: int,
|
| 51 |
-
tokenizer: AutoTokenizer = None, block_module_attr=None
|
| 52 |
-
):
|
| 53 |
-
if tokenizer is None:
|
| 54 |
-
self.tokenizer = self._load_tokenizer(model_name)
|
| 55 |
-
else:
|
| 56 |
-
self.tokenizer = tokenizer
|
| 57 |
-
self.model = self._load_model(model_name, self.tokenizer)
|
| 58 |
-
|
| 59 |
-
self.device = self.model.device
|
| 60 |
-
self.hidden_size = self.model.config.hidden_size
|
| 61 |
-
if block_module_attr is None:
|
| 62 |
-
self.block_modules = self.get_module(detect_module_attrs(self.model))
|
| 63 |
-
else:
|
| 64 |
-
self.block_modules = self.get_module(block_module_attr)
|
| 65 |
-
self.steering_layer = steering_layer
|
| 66 |
-
self.k = k
|
| 67 |
-
self.steering_vec, self.offset = self.set_dtype(steering_vec, offset)
|
| 68 |
-
|
| 69 |
-
def _load_model(self, model_name: str, tokenizer: AutoTokenizer) -> LanguageModel:
|
| 70 |
-
return LanguageModel(model_name, tokenizer=tokenizer, dispatch=True, trust_remote_code=True, device_map="auto", torch_dtype=torch.bfloat16)
|
| 71 |
-
|
| 72 |
-
def _load_tokenizer(self, model_name) -> AutoTokenizer:
|
| 73 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
| 74 |
-
tokenizer.padding_side = "left"
|
| 75 |
-
if not tokenizer.pad_token:
|
| 76 |
-
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 77 |
-
tokenizer.pad_token = tokenizer.eos_token
|
| 78 |
-
return tokenizer
|
| 79 |
-
|
| 80 |
-
def tokenize(self, prompt: str) -> BatchEncoding:
|
| 81 |
-
return self.tokenizer(prompt, padding=True, truncation=False, return_tensors="pt")
|
| 82 |
-
|
| 83 |
-
def get_module(self, attr: str) -> Envoy:
|
| 84 |
-
return attrgetter(attr)(self.model)
|
| 85 |
-
|
| 86 |
-
def set_dtype(self, *vars):
|
| 87 |
-
if len(vars) == 1:
|
| 88 |
-
return vars[0].to(self.model.dtype)
|
| 89 |
-
else:
|
| 90 |
-
return (var.to(self.model.dtype) for var in vars)
|
| 91 |
-
|
| 92 |
-
def apply_chat_template(self, instruction: str) -> List[str]:
|
| 93 |
-
messages = [{"role": "user", "content": instruction}]
|
| 94 |
-
return self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 95 |
-
|
| 96 |
-
def generate(self, prompt: str, streamer: TextIteratorStreamer, steering: bool, coeff: float, generation_config: Dict):
|
| 97 |
-
formatted_prompt = self.apply_chat_template(prompt)
|
| 98 |
-
inputs = self.tokenize(formatted_prompt)
|
| 99 |
-
|
| 100 |
-
if steering:
|
| 101 |
-
intervene_func = get_intervention_func(self.steering_vec, offset=self.offset, k=self.k, coeff=coeff)
|
| 102 |
-
|
| 103 |
-
with self.model.generate(inputs, do_sample=True, streamer=streamer, **generation_config):
|
| 104 |
-
self.block_modules.all()
|
| 105 |
-
acts = self.block_modules[self.steering_layer].output[0]
|
| 106 |
-
new_acts = intervene_func(acts)
|
| 107 |
-
self.block_modules[self.steering_layer].output[0][:] = new_acts
|
| 108 |
-
else:
|
| 109 |
-
inputs = inputs.to(self.device)
|
| 110 |
-
_ = self.model._model.generate(**inputs, do_sample=True, streamer=streamer, **generation_config)
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
def load_model() -> ModelBase:
|
| 114 |
-
steering_vec = torch.load(config['steering_vec'], weights_only=True)
|
| 115 |
-
offset = torch.load(config['offset'], weights_only=True)
|
| 116 |
-
model = ModelBase(config['model_name'], steering_vec=steering_vec, offset=offset, k=config['k'], steering_layer=config['layer'])
|
| 117 |
-
model.tokenizer.chat_template = model.tokenizer.chat_template.replace("<|Assistant|><think>\\n", "<|Assistant|><think>")
|
| 118 |
-
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,11 +1,4 @@
|
|
| 1 |
-
|
| 2 |
-
accelerate==0.33.0
|
| 3 |
-
nnsight==0.4.3
|
| 4 |
-
triton==3.1.0
|
| 5 |
-
torchtyping==0.1.5
|
| 6 |
-
tiktoken==0.8.0
|
| 7 |
-
transformers_stream_generator==0.0.5
|
| 8 |
-
zstandard==0.23.0
|
| 9 |
pandas==2.2.2
|
| 10 |
pyarrow==19.0.1
|
| 11 |
gradio_toggle==2.0.2
|
|
|
|
| 1 |
+
aiohttp==3.11.16
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
pandas==2.2.2
|
| 3 |
pyarrow==19.0.1
|
| 4 |
gradio_toggle==2.0.2
|
scheduler.py
CHANGED
|
@@ -2,7 +2,6 @@ import json
|
|
| 2 |
import logging
|
| 3 |
import tempfile
|
| 4 |
import uuid
|
| 5 |
-
from pathlib import Path
|
| 6 |
from typing import Optional, Union, Dict, List, Any
|
| 7 |
|
| 8 |
import pyarrow as pa
|
|
@@ -13,49 +12,38 @@ from huggingface_hub.hf_api import HfApi
|
|
| 13 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s:%(message)s')
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
return {"_type": "Value", "dtype": "binary"}
|
| 35 |
-
# Otherwise in last resort => convert it to a string
|
| 36 |
-
return {"_type": "Value", "dtype": "string"}
|
| 37 |
|
| 38 |
|
| 39 |
class ParquetScheduler(CommitScheduler):
|
| 40 |
"""
|
| 41 |
Reference: https://huggingface.co/spaces/Wauplin/space_to_dataset_saver
|
| 42 |
-
Usage:
|
| 43 |
-
|
|
|
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
>>> scheduler = ParquetScheduler(repo_id="my-parquet-dataset")
|
| 48 |
-
|
| 49 |
-
# Append some data to be uploaded
|
| 50 |
-
>>> scheduler.append({...})
|
| 51 |
-
>>> scheduler.append({...})
|
| 52 |
-
>>> scheduler.append({...})
|
| 53 |
-
```
|
| 54 |
-
|
| 55 |
-
The scheduler will automatically infer the schema from the data it pushes.
|
| 56 |
-
Optionally, you can manually set the schema yourself:
|
| 57 |
|
| 58 |
```py
|
|
|
|
| 59 |
>>> scheduler = ParquetScheduler(
|
| 60 |
... repo_id="my-parquet-dataset",
|
| 61 |
... schema={
|
|
@@ -65,13 +53,16 @@ class ParquetScheduler(CommitScheduler):
|
|
| 65 |
... "image": {"_type": "Image"},
|
| 66 |
... },
|
| 67 |
... )
|
|
|
|
|
|
|
|
|
|
| 68 |
"""
|
| 69 |
|
| 70 |
def __init__(
|
| 71 |
self,
|
| 72 |
*,
|
| 73 |
repo_id: str,
|
| 74 |
-
schema:
|
| 75 |
every: Union[int, float] = 5, # Number of minutes between each commits
|
| 76 |
path_in_repo: Optional[str] = "data",
|
| 77 |
repo_type: Optional[str] = "dataset",
|
|
@@ -80,6 +71,7 @@ class ParquetScheduler(CommitScheduler):
|
|
| 80 |
token: Optional[str] = None,
|
| 81 |
allow_patterns: Union[List[str], str, None] = None,
|
| 82 |
ignore_patterns: Union[List[str], str, None] = None,
|
|
|
|
| 83 |
hf_api: Optional[HfApi] = None,
|
| 84 |
) -> None:
|
| 85 |
super().__init__(
|
|
@@ -93,6 +85,7 @@ class ParquetScheduler(CommitScheduler):
|
|
| 93 |
token=token,
|
| 94 |
allow_patterns=allow_patterns,
|
| 95 |
ignore_patterns=ignore_patterns,
|
|
|
|
| 96 |
hf_api=hf_api,
|
| 97 |
)
|
| 98 |
|
|
@@ -113,29 +106,9 @@ class ParquetScheduler(CommitScheduler):
|
|
| 113 |
return
|
| 114 |
logger.info("Got %d item(s) to commit.", len(rows))
|
| 115 |
|
| 116 |
-
# Load images + create 'features' config for datasets library
|
| 117 |
-
schema: Dict[str, Dict] = self._schema or {}
|
| 118 |
-
path_to_cleanup: List[Path] = []
|
| 119 |
-
for row in rows:
|
| 120 |
-
for key, value in row.items():
|
| 121 |
-
# Infer schema (for `datasets` library)
|
| 122 |
-
if key not in schema:
|
| 123 |
-
schema[key] = _infer_schema(key, value)
|
| 124 |
-
|
| 125 |
-
# Load binary files if necessary
|
| 126 |
-
if schema[key]["_type"] in ("Image", "Audio"):
|
| 127 |
-
# It's an image or audio: we load the bytes and remember to cleanup the file
|
| 128 |
-
file_path = Path(value)
|
| 129 |
-
if file_path.is_file():
|
| 130 |
-
row[key] = {
|
| 131 |
-
"path": file_path.name,
|
| 132 |
-
"bytes": file_path.read_bytes(),
|
| 133 |
-
}
|
| 134 |
-
path_to_cleanup.append(file_path)
|
| 135 |
-
|
| 136 |
# Complete rows if needed
|
| 137 |
for row in rows:
|
| 138 |
-
for feature in
|
| 139 |
if feature not in row:
|
| 140 |
row[feature] = None
|
| 141 |
|
|
@@ -144,7 +117,7 @@ class ParquetScheduler(CommitScheduler):
|
|
| 144 |
|
| 145 |
# Add metadata (used by datasets library)
|
| 146 |
table = table.replace_schema_metadata(
|
| 147 |
-
{"huggingface": json.dumps({"info": {"features":
|
| 148 |
)
|
| 149 |
|
| 150 |
# Write to parquet file
|
|
@@ -163,5 +136,4 @@ class ParquetScheduler(CommitScheduler):
|
|
| 163 |
|
| 164 |
# Cleanup
|
| 165 |
archive_file.close()
|
| 166 |
-
|
| 167 |
-
path.unlink(missing_ok=True)
|
|
|
|
| 2 |
import logging
|
| 3 |
import tempfile
|
| 4 |
import uuid
|
|
|
|
| 5 |
from typing import Optional, Union, Dict, List, Any
|
| 6 |
|
| 7 |
import pyarrow as pa
|
|
|
|
| 12 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s:%(message)s')
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
+
def load_scheduler():
|
| 16 |
+
return ParquetScheduler(
|
| 17 |
+
repo_id="hannahcyberey/Censorship-Steering-Logs", every=10,
|
| 18 |
+
private=True,
|
| 19 |
+
squash_history=False,
|
| 20 |
+
schema={
|
| 21 |
+
"session_id": {"_type": "Value", "dtype": "string"},
|
| 22 |
+
"prompt": {"_type": "Value", "dtype": "string"},
|
| 23 |
+
"steering": {"_type": "Value", "dtype": "bool"},
|
| 24 |
+
"coeff": {"_type": "Value", "dtype": "float64"},
|
| 25 |
+
"top_p": {"_type": "Value", "dtype": "float64"},
|
| 26 |
+
"temperature": {"_type": "Value", "dtype": "float64"},
|
| 27 |
+
"reasoning": {"_type": "Value", "dtype": "string"},
|
| 28 |
+
"answer": {"_type": "Value", "dtype": "string"},
|
| 29 |
+
"upvote": {"_type": "Value", "dtype": "bool"},
|
| 30 |
+
"timestamp": {"_type": "Value", "dtype": "string"},
|
| 31 |
+
}
|
| 32 |
+
)
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
class ParquetScheduler(CommitScheduler):
|
| 36 |
"""
|
| 37 |
Reference: https://huggingface.co/spaces/Wauplin/space_to_dataset_saver
|
| 38 |
+
Usage:
|
| 39 |
+
Configure the scheduler with a repo id. Once started, you can add data to be uploaded to the Hub.
|
| 40 |
+
1 `.append` call will result in 1 row in your final dataset.
|
| 41 |
|
| 42 |
+
List of possible dtypes:
|
| 43 |
+
https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Value.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
```py
|
| 46 |
+
# Start scheduler
|
| 47 |
>>> scheduler = ParquetScheduler(
|
| 48 |
... repo_id="my-parquet-dataset",
|
| 49 |
... schema={
|
|
|
|
| 53 |
... "image": {"_type": "Image"},
|
| 54 |
... },
|
| 55 |
... )
|
| 56 |
+
|
| 57 |
+
# Append some data to be uploaded
|
| 58 |
+
>>> scheduler.append({...})
|
| 59 |
"""
|
| 60 |
|
| 61 |
def __init__(
|
| 62 |
self,
|
| 63 |
*,
|
| 64 |
repo_id: str,
|
| 65 |
+
schema: Dict[str, Dict[str, str]],
|
| 66 |
every: Union[int, float] = 5, # Number of minutes between each commits
|
| 67 |
path_in_repo: Optional[str] = "data",
|
| 68 |
repo_type: Optional[str] = "dataset",
|
|
|
|
| 71 |
token: Optional[str] = None,
|
| 72 |
allow_patterns: Union[List[str], str, None] = None,
|
| 73 |
ignore_patterns: Union[List[str], str, None] = None,
|
| 74 |
+
squash_history: Optional[bool] = False,
|
| 75 |
hf_api: Optional[HfApi] = None,
|
| 76 |
) -> None:
|
| 77 |
super().__init__(
|
|
|
|
| 85 |
token=token,
|
| 86 |
allow_patterns=allow_patterns,
|
| 87 |
ignore_patterns=ignore_patterns,
|
| 88 |
+
squash_history=squash_history,
|
| 89 |
hf_api=hf_api,
|
| 90 |
)
|
| 91 |
|
|
|
|
| 106 |
return
|
| 107 |
logger.info("Got %d item(s) to commit.", len(rows))
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
# Complete rows if needed
|
| 110 |
for row in rows:
|
| 111 |
+
for feature in self._schema:
|
| 112 |
if feature not in row:
|
| 113 |
row[feature] = None
|
| 114 |
|
|
|
|
| 117 |
|
| 118 |
# Add metadata (used by datasets library)
|
| 119 |
table = table.replace_schema_metadata(
|
| 120 |
+
{"huggingface": json.dumps({"info": {"features": self._schema}})}
|
| 121 |
)
|
| 122 |
|
| 123 |
# Write to parquet file
|
|
|
|
| 136 |
|
| 137 |
# Cleanup
|
| 138 |
archive_file.close()
|
| 139 |
+
|
|
|
schemas.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from datetime import datetime, timezone
|
| 3 |
+
from pydantic import BaseModel, Field
|
| 4 |
+
from pydantic.json_schema import SkipJsonSchema
|
| 5 |
+
|
| 6 |
+
CONFIG = {
|
| 7 |
+
"max_new_tokens": 3048,
|
| 8 |
+
"top_p": 0.95,
|
| 9 |
+
"temperature": 0.6
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
class UserRequest(BaseModel):
|
| 13 |
+
session_id: str
|
| 14 |
+
request_id: uuid.UUID = Field(uuid.uuid4())
|
| 15 |
+
prompt: str = None
|
| 16 |
+
steering: bool = True
|
| 17 |
+
coeff: float = -1.0
|
| 18 |
+
max_new_tokens: int = Field(CONFIG["max_new_tokens"], le=3048)
|
| 19 |
+
top_p: float = Field(CONFIG["top_p"], ge=0.0, le=1.0)
|
| 20 |
+
temperature: float = Field(CONFIG["temperature"], ge=0.0, le=1.0)
|
| 21 |
+
|
| 22 |
+
def get_api_format(self):
|
| 23 |
+
return {
|
| 24 |
+
"prompt": self.prompt,
|
| 25 |
+
"steering": self.steering,
|
| 26 |
+
"coeff": self.coeff,
|
| 27 |
+
"generation_config": {
|
| 28 |
+
"max_new_tokens": self.max_new_tokens,
|
| 29 |
+
"top_p": self.top_p,
|
| 30 |
+
"temperature": self.temperature
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SteeringOutput(UserRequest):
|
| 36 |
+
request_id: SkipJsonSchema[uuid.UUID] = Field(exclude=True)
|
| 37 |
+
max_new_tokens: SkipJsonSchema[int] = Field(exclude=True)
|
| 38 |
+
reasoning: str = None
|
| 39 |
+
answer: str = None
|
| 40 |
+
upvote: bool = None
|
| 41 |
+
timestamp: str = Field(datetime.now(timezone.utc).isoformat())
|