Niansuh commited on
Commit
b767a5f
1 Parent(s): 16f4106

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -0
app.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ import torch
6
+
7
+
8
+ class ModelProcessor:
9
+ def __init__(self, repo_id="HuggingFaceTB/cosmo-1b"):
10
+ self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
11
+ # Initialize the tokenizer
12
+ self.tokenizer = AutoTokenizer.from_pretrained(repo_id, use_fast=True)
13
+
14
+ # Initialize and configure the model
15
+ self.model = AutoModelForCausalLM.from_pretrained(
16
+ repo_id, torch_dtype=torch.float16, device_map={"": self.device}, trust_remote_code=True
17
+ )
18
+ self.model.eval() # Set the model to evaluation mode
19
+
20
+ # Set padding token as end-of-sequence token
21
+ self.tokenizer.pad_token = self.tokenizer.eos_token
22
+
23
+
24
+ @torch.inference_mode()
25
+ def process_data_and_compute_statistics(self, prompt):
26
+ # Tokenize the prompt and move to the device
27
+ tokens = self.tokenizer(
28
+ prompt, return_tensors="pt", truncation=True, max_length=512
29
+ ).to(self.model.device)
30
+
31
+ # Get the model outputs and logits
32
+ outputs = self.model(tokens["input_ids"])
33
+ logits = outputs.logits
34
+
35
+ # Shift right to align with logits' prediction position
36
+ shifted_labels = tokens["input_ids"][..., 1:].contiguous()
37
+ shifted_logits = logits[..., :-1, :].contiguous()
38
+
39
+ # Calculate entropy
40
+ shifted_probs = torch.softmax(shifted_logits, dim=-1)
41
+ shifted_log_probs = torch.log_softmax(shifted_logits, dim=-1)
42
+ entropy = -torch.sum(shifted_probs * shifted_log_probs, dim=-1).squeeze()
43
+
44
+ # Flatten the logits and labels
45
+ logits_flat = shifted_logits.view(-1, shifted_logits.size(-1))
46
+ labels_flat = shifted_labels.view(-1)
47
+
48
+ # Calculate the negative log-likelihood loss
49
+ probabilities_flat = torch.softmax(logits_flat, dim=-1)
50
+ true_class_probabilities = probabilities_flat.gather(
51
+ 1, labels_flat.unsqueeze(1)
52
+ ).squeeze(1)
53
+ nll = -torch.log(
54
+ true_class_probabilities.clamp(min=1e-9)
55
+ ) # Clamp to prevent log(0)
56
+
57
+ ranks = (
58
+ shifted_logits.argsort(dim=-1, descending=True)
59
+ == shifted_labels.unsqueeze(-1)
60
+ ).nonzero()[:, -1]
61
+
62
+ if entropy.clamp(max=4).median() < 2.0:
63
+ return 1
64
+
65
+ return 1 if (ranks.clamp(max=4) * nll.clamp(max=4)).mean() < 5.2 else 0
66
+
67
+
68
+ processor = ModelProcessor()
69
+
70
+ @spaces.GPU(duration=180)
71
+ def detect(prompt):
72
+ prediction = processor.process_data_and_compute_statistics(prompt)
73
+ if prediction == 1:
74
+ return "The text is likely **generated** by a language model."
75
+ else:
76
+ return "The text is likely **not generated** by a language model."
77
+
78
+
79
+ with gr.Blocks(
80
+ css="""
81
+ .gradio-container {
82
+ max-width: 800px;
83
+ margin: 0 auto;
84
+ }
85
+ .gr-box {
86
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
87
+ padding: 20px;
88
+ border-radius: 4px;
89
+ }
90
+ .gr-button {
91
+ background-color: #007bff;
92
+ color: white; padding: 10px 20px;
93
+ border-radius: 4px;
94
+ }
95
+ .gr-button:hover {
96
+ background-color: }
97
+ .hyperlinks a {
98
+ margin-right: 10px;
99
+ }
100
+ """
101
+ ) as demo:
102
+ with gr.Row():
103
+ with gr.Column(scale=3):
104
+ gr.Markdown("# ENTELL Model Detection - ChatGPTBots.net")
105
+ with gr.Column(scale=1):
106
+ gr.HTML(
107
+ """
108
+ """,
109
+ elem_classes="hyperlinks",
110
+ )
111
+ with gr.Row():
112
+ with gr.Column():
113
+ prompt = gr.Textbox(
114
+ lines=8,
115
+ placeholder="Type your prompt here...",
116
+ label="Prompt",
117
+ )
118
+ submit_btn = gr.Button("Submit", variant="primary")
119
+ output = gr.Markdown()
120
+
121
+ submit_btn.click(fn=detect, inputs=prompt, outputs=output)
122
+
123
+ demo.launch()