s986103 commited on
Commit
67f5816
·
1 Parent(s): 83668ee

Updated app with custom DeBERTaV3 model

Browse files
Files changed (4) hide show
  1. __pycache__/models.cpython-310.pyc +0 -0
  2. app.py +29 -62
  3. models.py +37 -0
  4. requirements.txt +4 -1
__pycache__/models.cpython-310.pyc ADDED
Binary file (1.32 kB). View file
 
app.py CHANGED
@@ -1,63 +1,30 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer
4
+
5
+ from models import DebertaV3ForCustomClassification
6
+
7
+ tokenizer = AutoTokenizer.from_pretrained(
8
+ 's986103/DebertaV3ForCustomClassification')
9
+
10
+ model = DebertaV3ForCustomClassification.from_pretrained(
11
+ 's986103/DebertaV3ForCustomClassification')
12
+ model.eval()
13
+
14
+
15
+ def classify_text(text):
16
+ inputs = tokenizer(text, return_tensors="pt",
17
+ truncation=True, padding=True)
18
+ with torch.no_grad():
19
+ logits = model(**inputs)
20
+ prediction = torch.argmax(logits, dim=1).item()
21
+ return prediction
22
+
23
+
24
+ iface = gr.Interface(fn=classify_text,
25
+ inputs="text",
26
+ outputs="label",
27
+ description="自動作文評分")
28
+
29
+ # 啟動 UI
30
+ iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from transformers import DebertaV2Model, DebertaV2PreTrainedModel
4
+
5
+
6
+ class DebertaV3ForCustomClassification(DebertaV2PreTrainedModel):
7
+ def __init__(self, config):
8
+ super().__init__(config)
9
+ self.deberta = DebertaV2Model(config) # 使用 DebertaV2 作为基础模型
10
+ self.dropout = nn.Dropout(0.1) # 添加一个 dropout 层
11
+ self.classifier = nn.Linear(
12
+ config.hidden_size, config.num_labels) # fully connected 层
13
+ self.config = config # 保存配置
14
+
15
+ def forward(self, input_ids, attention_mask=None, token_type_ids=None, labels=None):
16
+ # 获取 DeBERTaV3 的输出
17
+ outputs = self.deberta(
18
+ input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)
19
+
20
+ # 使用 Mean Pooling
21
+ # [batch_size, seq_len, hidden_size]
22
+ last_hidden_state = outputs.last_hidden_state
23
+ # [batch_size, hidden_size]
24
+ pooled_output = torch.mean(last_hidden_state, dim=1)
25
+
26
+ # Dropout and Fully Connected Layer
27
+ pooled_output = self.dropout(pooled_output)
28
+ logits = self.classifier(pooled_output) # [batch_size, num_labels]
29
+
30
+ # 如果提供了标签,则计算损失
31
+ loss = None
32
+ if labels is not None:
33
+ loss_fct = nn.CrossEntropyLoss()
34
+ loss = loss_fct(
35
+ logits.view(-1, self.config.num_labels), labels.view(-1))
36
+
37
+ return (loss, logits) if loss is not None else logits
requirements.txt CHANGED
@@ -1 +1,4 @@
1
- huggingface_hub==0.22.2
 
 
 
 
1
+ huggingface_hub==0.22.2
2
+ gradio
3
+ torch
4
+ transformers