malaika971 commited on
Commit
7280553
Β·
verified Β·
1 Parent(s): 5b7dfac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -38
app.py CHANGED
@@ -1,7 +1,3 @@
1
- # ==============================
2
- # INSTALL REQUIRED PACKAGES
3
- # ==============================
4
-
5
  # ==============================
6
  # IMPORTS
7
  # ==============================
@@ -9,44 +5,55 @@ import torch
9
  import re
10
  import time
11
  import gradio as gr
12
- from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
13
  from peft import PeftModel
 
 
14
 
15
  # ==============================
16
- # GPU STATUS FUNCTION
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  # ==============================
18
- import os
19
  def print_gpu():
20
- os.system("nvidia-smi")
 
 
 
21
 
22
  # ==============================
23
- # LOAD MODEL + LO-RA ADAPTER
24
  # ==============================
25
  BASE_MODEL = "mistralai/Mistral-7B-v0.1"
26
- MODEL_PATH = "/kaggle/input/datasets/malaikaahmed971/1epoch-cds-mistral4bit-training/mistral7b_fast/checkpoint-7125"
27
-
28
- print("πŸš€ Loading base model and LoRA adapter...")
29
 
30
- bnb_config = BitsAndBytesConfig(
31
- load_in_4bit=True,
32
- bnb_4bit_compute_dtype=torch.float16,
33
- bnb_4bit_use_double_quant=True,
34
- bnb_4bit_quant_type="nf4"
35
- )
36
 
37
  tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
38
 
 
39
  base_model = AutoModelForCausalLM.from_pretrained(
40
  BASE_MODEL,
41
- quantization_config=bnb_config,
42
- device_map="auto"
43
  )
44
 
45
  model = PeftModel.from_pretrained(base_model, MODEL_PATH)
46
  model.eval()
47
 
48
  # ==============================
49
- # CLEAN OUTPUT & METRICS FUNCTIONS
50
  # ==============================
51
  def clean_output(text):
52
  text = text.strip()
@@ -57,6 +64,9 @@ def clean_output(text):
57
  return before.strip() + "\n\nFinal Decision: " + decision_line.strip()
58
  return text
59
 
 
 
 
60
  def extract_label(text):
61
  text = text.lower()
62
  if "final decision" in text:
@@ -67,54 +77,74 @@ def extract_label(text):
67
  return "hate"
68
  return "unknown"
69
 
 
 
 
70
  def compute_metrics(output, post):
71
  out = output.lower()
72
  post = post.lower()
 
73
  htc = 1 if "final decision" in out else 0
 
74
  post_words = post.split()
75
  qf = 1 if any(word in out for word in post_words[:5]) else 0
 
76
  tgi_keywords = ["muslim","black","white","asian","women","men","jews","christian","pakistan","indian"]
77
  tgi = 1 if any(word in out for word in tgi_keywords) else 0
 
78
  pred = extract_label(out)
79
- cons = 1 if (pred=="hate" and "hate" in out) or (pred=="non_hate" and "not hate" in out) else 0
 
 
 
 
 
 
 
80
  return htc, qf, tgi, cons
81
 
82
  # ==============================
83
- # INFERENCE FUNCTION FOR GRADIO
84
  # ==============================
85
  def infer(post):
86
- print("\nπŸ“Š GPU STATUS BEFORE INFERENCE:")
87
  print_gpu()
88
-
89
- inputs = tokenizer(post, return_tensors="pt").to(model.device)
90
  token_count = inputs.input_ids.shape[1]
 
91
  start = time.time()
92
-
93
  with torch.no_grad():
94
  outputs = model.generate(
95
  **inputs,
96
- max_new_tokens=300,
97
  min_new_tokens=150,
98
  do_sample=False,
99
  repetition_penalty=1.15,
100
  pad_token_id=tokenizer.eos_token_id
101
  )
102
-
103
  end = time.time()
 
104
  output = tokenizer.decode(outputs[0], skip_special_tokens=True)
105
  response = clean_output(output.replace(post, "").strip())
 
106
  pred = extract_label(response)
107
  htc, qf, tgi, cons = compute_metrics(response, post)
108
-
109
- metrics = f"Prediction: {pred}\nHTC={htc}, QF={qf}, TGI={tgi}, Consistency={cons}\nTokens processed: {token_count}\nTime: {end-start:.2f} sec"
110
-
111
- print("\nπŸ“Š GPU STATUS AFTER INFERENCE:")
 
 
 
112
  print_gpu()
113
-
114
  return response, metrics
115
 
116
  # ==============================
117
- # CREATE GRADIO INTERFACE
118
  # ==============================
119
  iface = gr.Interface(
120
  fn=infer,
@@ -124,8 +154,10 @@ iface = gr.Interface(
124
  gr.Textbox(label="Metrics", lines=5)
125
  ],
126
  title="Hate Speech Rationales + Decision",
127
- description="Enter a social media post, and the model will generate step-by-step rationales and the final decision."
128
  )
129
 
130
- # Launch the app with public share link
131
- iface.launch(share=True)
 
 
 
 
 
 
 
1
  # ==============================
2
  # IMPORTS
3
  # ==============================
 
5
  import re
6
  import time
7
  import gradio as gr
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM
9
  from peft import PeftModel
10
+ import zipfile
11
+ import os
12
 
13
  # ==============================
14
+ # UNZIP MODEL
15
+ # ==============================
16
+ zip_path = "./1epoch-cds-mistral4bit-training.zip"
17
+ extract_path = "./1epoch-cds-mistral4bit-training"
18
+
19
+ if not os.path.exists(extract_path):
20
+ print("πŸ“¦ Extracting model...")
21
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
22
+ zip_ref.extractall(extract_path)
23
+ print("βœ… Done")
24
+ else:
25
+ print("βœ… Model already extracted")
26
+
27
+ # ==============================
28
+ # GPU STATUS FUNCTION (SAFE)
29
  # ==============================
 
30
  def print_gpu():
31
+ try:
32
+ os.system("nvidia-smi")
33
+ except:
34
+ print("No GPU (running on CPU)")
35
 
36
  # ==============================
37
+ # LOAD MODEL
38
  # ==============================
39
  BASE_MODEL = "mistralai/Mistral-7B-v0.1"
40
+ MODEL_PATH = "./1epoch-cds-mistral4bit-training/mistral7b_fast/checkpoint-7125"
 
 
41
 
42
+ print("πŸš€ Loading model...")
 
 
 
 
 
43
 
44
  tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
45
 
46
+ # CPU SAFE LOADING
47
  base_model = AutoModelForCausalLM.from_pretrained(
48
  BASE_MODEL,
49
+ device_map={"": "cpu"}
 
50
  )
51
 
52
  model = PeftModel.from_pretrained(base_model, MODEL_PATH)
53
  model.eval()
54
 
55
  # ==============================
56
+ # CLEAN OUTPUT
57
  # ==============================
58
  def clean_output(text):
59
  text = text.strip()
 
64
  return before.strip() + "\n\nFinal Decision: " + decision_line.strip()
65
  return text
66
 
67
+ # ==============================
68
+ # LABEL EXTRACTION
69
+ # ==============================
70
  def extract_label(text):
71
  text = text.lower()
72
  if "final decision" in text:
 
77
  return "hate"
78
  return "unknown"
79
 
80
+ # ==============================
81
+ # METRICS
82
+ # ==============================
83
  def compute_metrics(output, post):
84
  out = output.lower()
85
  post = post.lower()
86
+
87
  htc = 1 if "final decision" in out else 0
88
+
89
  post_words = post.split()
90
  qf = 1 if any(word in out for word in post_words[:5]) else 0
91
+
92
  tgi_keywords = ["muslim","black","white","asian","women","men","jews","christian","pakistan","indian"]
93
  tgi = 1 if any(word in out for word in tgi_keywords) else 0
94
+
95
  pred = extract_label(out)
96
+
97
+ if pred == "hate" and "hate" in out:
98
+ cons = 1
99
+ elif pred == "non_hate" and "not hate" in out:
100
+ cons = 1
101
+ else:
102
+ cons = 0
103
+
104
  return htc, qf, tgi, cons
105
 
106
  # ==============================
107
+ # INFERENCE FUNCTION
108
  # ==============================
109
  def infer(post):
110
+ print("\nπŸ“Š STATUS BEFORE:")
111
  print_gpu()
112
+
113
+ inputs = tokenizer(post, return_tensors="pt")
114
  token_count = inputs.input_ids.shape[1]
115
+
116
  start = time.time()
117
+
118
  with torch.no_grad():
119
  outputs = model.generate(
120
  **inputs,
121
+ max_new_tokens=300, # SAME as your original
122
  min_new_tokens=150,
123
  do_sample=False,
124
  repetition_penalty=1.15,
125
  pad_token_id=tokenizer.eos_token_id
126
  )
127
+
128
  end = time.time()
129
+
130
  output = tokenizer.decode(outputs[0], skip_special_tokens=True)
131
  response = clean_output(output.replace(post, "").strip())
132
+
133
  pred = extract_label(response)
134
  htc, qf, tgi, cons = compute_metrics(response, post)
135
+
136
+ metrics = f"""Prediction: {pred}
137
+ HTC={htc}, QF={qf}, TGI={tgi}, Consistency={cons}
138
+ Tokens processed: {token_count}
139
+ Time: {end-start:.2f} sec"""
140
+
141
+ print("\nπŸ“Š STATUS AFTER:")
142
  print_gpu()
143
+
144
  return response, metrics
145
 
146
  # ==============================
147
+ # GRADIO UI
148
  # ==============================
149
  iface = gr.Interface(
150
  fn=infer,
 
154
  gr.Textbox(label="Metrics", lines=5)
155
  ],
156
  title="Hate Speech Rationales + Decision",
157
+ description="Enter a post to get step-by-step reasoning + final decision"
158
  )
159
 
160
+ # ==============================
161
+ # LAUNCH
162
+ # ==============================
163
+ iface.launch()