---
title: QA_about_Party_affairs_assistant
canonical_url: "https://www.modelscope.cn/models/lzjune0315/QA_about_Party_affairs_assistant"
md_url: "https://www.modelscope.cn/models/lzjune0315/QA_about_Party_affairs_assistant.md"
repository: lzjune0315/QA_about_Party_affairs_assistant
chinese_name: "党务知识问答小助手"
last_updated: 2024-09-08
pipeline_tag: text-generation
tasks:
  - text-generation
parameters: 20.2M
tensor_type:
  - BF16
library_name:
  - safetensors
  - pytorch
frameworks:
  - Pytorch
downloads: 26
stars: 0
---

# QA_about_Party_affairs_assistant

> QA_about_Party_affairs_assistant - lzjune0315 在 ModelScope 开源的模型。党务知识问答模型

- **Repository**: lzjune0315/QA_about_Party_affairs_assistant
- **Tasks**: text-generation
- **Parameters**: 20.2M
- **Downloads**: 26
- **Stars**: 0
- **Last updated**: 2024-09-08

Source: https://www.modelscope.cn/models/lzjune0315/QA_about_Party_affairs_assistant

---

# ModelScope开源模型应用挑战赛-外星人战队党务知识问答小助手

本模型基于**qwen2-7b-instruct**模型，通过**LoRA**的训练方式，在党务知识数据混合通用数据的数据集上进行微调，适用于党务领域FAQ问答任务；包括但不局限于党员、入党积极分子分子学习等场景。

## 目录
- 数据准备
- 微调
- 推理

## 数据准备
数据集采自[党务问答网](https://wenda.12371.cn/liebiao.php?mod=wantanswer&action=hot)中的对话，利用python脚本获取提问，人工筛选问题答案。经训练后，发现遗忘问题严重。为解决该问题，我们在重新筛选党务知识数据集的基础上，将党务数据集混合通用微调数据集[通用微调数据集](https://www.modelscope.cn/datasets/iic/ms_bench)进行训练，训练效果明显好转。
获取党务知识数据的问题代码如下:
``` python
import requests  
from bs4 import BeautifulSoup  
import pandas as pd  
  
base_url = "https://wenda.12371.cn/liebiao.php?mod=forumdisplay&fid=3"  
page = 1  
def fetch_page(url):  
    headers = {  
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'  
  }  
    response = requests.get(url, headers=headers)  
    response.raise_for_status()  
    return response.text  
def parse_page(html):  
    soup = BeautifulSoup(html, 'html.parser')  
    items = soup.find_all('li', id=lambda x: x and x.startswith('normalthread_'))  
    data = []  
    for item in items:  
        title_tag = item.find('p', class_='questionTit')  
  
        title = title_tag.get_text(strip=True) if title_tag else 'N/A'  
  data.append({'title': title})  
  
    next_page = soup.find('a', class_='next')  
    next_page_url = next_page['href'] if next_page else None  
  
 return data, next_page_url  
  
def main():  
    global base_url  
    global page  
    all_data = []  
    while True:  
        url = f"{base_url}&page={page}"  
  html = fetch_page(url)  
        data, next_page_url = parse_page(html)  
        print(data[0]['title'])  
        all_data.extend(data)  
  
        if next_page_url:  
            base_url = f"https://wenda.12371.cn/{next_page_url}"  
  page += 1  
  else:  
            break  
  
 for item in all_data:  
        print(item['title'])  
  
    df = pd.DataFrame(all_data)  
    df.to_excel("D:\\dangwu\\问题收集.xlsx", index=False, engine='openpyxl')  
  
if __name__ == "__main__":  
    main()
```
数据集格式采用如下对话形式：
``` 
{"from": "user", "value": "线上转党组织关系，超过天未接收会怎么样？十二月份发起党组织关系转接，但接收地支部名称有误，导致接收地系统无法收到转接命令，期间由于系统问题，十二月和一月系统始终无法正常登录。请问这种情况下超过六十天未被接收会怎样，应该怎样解决呢？"},

{"from": "assistant", "value": "线上的流程，里面也是有转接日期的时间限制，一般不超过个月，超过了期限，介绍信无效。解决方式：原流程作废，重新发起组织关系转移的流程。"}

{"from": "user", "value": "党支部纪检委员必须单设吗？如果不必须单设，是可以组织委员兼任还是宣传委员兼任，或者是都可以？"},

{"from": "assistant", "value": "要求必须设置，可以由其他委员兼任。不建议组织委员兼任，一般由宣传委员兼任。"}
```
数据集格式处理脚本代码如下:
``` python
import json  
import os  
import re  
def remove_non_chinese_chars(text):  
    return re.sub(r'[^\u4e00-\u9fa5，。！？、；：“”‘’（）《》【】]', '', text)  
  
seen_client_data = set()  
def Fuc(path,output_file)  :  
    global seen_client_data  
    with open(path, 'r', encoding='utf-8') as infile:  
        original_data = json.load(infile)  
  
    output=""  
  user_count = 0  
  assistant_count = 0  
  for item in original_data:  
        content = remove_non_chinese_chars(item["content"])  
        if item["role"] == "client":  
            if content in seen_client_data:  
                return  
  seen_client_data.add(content)  
            data="{\\\"from\\\": \\\"user\\\", \\\"value\\\": \\\""+content+"\\\"}, "  
  user_count += 1  
  if (user_count - assistant_count != 1):  
            return  
 if item["role"]=="counselor" :  
            data = "{\\\"from\\\": \\\"assistant\\\", \\\"value\\\": \\\"" + content + "\\\"}, "  
  assistant_count += 1  
  output=output+data  
  if (user_count != assistant_count):  
        return  
  output="{\"conversations\": \"["+output+"]\", \"origin\": \"[]\"}"  
  output=output[:-21]+output[-19:]  
    with open(output_file, 'a', encoding='utf-8') as outfile:  
        outfile.write(output + '\n')  
    # print(output)  
  
folder_path = "C:\\Users\\86183\\Desktop\\data"  
output_file = "C:\\Users\\86183\\Desktop\\output.txt"  
  
try:  
    files_and_dirs = os.listdir(folder_path)  
  
    files = [f for f in files_and_dirs if os.path.isfile(os.path.join(folder_path, f))]  
  
    for file in files:  
        Fuc(os.path.join(folder_path, file), output_file)  
except FileNotFoundError:  
    print(f"文件夹 {folder_path} 未找到。")  
except PermissionError:  
    print(f"没有权限访问文件夹 {folder_path}。")  
except Exception as e:  
    print(f"发生错误: {e}")
```
最后将处理好的数据集上传至[ModelScope数据集](https://modelscope.cn/datasets/lzjune0315/output_dataset)，可直接在微调参数中使用。

##  微调
该党务知识小助手基于qwen2-7b-struct大模型，为节省显存，我们采用LoRA微调方法。
系统：采用modelscope:1.16.1-pytorch2.3.0tensorflow2.16.1-gpu-py310-cu121-ubuntu22.04镜像
显卡：NVIDIA A10
模型：qwen2-7b-instruct
框架：魔搭轻量训推框架SWIFT 接链接https://github.com/modelscope/ms-swift
显存：最高达到20.54G的显存占用
训练时长: 2d 20h 6m
用于训练的脚本如下:
```
CUDA_VISIBLE_DEVICES=0 \
swift sft \
    --model_type qwen2-7b-instruct \
    --sft_type lora \
    --output_dir output \
    --dataset output_dataset \
    --num_train_epochs 1 \
    --max_length 1024 \
    --check_dataset_strategy warning \
    --lora_rank 8 \
    --lora_alpha 32 \
    --lora_dropout_p 0.05 \
    --lora_target_modules ALL \
    --gradient_checkpointing true \
    --batch_size 1 \
    --learning_rate 5e-5 \
    --gradient_accumulation_steps 16 \
    --max_grad_norm 1.0 \
    --warmup_ratio 0.03 \
    --eval_steps 100 \
    --save_steps 100 \
    --save_total_limit 2 \
    --logging_steps 10
```
### 训练效果
eval_loss和eval_acc效果如下:

![eval_loss](./eval_loss.png)
![eval_acc](./eval_acc.png)
> 横轴为训练步数，纵轴分别为残差值和准确率

## 推理
推理脚本如下:

```
swift infer --ckpt_dir output/qwen2-7b-instruct/v0-20240902-123232/checkpoint-27400
```
> best checkpoint

该党务知识问答模型已经上传至[ModelScope](https://modelscope.cn/datasets/lzjune0315/output_dataset)
