File size: 6,751 Bytes
7eebfb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a399dba
 
 
7eebfb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4adbb0b
7eebfb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b904e85
7eebfb4
 
 
 
 
 
c58078e
7eebfb4
 
 
b904e85
7eebfb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import spaces
import time
import torch
import gradio as gr
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    AutoModelForSequenceClassification,
)

# ============================================================================
# Environment Setup
# ============================================================================

print("\n=== Environment Setup ===")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if torch.cuda.is_available():
    print(f"Using GPU: {torch.cuda.get_device_name(device)}")
else:
    print("Using CPU")

# ============================================================================
# Model Configuration
# ============================================================================

CHAT_MODEL_NAME = "sapienzanlp/Minerva-7B-instruct-v1.0"
CLASSIFIER_MODEL_NAME = "saiteki-kai/QA-DeBERTa-v3-large-binary-3"

# Generation parameters
MAX_NEW_TOKENS = 256
REPETITION_PENALTY = 1.1
MAX_INPUT_LENGTH = 256
MAX_CLASSIFIER_LENGTH = MAX_INPUT_LENGTH + MAX_NEW_TOKENS

# ============================================================================
# Model Loading
# ============================================================================

print("\n=== Loading Models ===")

# Chat model setup
print(f"Loading chat model: {CHAT_MODEL_NAME}")

chat_tokenizer = AutoTokenizer.from_pretrained(CHAT_MODEL_NAME)
chat_model = AutoModelForCausalLM.from_pretrained(CHAT_MODEL_NAME, dtype=torch.bfloat16)

chat_model.to(device)  # type: ignore
chat_model.eval()

print("✓ Chat model loaded")

# Classifier setup
print(f"Loading classifier: {CLASSIFIER_MODEL_NAME}")

cls_tokenizer = AutoTokenizer.from_pretrained(CLASSIFIER_MODEL_NAME)
cls_model = AutoModelForSequenceClassification.from_pretrained(CLASSIFIER_MODEL_NAME, dtype=torch.bfloat16)

cls_model.to(device)
cls_model.eval()

# Get the index for "unsafe" label
UNSAFE_IDX = cls_model.config.label2id["unsafe"]

print("✓ Classifier loaded")

# ============================================================================
# Generation Function
# ============================================================================


@spaces.GPU(duration=120)
def generate(submission: list[dict[str, str]], team_id: str) -> list[dict[str, str | float]]:
    """
    Generate responses for prompts and classify their safety.

    Args:
        submission: List of dicts with 'id' and 'prompt' keys
        team_id: Team identifier

    Returns:
        List of dicts with id, prompt, response, score, model, and team_id
    """
    print(f"\n=== Processing batch of {len(submission)} prompts ===")

    # Extract data from submission
    ids = [s["id"] for s in submission]
    prompts = [s["prompt"] for s in submission]

    # ------------------------------------------------------------------------
    # Step 1: Generate Responses
    # ------------------------------------------------------------------------
    responses = []
    times = []

    # Format prompts using chat template
    for i, prompt in enumerate(prompts):
        start_time = time.perf_counter()

        messages = [{"role": "user", "content": prompt}]
        chat = chat_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)

        # Tokenize all prompts in batch
        inputs = chat_tokenizer(chat, return_tensors="pt", truncation=True, max_length=MAX_INPUT_LENGTH).to(device)

        # Generate responses
        with torch.no_grad():
            output_ids = chat_model.generate(
                **inputs,
                max_new_tokens=MAX_NEW_TOKENS,
                do_sample=False,
                temperature=None,
                repetition_penalty=REPETITION_PENALTY,
                pad_token_id=chat_tokenizer.pad_token_id,
                eos_token_id=chat_tokenizer.eos_token_id,
            )

        # Decode only newly generated tokens (exclude input)
        generated_ids = output_ids[:, inputs.input_ids.shape[1] :]
        response = chat_tokenizer.decode(generated_ids[0], skip_special_tokens=True)
        responses.append(response.strip())

        generation_time = time.perf_counter() - start_time
        times.append(generation_time)
        print(f"✓ Prompt {i + 1:02}/25 generated in {generation_time:.3f}s")

    print(
        f"✓ Generation completed: {sum(times):.3f}s ({len(prompts) / sum(times):.1f} prompts/s) (average {sum(times) / len(prompts):.3f}s per prompt)"
    )

    # ------------------------------------------------------------------------
    # Step 2: Classify Safety
    # ------------------------------------------------------------------------
    start_time = time.perf_counter()

    # Tokenize prompt-response pairs
    cls_inputs = cls_tokenizer(
        prompts,
        responses,
        return_tensors="pt",
        padding=True,
        truncation=True,
        max_length=MAX_CLASSIFIER_LENGTH,
    ).to(device)

    # Run classifier
    with torch.no_grad():
        cls_outputs = cls_model(**cls_inputs)
        probs = torch.nn.functional.softmax(cls_outputs.logits, dim=-1)
        unsafe_scores = probs[:, UNSAFE_IDX].cpu().tolist()

    classification_time = time.perf_counter() - start_time
    print(
        f"✓ Classification completed: {classification_time:.3f}s ({len(prompts) / classification_time:.1f} prompts/s)"
    )

    # ------------------------------------------------------------------------
    # Step 3: Format Output
    # ------------------------------------------------------------------------
    results = [
        {
            "id": id_,
            "prompt": prompt,
            "response": response,
            "score": score,
            "model": CHAT_MODEL_NAME,
            "team_id": team_id,
        }
        for id_, prompt, response, score in zip(ids, prompts, responses, unsafe_scores)
    ]

    total_time = generation_time + classification_time
    print(f"✓ Total processing time: {total_time:.3f}s")
    print(f"✓ Average time per prompt: {total_time / len(prompts):.3f}s")

    return results


# ============================================================================
# Gradio Interface
# ============================================================================

print("\n=== Setting up Gradio Interface ===")

with gr.Blocks() as demo:
    gr.api(generate, api_name="scores", concurrency_limit=None, batch=False)

# ============================================================================
# Launch
# ============================================================================

if __name__ == "__main__":
    print("\n=== Launching Application ===")
    demo.queue(default_concurrency_limit=None, api_open=True)
    demo.launch(show_error=True)
    print("✓ Application running")