├── ProactiveHealthGPT.png ├── README.md ├── bianque_icon.png ├── bianque_v1_app.py ├── bianque_v1_v2_app.py ├── bianque_v2_app.py ├── data └── cMedialog_example.csv ├── figure ├── coq.png ├── dataset_example.png ├── example_multi_turn.png ├── example_test1.png └── example_test2.png ├── models ├── __init__.py └── t5 │ ├── __init__.py │ ├── configuration_t5.py │ ├── modeling_t5.py │ └── tokenization_t5.py ├── proactivehealthgpt_py38.yml ├── py38_conda_env.yml ├── requirements.txt ├── scripts └── run_train_model_bianque.sh ├── train_model.py ├── train_model_args.py └── utils ├── __init__.py └── prompt_dataset.py /ProactiveHealthGPT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scutcyr/BianQue/38c5b3b15df68de375e8bab5394e0a3734336483/ProactiveHealthGPT.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [扁鹊(BianQue)]((https://github.com/scutcyr/BianQue)) 2 |

3 | 4 |

5 |

6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

15 | 16 | 基于主动健康的主动性、预防性、精确性、个性化、共建共享、自律性六大特征,华南理工大学未来技术学院-广东省数字孪生人重点实验室开源了中文领域生活空间主动健康大模型基座ProactiveHealthGPT,包括: 17 | * 经过千万规模中文健康对话数据指令微调的[生活空间健康大模型扁鹊(BianQue)](https://github.com/scutcyr/BianQue) 18 | * 经过百万规模心理咨询领域中文长文本指令与多轮共情对话数据联合指令微调的[心理健康大模型灵心(SoulChat)](https://github.com/scutcyr/SoulChat) 19 | 20 | 我们期望,**生活空间主动健康大模型基座ProactiveHealthGPT** 可以帮助学术界加速大模型在慢性病、心理咨询等主动健康领域的研究与应用。本项目为 **生活空间健康大模型扁鹊(BianQue)** 。 21 | 22 | ## 最近更新 23 | - 👏🏻 2023.07.07: 心理健康大模型灵心(SoulChat)在线内测版本启用,欢迎点击链接使用:[灵心内测版](https://soulchat.iai007.cloud/)。 24 | - 👏🏻 2023.07.01: 感谢[PULSE]([PULSE](https://github.com/openmedlab/PULSE))团队提供的Elo评测,点击[链接](https://github.com/openmedlab/PULSE#elo%E8%AF%84%E6%B5%8B)查看详情。 25 | - 👏🏻 2023.06.24: 本项目被收录到[中国大模型列表](https://github.com/wgwang/LLMs-In-China),为国内首个开源的具备多轮问询与建议能力的健康大模型。 26 | - 👏🏻 2023.06.09: 增加Windows下环境配置,详情见本文件的小节:【补充】Windows下的用户推荐参考如下流程配置环境。 27 | - 👏🏻 2023.06.06: 扁鹊-2.0模型开源,详情见[BianQue-2.0](https://huggingface.co/scutcyr/BianQue-2)。 28 | - 👏🏻 2023.06.06: 具备共情与倾听能力的灵心健康大模型SoulChat发布,详情见:[灵心健康大模型SoulChat:通过长文本咨询指令与多轮共情对话数据集的混合微调,提升大模型的“共情”能力 ](https://huggingface.co/scutcyr/SoulChat)。 29 | - 👏🏻 2023.04.22: 基于扁鹊-1.0模型的医疗问答系统Demo,详情访问:[https://huggingface.co/spaces/scutcyr/BianQue](https://huggingface.co/spaces/scutcyr/BianQue) 30 | - 👏🏻 2023.04.22: 扁鹊-1.0版本模型发布,详情见:[扁鹊-1.0:通过混合指令和多轮医生问询数据集的微调,提高医疗聊天模型的“问”能力(BianQue-1.0: Improving the "Question" Ability of Medical Chat Model through finetuning with Hybrid Instructions and Multi-turn Doctor QA Datasets)](https://huggingface.co/scutcyr/BianQue-1.0) 31 | 32 | 33 | ## 扁鹊健康大数据BianQueCorpus 34 | 我们经过调研发现,在健康领域,用户通常不会在一轮交互当中清晰地描述自己的问题,而当前常见的开源医疗问答模型(例如:ChatDoctor、本草(HuaTuo,原名华驼 )、DoctorGLM、MedicalGPT-zh)侧重于解决单轮用户描述的问题,而忽略了“用户描述可能存在不足”的情况。哪怕是当前大火的ChatGPT也会存在类似的问题:如果用户不强制通过文本描述让ChatGPT采用一问一答的形式,ChatGPT也偏向于针对用户的描述,迅速给出它认为合适的建议和方案。然而,实际的医生与用户交谈往往会存在“医生根据用户当前的描述进行持续多轮的询问”。并且医生在最后根据用户提供的信息综合给出建议,如下图所示。我们把医生不断问询的过程定义为 **询问链(CoQ, Chain of Questioning)** ,当模型处于询问链阶段,其下一个问题通常由对话上下文历史决定。 35 | 36 |

37 | 38 |

39 | 40 | 41 | 我们结合当前开源的中文医疗问答数据集([MedDialog-CN](https://github.com/UCSD-AI4H/Medical-Dialogue-System)、[IMCS-V2](https://github.com/lemuria-wchen/imcs21)、[CHIP-MDCFNPC](https://tianchi.aliyun.com/dataset/95414)、[MedDG](https://tianchi.aliyun.com/dataset/95414)、[cMedQA2](https://github.com/zhangsheng93/cMedQA2)、[Chinese-medical-dialogue-data](https://github.com/Toyhom/Chinese-medical-dialogue-data)),分析其中的单轮/多轮特性以及医生问询特性,结合实验室长期自建的生活空间健康对话大数据,构建了千万级别规模的扁鹊健康大数据BianQueCorpus。对话数据通过“病人:xxx\n医生:xxx\n病人:xxx\n医生:”的形式统一为一种指令格式,如下图所示。 42 | 43 |

44 | 45 |

46 | 47 | 48 | ```data 49 | input: "病人:六岁宝宝拉大便都是一个礼拜或者10天才一次正常吗,要去医院检查什么项目\n医生:您好\n病人:六岁宝宝拉大便都是一个礼拜或者10天才一次正常吗,要去医院检查什么项目\n医生:宝宝之前大便什么样呢?多久一次呢\n病人:一般都是一个礼拜,最近这几个月都是10多天\n医生:大便干吗?\n病人:每次10多天拉的很多\n医生:" 50 | target: "成形还是不成形呢?孩子吃饭怎么样呢?" 51 | ``` 52 | 53 | 训练数据当中混合了大量target文本为**医生问询的内容**而非直接的建议,这将有助于提升AI模型的问询能力。 54 | 55 | 56 | ## 使用方法 57 | * 克隆本项目 58 | ```bash 59 | cd ~ 60 | git clone https://github.com/scutcyr/BianQue.git 61 | ``` 62 | 63 | * 安装依赖 64 | 需要注意的是torch的版本需要根据你的服务器实际的cuda版本选择,详情参考[pytorch安装指南](https://pytorch.org/get-started/previous-versions/) 65 | ```bash 66 | cd BianQue 67 | conda env create -n proactivehealthgpt_py38 --file proactivehealthgpt_py38.yml 68 | conda activate proactivehealthgpt_py38 69 | 70 | pip install cpm_kernels 71 | pip install torch==1.13.1+cu116 torchvision==0.14.1+cu116 torchaudio==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu116 72 | ``` 73 | 74 | * 【补充】Windows下的用户推荐参考如下流程配置环境 75 | ```bash 76 | cd BianQue 77 | conda create -n proactivehealthgpt_py38 python=3.8 78 | conda activate proactivehealthgpt_py38 79 | pip install torch==1.13.1+cu116 torchvision==0.14.1+cu116 torchaudio==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu116 80 | pip install -r requirements.txt 81 | pip install rouge_chinese nltk jieba datasets 82 | # 以下安装为了运行demo 83 | pip install streamlit 84 | pip install streamlit_chat 85 | ``` 86 | * 【补充】Windows下配置CUDA-11.6:[下载并且安装CUDA-11.6](https://developer.nvidia.com/cuda-11-6-0-download-archive?target_os=Windows&target_arch=x86_64&target_version=11&target_type=exe_local)、[下载cudnn-8.4.0,解压并且复制其中的文件到CUDA-11.6对应的路径](https://developer.nvidia.com/compute/cudnn/secure/8.4.0/local_installers/11.6/cudnn-windows-x86_64-8.4.0.27_cuda11.6-archive.zip),参考:[win11下利用conda进行pytorch安装-cuda11.6-泛用安装思路](https://blog.csdn.net/qq_34740266/article/details/129137794) 87 | 88 | * 在Python当中调用BianQue-2.0模型: 89 | ```python 90 | import torch 91 | from transformers import AutoModel, AutoTokenizer 92 | # GPU设置 93 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 94 | # 加载模型与tokenizer 95 | model_name_or_path = 'scutcyr/BianQue-2' 96 | model = AutoModel.from_pretrained(model_name_or_path, trust_remote_code=True).half() 97 | model.to(device) 98 | tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True) 99 | 100 | # 单轮对话调用模型的chat函数 101 | user_input = "我的宝宝发烧了,怎么办?" 102 | input_text = "病人:" + user_input + "\n医生:" 103 | response, history = model.chat(tokenizer, query=input_text, history=None, max_length=2048, num_beams=1, do_sample=True, top_p=0.75, temperature=0.95, logits_processor=None) 104 | 105 | # 多轮对话调用模型的chat函数 106 | # 注意:本项目使用"\n病人:"和"\n医生:"划分不同轮次的对话历史 107 | # 注意:user_history比bot_history的长度多1 108 | user_history = ['你好', '我最近失眠了'] 109 | bot_history = ['我是利用人工智能技术,结合大数据训练得到的智能医疗问答模型扁鹊,你可以向我提问。'] 110 | # 拼接对话历史 111 | context = "\n".join([f"病人:{user_history[i]}\n医生:{bot_history[i]}" for i in range(len(bot_history))]) 112 | input_text = context + "\n病人:" + user_history[-1] + "\n医生:" 113 | 114 | response, history = model.chat(tokenizer, query=input_text, history=None, max_length=2048, num_beams=1, do_sample=True, top_p=0.75, temperature=0.95, logits_processor=None) 115 | ``` 116 | 117 | * 启动服务 118 | 119 | 本项目提供了[bianque_v2_app.py](./bianque_v2_app.py)作为BianQue-2.0模型的使用示例,通过以下命令即可开启服务,然后,通过http://:9005访问。 120 | ```bash 121 | streamlit run bianque_v2_app.py --server.port 9005 122 | ``` 123 | 特别地,在[bianque_v2_app.py](./bianque_v2_app.py)当中, 124 | 可以修改以下代码更换指定的显卡: 125 | ```python 126 | os.environ['CUDA_VISIBLE_DEVICES'] = '1' 127 | ``` 128 | **对于Windows单显卡用户,需要修改为:```os.environ['CUDA_VISIBLE_DEVICES'] = '0'```,否则会报错!** 129 | 130 | 可以通过更改以下代码指定模型路径为本地路径: 131 | ```python 132 | model_name_or_path = "scutcyr/BianQue-2" 133 | ``` 134 | 135 | 我们还提供了[bianque_v1_app.py](./bianque_v1_app.py)作为BianQue-1.0模型的使用示例,以及[bianque_v1_v2_app.py](./bianque_v1_v2_app.py)作为BianQue-1.0模型和BianQue-2.0模型的联合使用示例。 136 | 137 | ## 扁鹊-2.0 138 | 基于扁鹊健康大数据BianQueCorpus,我们选择了 [ChatGLM-6B](https://huggingface.co/THUDM/chatglm-6b) 作为初始化模型,经过全量参数的指令微调训练得到了[新一代BianQue【BianQue-2.0】](https://huggingface.co/scutcyr/BianQue-2)。与扁鹊-1.0模型不同的是,扁鹊-2.0扩充了药品说明书指令、医学百科知识指令以及ChatGPT蒸馏指令等数据,强化了模型的建议与知识查询能力。以下为两个测试样例。 139 | 140 | 141 | * 样例1:宝宝特别喜欢打嗝,是什么原因啊,该怎么预防啊 142 |

143 | 144 |

145 | 146 | * 样例2:我外婆近来身体越来越差了,带她去医院检查,医生说她得了肾静脉血栓,我们全家都很担心,医生开了很多注射用低分子量肝素钙,我想问它的药理毒理? 147 |

148 | 149 |

150 | 151 | 152 | ## 扁鹊-2.0与扁鹊-1.0联合使用,兼顾多轮问询与出色的健康建议能力 153 | 通过以下命令实现联合使用扁鹊-2.0与扁鹊-1.0构建主动健康服务: 154 | ```bash 155 | streamlit run bianque_v1_v2_app.py --server.port 9005 156 | ``` 157 | 158 | 以下为应用例子:前面若干轮为经过扁鹊-1.0模型进行问询的过程,最后一轮回复为经过扁鹊-2.0模型的回答。 159 |

160 | 161 |

162 | 163 | 164 | ## 扁鹊-1.0 165 | 166 | **扁鹊-1.0(BianQue-1.0)** 是一个经过指令与多轮问询对话联合微调的医疗对话大模型。我们经过调研发现,在医疗领域,往往医生需要通过多轮问询才能进行决策,这并不是单纯的“指令-回复”模式。用户在咨询医生时,往往不会在最初就把完整的情况告知医生,因此医生需要不断进行询问,最后才能进行诊断并给出合理的建议。基于此,我们构建了 **扁鹊-1.0(BianQue-1.0)** ,拟在 **强化AI系统的问询能力** ,从而达到模拟医生问诊的过程。我们把这种能力定义为“望闻问切”当中的“问”。综合考虑当前中文语言模型架构、参数量以及所需要的算力,我们采用了[ClueAI/ChatYuan-large-v2](https://huggingface.co/ClueAI/ChatYuan-large-v2)作为基准模型,在8张 NVIDIA RTX 4090显卡上微调了1个epoch得到**扁鹊-1.0(BianQue-1.0)**,用于训练的**中文医疗问答指令与多轮问询对话混合数据集**包含了超过900万条样本,这花费了大约16天的时间完成一个epoch的训练。我们将计划围绕扁鹊模型的“望闻问切”能力,结合医学专家知识、多模态技术、多生理信号计算等,进行多个版本的模型迭代研究。扁鹊(BianQue)模型欢迎你的贡献!我们鼓励你在 [BianQue GitHub](https://github.com/scutcyr/BianQue) 页面报告问题、贡献 PR 并参与讨论。我们期待与更多的高校、医院、研究实验室、公司等进行合作,共同开展下一代扁鹊模型研究。对于此类需求(以及其他不适合在 GitHub 上提出的需求),请直接发送电子邮件至 [eeyirongchen@mail.scut.edu.cn](mailto:eeyirongchen@mail.scut.edu.cn)。 167 | 168 | 169 | ### 模型“问”能力示例 170 | “望闻问切”四诊法由扁鹊发明。“四诊法”(望、闻、问、切),是中医诊病的基本方法。其中,“问”的能力可以被建模到语言模型当中。我们把AI模型的“问”能力定义为: 171 | **“问”能力**:AI模型能够根据病人输入的信息,结合医学知识来进行**恰当的问询**,并且结合进一步的问询得到的病人的信息,给出“合适的诊断或建议”。“问”的过程通常是一个多轮对话过程。 172 | 173 | 以下是2个简单的例子: 174 | 175 | * **例子1** 176 | 用户:我最近感觉全身疲惫 177 | 扁鹊-1.0:是劳累了,还是熬夜了? 178 | 用户:这周都在熬夜赶论文 179 | 扁鹊-1.0:嗯,熬夜容易引起各种不适,如头晕、乏力、失眠、多梦等,多休息,可以口服谷维素、维生素B1和安神补脑液,避免熬夜。 180 | 181 | * **例子2** 182 | 用户:我最近经常失眠 183 | 扁鹊-1.0:失眠多久了? 184 | 用户:两周了 185 | 扁鹊-1.0:睡眠怎么样? 186 | 用户:上床几小时才睡得着 187 | 扁鹊-1.0:可以口服一些药物 188 | 用户:有具体推荐吗 189 | 扁鹊-1.0:需要先检查一下 190 | 用户:那我需要做什么检查? 191 | 扁鹊-1.0:心电图 192 | 193 | 194 | ### 使用方法 195 | 196 | #### 直接使用扁鹊-1.0模型 197 | 198 | ```python 199 | import os 200 | from transformers import T5Tokenizer, T5ForConditionalGeneration, AutoTokenizer 201 | import torch 202 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 203 | 204 | 205 | tokenizer = T5Tokenizer.from_pretrained("scutcyr/BianQue-1.0") 206 | model = T5ForConditionalGeneration.from_pretrained("scutcyr/BianQue-1.0") 207 | model = model.to(device) 208 | 209 | def preprocess(text): 210 | text = text.replace("\n", "\\n").replace("\t", "\\t") 211 | return text 212 | 213 | def postprocess(text): 214 | return text.replace("\\n", "\n").replace("\\t", "\t") 215 | 216 | def answer(user_history, bot_history, sample=True, top_p=1, temperature=0.7): 217 | '''sample:是否抽样。生成任务,可以设置为True; 218 | top_p:0-1之间,生成的内容越多样 219 | max_new_tokens=512 lost...''' 220 | 221 | if len(bot_history)>0: 222 | context = "\n".join([f"病人:{user_history[i]}\n医生:{bot_history[i]}" for i in range(len(bot_history))]) 223 | input_text = context + "\n病人:" + user_history[-1] + "\n医生:" 224 | else: 225 | input_text = "病人:" + user_history[-1] + "\n医生:" 226 | return "我是利用人工智能技术,结合大数据训练得到的智能医疗问答模型扁鹊,你可以向我提问。" 227 | 228 | 229 | input_text = preprocess(input_text) 230 | print(input_text) 231 | encoding = tokenizer(text=input_text, truncation=True, padding=True, max_length=768, return_tensors="pt").to(device) 232 | if not sample: 233 | out = model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_new_tokens=512, num_beams=1, length_penalty=0.6) 234 | else: 235 | out = model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_new_tokens=512, do_sample=True, top_p=top_p, temperature=temperature, no_repeat_ngram_size=3) 236 | out_text = tokenizer.batch_decode(out["sequences"], skip_special_tokens=True) 237 | print('医生: '+postprocess(out_text[0])) 238 | return postprocess(out_text[0]) 239 | 240 | answer_text = answer(user_history=["你好!", 241 | "我最近经常失眠", 242 | "两周了", 243 | "上床几小时才睡得着"], 244 | bot_history=["我是利用人工智能技术,结合大数据训练得到的智能医疗问答模型扁鹊,你可以向我提问。", 245 | "失眠多久了?", 246 | "睡眠怎么样?"]) 247 | ``` 248 | 249 | #### 使用个人数据在扁鹊-1.0模型基础上进一步微调模型 250 | * 环境创建 251 | 以下为在RTX 4090显卡,CUDA-11.6驱动配置下的环境配置 252 | ```bash 253 | conda env create -n bianque_py38 --file py38_conda_env.yml 254 | conda activate bianque_py38 255 | pip install torch==1.13.1+cu116 torchvision==0.14.1+cu116 torchaudio==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu116 256 | ``` 257 | * 数据集构建 258 | 参考[.data/cMedialog_example.csv](.data/cMedialog_example.csv)格式,构建你的数据集 259 | * 基于扁鹊-1.0模型微调你的模型 260 | 修改[./scripts/run_train_model_bianque.sh](./scripts/run_train_model_bianque.sh),通过绝对路径指定PREPROCESS_DATA,并且调整其他变量,然后运行: 261 | ```bash 262 | cd scripts 263 | bash run_train_model_bianque.sh 264 | ``` 265 | 266 | 267 | ## 声明 268 | 269 | **扁鹊-1.0(BianQue-1.0)** 当前仅经过1个epoch的训练,尽管模型具备了一定的医疗问询能力,但其仍然存在以下局限: 270 | * 训练数据来源于开源数据集以及互联网,尽管我们采用了严格的数据清洗流程,数据集当中仍然不可避免地存在大量噪声,这会使得部分回复产生错误; 271 | * 医生“问询”是一项复杂的能力,这是非医生群体所不具备的,当前的模型对于模拟“医生问询”过程是通过大量样本学习得到的,因此在问询过程当中,有可能出现一些奇异的提问风格。换一句话来说,当前版本的模型强化了“问”的能力,但是“望”、“闻”、“切”的能力仍待进一步研究! 272 | 273 | **扁鹊-2.0(BianQue-2.0)**使用了ChatGLM-6B 模型的权重,需要遵循其[MODEL_LICENSE](https://github.com/THUDM/ChatGLM-6B/blob/main/MODEL_LICENSE),因此,**本项目仅可用于您的非商业研究目的**。 274 | * 本项目提供的BianQue模型致力于提升大模型的健康对话能力(多轮问询及健康建议),然而,模型的输出文本具有一定的随机性,本项目不保证模型输出的文本完全适合于用户,用户在使用本模型时需要承担其带来的所有风险! 275 | * 您不得出于任何商业、军事或非法目的使用、复制、修改、合并、发布、分发、复制或创建BianQue模型的全部或部分衍生作品。 276 | * 您不得利用BianQue模型从事任何危害国家安全和国家统一、危害社会公共利益、侵犯人身权益的行为。 277 | * 您在使用BianQue模型时应知悉,其不能替代医生、心理医生等专业人士,不应过度依赖、服从、相信模型的输出,不能过度依赖于与BianQue模型聊天获取的健康建议。 278 | 279 | ## 致谢 280 | 本项目由[华南理工大学未来技术学院](https://www2.scut.edu.cn/ft/main.htm) 广东省数字孪生人重点实验室发起,得到了华南理工大学信息网络工程研究中心、电子与信息学院等学院部门的支撑,同时致谢广东省妇幼保健院、广州市妇女儿童医疗中心、中山大学附属第三医院、合肥综合性国家科学中心人工智能研究院等合作单位。 281 | 282 | 同时,我们感谢以下媒体或公众号对本项目的报道(排名不分先后): 283 | * 媒体报道 284 | [人民日报](https://wap.peopleapp.com/article/rmh36174922/rmh36174922)、[中国网](https://hs.china.com.cn/gd/83980.html)、[光明网](https://health.gmw.cn/2023-06/13/content_36628062.htm)、[TOM科技](https://tech.tom.com/202306/4526869977.html)、[未来网](http://www.zzfuture.cn/news/956.html)、[大众网](http://linyi.dzwww.com.3xw.site/xinwen/202306/t20230613_202306135667.htm)、[中国发展报道网](http://www.chinafzbdw.com/computer/13149.html?1686564408)、[中国日报网](http://energy.chinaduily.com.cn/c/2023/15205.html)、[新华资讯网](http://www.xinhuazxun.com/world/21762.html?1686564382)、[中华网](https://life.china.com/2023-06/12/content_215815.html)、[今日头条](https://www.toutiao.com/article/7243412314223952418/)、[搜狐](https://www.sohu.com/a/684501109_120159010)、[腾讯新闻](https://page.om.qq.com/page/OhSXIMEUtDtdg0rTi6aAoTbg0)、[网易新闻](https://www.163.com/dy/article/I70BJ9U00552UJUX.html)、[中国资讯网](http://www.chinazxun.com/world/23252.html?1686564532)、[中国传播网](http://www.chinachbo.com/a/view/11697.html?1686564509)、[中国都市报道网](http://www.zgdsbdw.com/meida/11273.html?1686564485)、[中华城市网](http://www.zhcsww.com/hot/2023/0612/9609.html?1686564434) 285 | 286 | * 公众号 287 | [广东实验室建设](https://mp.weixin.qq.com/s/gemlKfLg8c-AtjiV7uTUTQ)、[智能语音新青年](https://mp.weixin.qq.com/s/vBMKXUJoAIywkXY2nY60eA)、[深度学习与NLP](https://mp.weixin.qq.com/s/qSHLT8FbvohZESp-UCah6g)、[AINLP](https://mp.weixin.qq.com/s/EX3f9WblLKM8K_nSwhno_g) 288 | 289 | 290 | ## 引用 291 | ```bib 292 | @misc{chen2023bianque, 293 | title={BianQue: Balancing the Questioning and Suggestion Ability of Health LLMs with Multi-turn Health Conversations Polished by ChatGPT}, 294 | author={Yirong Chen and Zhenyu Wang and Xiaofen Xing and huimin zheng and Zhipei Xu and Kai Fang and Junhong Wang and Sihang Li and Jieling Wu and Qi Liu and Xiangmin Xu}, 295 | year={2023}, 296 | eprint={2310.15896}, 297 | archivePrefix={arXiv}, 298 | primaryClass={cs.CL} 299 | } 300 | ``` 301 | -------------------------------------------------------------------------------- /bianque_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scutcyr/BianQue/38c5b3b15df68de375e8bab5394e0a3734336483/bianque_icon.png -------------------------------------------------------------------------------- /bianque_v1_app.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 South China University of Technology and 3 | # Engineering Research Ceter of Ministry of Education on Human Body Perception. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | # Author: Chen Yirong 19 | # Date: 2023.03.14 20 | 21 | ''' 运行方式 22 | ```bash 23 | pip install streamlit # 第一次运行需要安装streamlit 24 | pip install streamlit_chat # 第一次运行需要安装streamlit_chat 25 | streamlit run bianque_v1_app.py --server.port 9001 26 | ``` 27 | 28 | ## 测试访问 29 | 30 | http://:9001 31 | 32 | ''' 33 | 34 | 35 | import os 36 | import torch 37 | import streamlit as st 38 | from streamlit_chat import message 39 | from transformers import T5Tokenizer, T5ForConditionalGeneration 40 | 41 | os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 默认使用0号显卡,避免Windows用户忘记修改该处 42 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 43 | 44 | model_name_or_path = "scutcyr/BianQue-1.0" 45 | tokenizer = T5Tokenizer.from_pretrained(model_name_or_path) 46 | 47 | 48 | def preprocess(text): 49 | text = text.replace("\n", "\\n").replace("\t", "\\t") 50 | return text 51 | 52 | def postprocess(text): 53 | return text.replace("\\n", "\n").replace("\\t", "\t") 54 | 55 | def answer(user_history, bot_history, sample=True, top_p=1, temperature=0.7): 56 | '''sample:是否抽样。生成任务,可以设置为True; 57 | top_p:0-1之间,生成的内容越多样 58 | max_new_tokens=512 lost...''' 59 | 60 | if len(bot_history)>0: 61 | context = "\n".join([f"病人:{user_history[i]}\n医生:{bot_history[i]}" for i in range(len(bot_history))]) 62 | input_text = context + "\n病人:" + user_history[-1] + "\n医生:" 63 | else: 64 | input_text = "病人:" + user_history[-1] + "\n医生:" 65 | return "我是利用人工智能技术,结合大数据训练得到的智能医疗问答模型扁鹊,你可以向我提问。" 66 | 67 | input_text = preprocess(input_text) 68 | print(input_text) 69 | encoding = tokenizer(text=input_text, truncation=True, padding=True, max_length=768, return_tensors="pt").to(device) 70 | if not sample: 71 | out = model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_new_tokens=512, num_beams=1, length_penalty=0.6) 72 | else: 73 | out = model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_new_tokens=512, do_sample=True, top_p=top_p, temperature=temperature, no_repeat_ngram_size=3) 74 | out_text = tokenizer.batch_decode(out["sequences"], skip_special_tokens=True) 75 | print('医生: '+postprocess(out_text[0])) 76 | return postprocess(out_text[0]) 77 | 78 | st.set_page_config( 79 | page_title="扁鹊健康支持模型(BianQue-1.0)", 80 | page_icon="⏺️", 81 | layout="wide", 82 | initial_sidebar_state="expanded", 83 | menu_items={ 84 | 'About': """ 85 | - 版本:扁鹊健康大模型(BianQue) V1.0.0 Beta 86 | - 机构:广东省数字孪生人重点实验室 87 | - 作者:陈艺荣、王振宇、徐志沛、方凱、李思航、王骏宏、邢晓芬、徐向民 88 | """ 89 | } 90 | ) 91 | 92 | st.header("⏺️扁鹊健康支持模型(BianQue-1.0) ") 93 | 94 | with st.expander("ℹ️ - 关于我们", expanded=False): 95 | st.write( 96 | """ 97 | - 版本:扁鹊健康大模型(BianQue) V1.0.0 Beta 98 | - 机构:广东省数字孪生人重点实验室 99 | - 作者:陈艺荣、王振宇、徐志沛、方凱、李思航、王骏宏、邢晓芬、徐向民 100 | """ 101 | ) 102 | 103 | # https://docs.streamlit.io/library/api-reference/performance/st.cache_resource 104 | @st.cache_resource 105 | def load_model(): 106 | model = T5ForConditionalGeneration.from_pretrained(model_name_or_path) 107 | model.to(device) 108 | print('Model Load done!') 109 | return model 110 | 111 | @st.cache_resource 112 | def load_tokenizer(): 113 | tokenizer = T5Tokenizer.from_pretrained(model_name_or_path) 114 | print('Tokenizer Load done!') 115 | return tokenizer 116 | 117 | model = load_model() 118 | tokenizer = load_tokenizer() 119 | 120 | 121 | if 'generated' not in st.session_state: 122 | st.session_state['generated'] = [] 123 | 124 | if 'past' not in st.session_state: 125 | st.session_state['past'] = [] 126 | 127 | 128 | user_col, ensure_col = st.columns([5, 1]) 129 | 130 | def get_text(): 131 | input_text = user_col.text_area("请在下列文本框输入您的咨询内容:","", key="input", placeholder="请输入您的咨询内容,并且点击Ctrl+Enter(或者发送按钮)确认内容") 132 | if ensure_col.button("发送", use_container_width=True): 133 | if input_text: 134 | return input_text 135 | 136 | user_input = get_text() 137 | 138 | if user_input: 139 | st.session_state.past.append(user_input) 140 | output = answer(st.session_state['past'],st.session_state["generated"]) 141 | st.session_state.generated.append(output) 142 | 143 | if st.session_state['generated']: 144 | for i in range(len(st.session_state['generated'])): 145 | if i == 0: 146 | # 147 | message(st.session_state['past'][i], is_user=True, key=str(i) + '_user', avatar_style="avataaars", seed=26) 148 | message(st.session_state["generated"][i]+"\n\n------------------\n以下回答由扁鹊健康模型自动生成,仅供参考!", key=str(i), avatar_style="avataaars", seed=5) 149 | else: 150 | message(st.session_state['past'][i], is_user=True, key=str(i) + '_user', avatar_style="avataaars", seed=26) 151 | #message(st.session_state["generated"][i], key=str(i)) 152 | message(st.session_state["generated"][i], key=str(i), avatar_style="avataaars", seed=5) 153 | 154 | if st.button("清理对话缓存"): 155 | # Clear values from *all* all in-memory and on-disk data caches: 156 | # i.e. clear values from both square and cube 157 | st.session_state['generated'] = [] 158 | st.session_state['past'] = [] 159 | -------------------------------------------------------------------------------- /bianque_v1_v2_app.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 South China University of Technology and 3 | # Engineering Research Ceter of Ministry of Education on Human Body Perception. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | # Author: Chen Yirong 19 | # Date: 2023.06.07 20 | 21 | ''' 运行方式 22 | ```bash 23 | pip install streamlit # 第一次运行需要安装streamlit 24 | pip install streamlit_chat # 第一次运行需要安装streamlit_chat 25 | streamlit run bianque_v1_v2_app.py --server.port 9005 26 | ``` 27 | 28 | ## 测试访问 29 | 30 | http://:9005 31 | 32 | ''' 33 | 34 | 35 | import os 36 | import torch 37 | import streamlit as st 38 | from streamlit_chat import message 39 | from transformers import AutoModel, AutoTokenizer 40 | from transformers import T5Tokenizer, T5ForConditionalGeneration 41 | 42 | 43 | os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 默认使用0号显卡,避免Windows用户忘记修改该处 44 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 45 | 46 | # 指定模型名称或路径 47 | bianque_v1_model_name_or_path = "scutcyr/BianQue-1.0" 48 | bianque_v2_model_name_or_path = "scutcyr/BianQue-2" 49 | 50 | bianque_v1_tokenizer = T5Tokenizer.from_pretrained(bianque_v1_model_name_or_path) 51 | bianque_v2_tokenizer = AutoTokenizer.from_pretrained(bianque_v2_model_name_or_path, trust_remote_code=True) 52 | 53 | 54 | def check_is_question(text): 55 | ''' 56 | 检查文本是否为问句 57 | ''' 58 | question_list = ["?", "?", "吗", "呢", "么", "什么", "有没有", "多少", "几次", "怎么样"] 59 | for token in question_list: 60 | if token in text: 61 | return True 62 | return False 63 | 64 | 65 | def preprocess(text): 66 | text = text.replace("\n", "\\n").replace("\t", "\\t") 67 | return text 68 | 69 | def postprocess(text): 70 | return text.replace("\\n", "\n").replace("\\t", "\t") 71 | 72 | def answer(user_history, bot_history, sample=True, bianque_v2_top_p=0.7, bianque_v2_temperature=0.95, bianque_v1_top_p=1, bianque_v1_temperature=0.7): 73 | '''sample:是否抽样。生成任务,可以设置为True; 74 | top_p=0.7, temperature=0.95时的生成效果较好 75 | top_p=1, temperature=0.7时提问能力会提升 76 | top_p:0-1之间,生成的内容越多样 77 | max_new_tokens=512 lost... 78 | ''' 79 | 80 | if len(bot_history)>0: 81 | context = "\n".join([f"病人:{user_history[i]}\n医生:{bot_history[i]}" for i in range(len(bot_history))]) 82 | input_text = context + "\n病人:" + user_history[-1] + "\n医生:" 83 | else: 84 | input_text = "病人:" + user_history[-1] + "\n医生:" 85 | #if user_history[-1] =="你好" or user_history[-1] =="你好!": 86 | return "我是利用人工智能技术,结合大数据训练得到的智能医疗问答模型扁鹊,你可以向我提问。" 87 | #return "我是生活空间健康对话大模型扁鹊,欢迎向我提问。" 88 | 89 | print(input_text) 90 | 91 | if len(bot_history) > 8: 92 | # 最多允许问8个问题 93 | if not sample: 94 | response, history = bianque_v2_model.chat(bianque_v2_tokenizer, query=input_text, history=None, max_length=2048, num_beams=1, do_sample=False, top_p=bianque_v2_top_p, temperature=bianque_v2_temperature, logits_processor=None) 95 | else: 96 | response, history = bianque_v2_model.chat(bianque_v2_tokenizer, query=input_text, history=None, max_length=2048, num_beams=1, do_sample=True, top_p=bianque_v2_top_p, temperature=bianque_v2_temperature, logits_processor=None) 97 | 98 | print('医生建议: '+response) 99 | 100 | return response 101 | 102 | 103 | if len(bot_history) == 1 or check_is_question(bot_history[-1]): 104 | input_text = preprocess(input_text) 105 | print(input_text) 106 | encoding = bianque_v1_tokenizer(text=input_text, truncation=True, padding=True, max_length=768, return_tensors="pt").to(device) 107 | if not sample: 108 | out = bianque_v1_model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_new_tokens=512, num_beams=1, length_penalty=0.6) 109 | else: 110 | out = bianque_v1_model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_new_tokens=512, do_sample=True, top_p=bianque_v1_top_p, temperature=bianque_v1_temperature, no_repeat_ngram_size=3) 111 | out_text = bianque_v1_tokenizer.batch_decode(out["sequences"], skip_special_tokens=True) 112 | response = postprocess(out_text[0]) 113 | print('医生提问: '+response) 114 | 115 | if check_is_question(response) and response not in bot_history: 116 | # 继续提问 117 | return response 118 | else: 119 | # 调用建议模型 120 | if not sample: 121 | response, history = bianque_v2_model.chat(bianque_v2_tokenizer, query=input_text, history=None, max_length=2048, num_beams=1, do_sample=False, top_p=bianque_v2_top_p, temperature=bianque_v2_temperature, logits_processor=None) 122 | else: 123 | response, history = bianque_v2_model.chat(bianque_v2_tokenizer, query=input_text, history=None, max_length=2048, num_beams=1, do_sample=True, top_p=bianque_v2_top_p, temperature=bianque_v2_temperature, logits_processor=None) 124 | 125 | print('医生建议: '+response) 126 | return response 127 | 128 | 129 | if not sample: 130 | response, history = bianque_v2_model.chat(bianque_v2_tokenizer, query=input_text, history=None, max_length=2048, num_beams=1, do_sample=False, top_p=bianque_v2_top_p, temperature=bianque_v2_temperature, logits_processor=None) 131 | else: 132 | response, history = bianque_v2_model.chat(bianque_v2_tokenizer, query=input_text, history=None, max_length=2048, num_beams=1, do_sample=True, top_p=bianque_v2_top_p, temperature=bianque_v2_temperature, logits_processor=None) 133 | 134 | print('医生建议: '+response) 135 | 136 | return response 137 | 138 | 139 | st.set_page_config( 140 | page_title="扁鹊健康大模型(BianQue) - Demo", 141 | page_icon="🧊", 142 | layout="wide", 143 | initial_sidebar_state="expanded", 144 | menu_items={ 145 | 'About': """ 146 | - 版本:扁鹊健康大模型(BianQue) V2.0.0 Beta 147 | - 机构:广东省数字孪生人重点实验室 148 | - 作者:陈艺荣、王振宇、徐志沛、方凱、李思航、王骏宏、邢晓芬、徐向民 149 | """ 150 | } 151 | ) 152 | 153 | st.header("扁鹊健康大模型(BianQue) - Demo") 154 | 155 | with st.expander("ℹ️ - 关于我们", expanded=False): 156 | st.write( 157 | """ 158 | - 版本:扁鹊健康大模型(BianQue) V2.0.0 Beta 159 | - 机构:广东省数字孪生人重点实验室 160 | - 作者:陈艺荣、王振宇、徐志沛、方凱、李思航、王骏宏、邢晓芬、徐向民 161 | """ 162 | ) 163 | 164 | # https://docs.streamlit.io/library/api-reference/performance/st.cache_resource 165 | 166 | @st.cache_resource 167 | def load_bianque_v2_model(): 168 | bianque_v2_model = AutoModel.from_pretrained(bianque_v2_model_name_or_path, trust_remote_code=True).half() 169 | #bianque_v2_model = T5ForConditionalGeneration.from_pretrained(bianque_v2_model_name_or_path) 170 | bianque_v2_model.to(device) 171 | print('bianque_v2 model Load done!') 172 | return bianque_v2_model 173 | 174 | @st.cache_resource 175 | def load_bianque_v2_tokenizer(): 176 | bianque_v2_tokenizer = AutoTokenizer.from_pretrained(bianque_v2_model_name_or_path, trust_remote_code=True) 177 | print('bianque_v2 tokenizer Load done!') 178 | return bianque_v2_tokenizer 179 | 180 | bianque_v2_model = load_bianque_v2_model() 181 | bianque_v2_tokenizer = load_bianque_v2_tokenizer() 182 | 183 | 184 | @st.cache_resource 185 | def load_bianque_v1_model(): 186 | bianque_v2_model = T5ForConditionalGeneration.from_pretrained(bianque_v1_model_name_or_path) 187 | bianque_v2_model.to(device) 188 | print('bianque_v1 model Load done!') 189 | return bianque_v2_model 190 | 191 | @st.cache_resource 192 | def load_bianque_v1_tokenizer(): 193 | bianque_v2_tokenizer = T5Tokenizer.from_pretrained(bianque_v1_model_name_or_path) 194 | print('bianque_v1 tokenizer Load done!') 195 | return bianque_v2_tokenizer 196 | 197 | bianque_v1_model = load_bianque_v1_model() 198 | bianque_v1_tokenizer = load_bianque_v1_tokenizer() 199 | 200 | 201 | if 'generated' not in st.session_state: 202 | st.session_state['generated'] = [] 203 | 204 | if 'past' not in st.session_state: 205 | st.session_state['past'] = [] 206 | 207 | 208 | user_col, ensure_col = st.columns([5, 1]) 209 | 210 | def get_text(): 211 | input_text = user_col.text_area("请在下列文本框输入您的咨询内容:","", key="input", placeholder="请输入您的咨询内容,并且点击Ctrl+Enter(或者发送按钮)确认内容") 212 | if ensure_col.button("发送", use_container_width=True): 213 | if input_text: 214 | return input_text 215 | 216 | user_input = get_text() 217 | 218 | if user_input: 219 | st.session_state.past.append(user_input) 220 | output = answer(st.session_state['past'],st.session_state["generated"]) 221 | st.session_state.generated.append(output) 222 | #bot_history.append(output) 223 | 224 | if st.session_state['generated']: 225 | for i in range(len(st.session_state['generated'])): 226 | if i == 0: 227 | # 228 | message(st.session_state['past'][i], is_user=True, key=str(i) + '_user', avatar_style="avataaars", seed=26) 229 | message(st.session_state["generated"][i]+"\n\n------------------\n以下回答由扁鹊健康模型自动生成,仅供参考!", key=str(i), avatar_style="avataaars", seed=5) 230 | else: 231 | message(st.session_state['past'][i], is_user=True, key=str(i) + '_user', avatar_style="avataaars", seed=26) 232 | #message(st.session_state["generated"][i], key=str(i)) 233 | message(st.session_state["generated"][i], key=str(i), avatar_style="avataaars", seed=5) 234 | 235 | 236 | if st.button("清理对话缓存"): 237 | # Clear values from *all* all in-memory and on-disk data caches: 238 | # i.e. clear values from both square and cube 239 | st.session_state['generated'] = [] 240 | st.session_state['past'] = [] 241 | -------------------------------------------------------------------------------- /bianque_v2_app.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 South China University of Technology and 3 | # Engineering Research Ceter of Ministry of Education on Human Body Perception. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | # Author: Chen Yirong 19 | # Date: 2023.06.07 20 | 21 | ''' 运行方式 22 | ```bash 23 | pip install streamlit # 第一次运行需要安装streamlit 24 | pip install streamlit_chat # 第一次运行需要安装streamlit_chat 25 | streamlit run bianque_v2_app.py --server.port 9005 26 | ``` 27 | 28 | ## 测试访问 29 | 30 | http://:9005 31 | 32 | ''' 33 | 34 | 35 | import os 36 | import torch 37 | import streamlit as st 38 | from streamlit_chat import message 39 | from transformers import AutoModel, AutoTokenizer 40 | 41 | 42 | os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 默认使用0号显卡,避免Windows用户忘记修改该处 43 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 44 | 45 | # 指定模型名称或路径 46 | model_name_or_path = "scutcyr/BianQue-2" 47 | 48 | tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True) 49 | 50 | 51 | def answer(user_history, bot_history, sample=True, top_p=0.7, temperature=0.95): 52 | '''sample:是否抽样。生成任务,可以设置为True; 53 | top_p=0.7, temperature=0.95时的生成效果较好 54 | top_p=1, temperature=0.7时提问能力会提升 55 | top_p:0-1之间,生成的内容越多样 56 | max_new_tokens=512 lost...''' 57 | 58 | if len(bot_history)>0: 59 | context = "\n".join([f"病人:{user_history[i]}\n医生:{bot_history[i]}" for i in range(len(bot_history))]) 60 | input_text = context + "\n病人:" + user_history[-1] + "\n医生:" 61 | else: 62 | input_text = "病人:" + user_history[-1] + "\n医生:" 63 | #if user_history[-1] =="你好" or user_history[-1] =="你好!": 64 | return "我是利用人工智能技术,结合大数据训练得到的智能医疗问答模型扁鹊,你可以向我提问。" 65 | #return "我是生活空间健康对话大模型扁鹊,欢迎向我提问。" 66 | 67 | print(input_text) 68 | 69 | if not sample: 70 | response, history = model.chat(tokenizer, query=input_text, history=None, max_length=2048, num_beams=1, do_sample=False, top_p=top_p, temperature=temperature, logits_processor=None) 71 | else: 72 | response, history = model.chat(tokenizer, query=input_text, history=None, max_length=2048, num_beams=1, do_sample=True, top_p=top_p, temperature=temperature, logits_processor=None) 73 | 74 | print('医生: '+response) 75 | 76 | return response 77 | 78 | st.set_page_config( 79 | page_title="扁鹊健康大模型(BianQue-2.0)", 80 | page_icon="🧊", 81 | layout="wide", 82 | initial_sidebar_state="expanded", 83 | menu_items={ 84 | 'About': """ 85 | - 版本:扁鹊健康大模型(BianQue) V2.0.0 Beta 86 | - 机构:广东省数字孪生人重点实验室 87 | - 作者:陈艺荣、王振宇、徐志沛、方凱、李思航、王骏宏、邢晓芬、徐向民 88 | """ 89 | } 90 | ) 91 | 92 | st.header("扁鹊健康大模型(BianQue-2.0)") 93 | 94 | with st.expander("ℹ️ - 关于我们", expanded=False): 95 | st.write( 96 | """ 97 | - 版本:扁鹊健康大模型(BianQue) V2.0.0 Beta 98 | - 机构:广东省数字孪生人重点实验室 99 | - 作者:陈艺荣、王振宇、徐志沛、方凱、李思航、王骏宏、邢晓芬、徐向民 100 | """ 101 | ) 102 | 103 | # https://docs.streamlit.io/library/api-reference/performance/st.cache_resource 104 | 105 | @st.cache_resource 106 | def load_model(): 107 | model = AutoModel.from_pretrained(model_name_or_path, trust_remote_code=True).half() 108 | model.to(device) 109 | print('Model Load done!') 110 | return model 111 | 112 | @st.cache_resource 113 | def load_tokenizer(): 114 | tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True) 115 | print('Tokenizer Load done!') 116 | return tokenizer 117 | 118 | model = load_model() 119 | tokenizer = load_tokenizer() 120 | 121 | if 'generated' not in st.session_state: 122 | st.session_state['generated'] = [] 123 | 124 | if 'past' not in st.session_state: 125 | st.session_state['past'] = [] 126 | 127 | 128 | user_col, ensure_col = st.columns([5, 1]) 129 | 130 | def get_text(): 131 | input_text = user_col.text_area("请在下列文本框输入您的咨询内容:","", key="input", placeholder="请输入您的咨询内容,并且点击Ctrl+Enter(或者发送按钮)确认内容") 132 | if ensure_col.button("发送", use_container_width=True): 133 | if input_text: 134 | return input_text 135 | 136 | user_input = get_text() 137 | 138 | if user_input: 139 | st.session_state.past.append(user_input) 140 | output = answer(st.session_state['past'],st.session_state["generated"]) 141 | st.session_state.generated.append(output) 142 | 143 | if st.session_state['generated']: 144 | for i in range(len(st.session_state['generated'])): 145 | if i == 0: 146 | # 147 | message(st.session_state['past'][i], is_user=True, key=str(i) + '_user', avatar_style="avataaars", seed=26) 148 | message(st.session_state["generated"][i]+"\n\n------------------\n以下回答由扁鹊健康模型自动生成,仅供参考!", key=str(i), avatar_style="avataaars", seed=5) 149 | else: 150 | message(st.session_state['past'][i], is_user=True, key=str(i) + '_user', avatar_style="avataaars", seed=26) 151 | #message(st.session_state["generated"][i], key=str(i)) 152 | message(st.session_state["generated"][i], key=str(i), avatar_style="avataaars", seed=5) 153 | 154 | if st.button("清理对话缓存"): 155 | # Clear values from *all* all in-memory and on-disk data caches: 156 | # i.e. clear values from both square and cube 157 | st.session_state['generated'] = [] 158 | st.session_state['past'] = [] 159 | -------------------------------------------------------------------------------- /data/cMedialog_example.csv: -------------------------------------------------------------------------------- 1 | "input","target","answer_choice","type" 2 | "病人:我和我男朋友再一起已经7年多了,但是我发现我有性冷淡,每当我男朋友提出行房,我就觉得十分的厌恶,我并不是讨厌他,只是非常非常的不想做.不知道是为什么,原先我们有过一段非常好的时期啊?可能是后来我觉得我男朋友越来越让我达不到状态,这样子持续了小半年,之后就觉得越来越对行房不感兴趣,还有之前因为保护不到位,我打过一次胎,哪次对我的心理也产生了一些阴影,再加上工作学习方面我一直顶者一些重压,人际关系最\n医生:","三个方面治疗性冷淡 3 |   1、身体 4 |   这个主要体现在身体疾病和不良生活习惯(性生活)。身体的疾病,个人建议找一个老道的中医,针对身体气血不同的情况,做出相应的调理。女性的身体上的疾病,用中医的调理之法,不伤身体,有助于恢复元气,增强气血,提升生命能量。(故而也提升性能量)。而针对不良生活习惯,不仅仅简单只是对性的影响,对我们的整个生命都是一种破坏。所以及早改正、断除。生命,是自己需要负责任的。 5 |   2、心理 6 |   性冷淡比较多的原因都是因为心理问题。如以上所谈到性恐惧,都是源于在此之前没有对性有一个较为健康全面的认知,从而造成后面对性的害怕乃至排斥。这个需要对性有正确的认识。性的本身是正常的,是美好的,是生命的起源。当然也有过去一些不良性经历,从而产生对性的厌恶,造成比较严重性冷淡。针对这种情况,女性朋友需要做的是有正确有效的心理咨询来辅助其走出心理阴影。这也非一朝一夕之功,不仅需要老师的指导,更需要自己的努力。心灵的成长,是一辈子的事。心理的创伤,在不断的进入心灵的探索中会被完全疗?。 7 |   3、配偶 8 |   女人的性冷淡,也有很大一部分来源于男人。而且可以说,绝大部分有男人的原因。如两性关系紧张甚至恶劣,这和男人逃脱不了关系吧。如女人性心理问题,男人为什么不能协助其走出心理阴影呢?多给些呵护,多些支持,多些关心,多些理解。当然更要多些沟通。两性关系中,很多的问题,本来有效沟通都是可以化解的。由于彼此的沉默,最后造成了关系的紧张。所以,我非常建议,在面对性的问题时,彼此一定要有表达,比如说身体感受,心理状况,以及自身的愿望。性的本身是促进二者更加和谐,更加美好的,但是如果因为性冷淡的这个问题,让彼此痛苦纠结,那就是大问题咯。","[]","medical_qa" 9 | "病人:无\n医生:","你好,可能是由于维生素缺乏或微量元素缺乏引起的,可以采用复合维生素片或21金维他效果较好,同时多喝开水,多吃蔬菜水果有利于症状的好转。","[]","medical_qa" 10 | "病人:意外怀孕怎么办伤害比较小请问怀孕四个月需要引产吗\n医生:","你好,一般怀孕49天内可以做药流的,对子宫的损伤较小,孕三个月内可以做人流,在做人流前需做B超检查排除宫外孕的可能,一周后复查B超排除子宫收缩不良或残留的可能,人流的费用估计在三百元左右,有地区差异,可以到当地咨询下。,你好,有肾结石引起疼痛严重的,你一般使用药物控制也不好,需要尽早碎石来缓解。所以现在可以考虑刨腹产。一般谈买37周,就算是足月了,所以孩子应该是没有问题。 ","[]","medical_qa" 11 | "病人:我最近一直都在拉稀,呈水样的,除了肚子疼其它也没什么不正常的,吃饭也还可以,但是长期这样拉下去也不是办法啊,请问:早上起来拉稀这是什么情况\n医生:","这种情况不太好说,是否是由于上次的胃肠炎的炎症没彻底清除呢。还是建议您去当地医院再作下化验,看一看如何除了其他细菌的传染,然后对症治疗,最好还是输液,这样效果好,见效快。祝您健康~~对于拉稀严重患者来说,建议立刻就诊,根据医生的意见来立刻治疗,不要盲目的使用药物,以免加重病情,谢谢。","[]","medical_qa" 12 | "病人:本人34岁,最近不知道怎么回事总是感觉恶心想吐,胃部阴阴作痛有时有灼热反酸的症状,去医院看过好了一段时间后又开始犯了,请问左下腹不舒服与什么有关\n医生:","可能与盆腔炎或肠道功能紊乱有关的,前者是属于妇科疾病的,后者属于内科疾病的。建议到医院复查做详细的检查才能确诊,除此之外,患者在治疗消化内科疾病期间,除了要对症治疗外,患者的饮食状况和心理状态也是尤为重要,患者一定要保持心情愉快,合理饮食,以免对消化内科疾病的恢复造成了不必要的影响。","[]","medical_qa" 13 | "病人:右脚第二脚趾发黑溃烂并有向脚背发展的趋势\n医生:","糖尿病是由遗传因素、免疫功能紊乱、等而引发的糖、蛋白质、脂肪、等一系列代谢紊乱综合征,典型病例可出现多尿、多饮、多食、消瘦等表现,即“三多一少”症状,长期坚持规范治疗是最重要的,包括:控制饮食,坚持适量运动锻炼,合理用药,降低脂肪比例,控制蛋白质摄入的饮食结构,对改善血糖耐量有较好的效果。忌辛辣食物多吃新鲜蔬菜水果,补充多种维生素口服二甲双胍,治疗","[]","medical_qa" 14 | "病人:晚上洗澡的时候发现自己龟头边上有一圈白色的,而且龟头好像有点皱有点红,近期发现自己上厕所也不是很顺畅,去医院检查了说是龟头炎,请问:得包皮瘙痒怎么治较好\n医生:","包皮瘙痒考虑炎症刺激,包皮龟头炎。包皮龟头炎的再次发生诱因有包皮过长现象,或者性伴侣有阴道炎症通过性生活引来交叉感染,抑或个人局部卫生未作好。建议;如果包皮瘙痒严重,建议你到正规医院复诊。留意局部清洁,每天有清水擦洗患处,不要搔抓,以免破溃传染期望能帮到你,祝您早日康复!包皮是可以康复的,但是一般治疗过程缓慢,且治疗后容易病发,因此治疗中一定积极互相配合医生的治疗,恰当用药,另外,治疗期间建议惯良好的生活习惯,恰当饮食,期望男性患者可以尽快康复!","[]","medical_qa" 15 | "病人:专家我想理解下男人该如何治疗前列腺炎呢?我父亲得了前列腺炎疾病了,一直久治不愈,不知晓该怎么办好?还请您帮帮我,谢谢!在乎怎样的帮助:男人该如何治疗前列腺炎呢?\n医生:","根据你叙述的这个症状,是可以治疗康复的,有这方面的不适,就需要有及时到正规医院明确。明确具体病情及时及早的治疗,这是很关键的。针对这类男性疾病针对性系统治疗,都是可以治疗康复,根据你的叙述,我还有些症状和之前的治疗等方面的问题还需要有更详细的问您,进一步理解你的病情。我再和你细谈,恭祝您早日康复。前列腺的治疗方法有许多,但是由于患者病情不同所以采用的医治方法也就不一样,因此患者需要有及时仔细检查诊断,方才能对症治疗。。","[]","medical_qa" 16 | "病人:主要症状一天前,莫名感觉排小便时候,尿道周围感觉不舒服,有点疼痛.\n医生:","尿路感染可分为上尿路感染和下尿路感染.上尿路常表现为发热达38度以上,尿频,尿急,尿痛,排尿不适,肾区压痛,叩击痛等.下尿路感染表现为一般无发热或低于38度.尿频,尿急,尿痛,很明显,有下腹痛.女性由于尿道短很容易引起尿路感染.指导意见:根据你提供的情况,有可能是尿路感染.药物有很多如四环素类,大环内酯类(红霉素,克拉霉素),喹诺酮类(氧氟沙星.环丙沙星).注意要多喝水,勤排尿.如过用药几天还没改善,请到医院就诊.","[]","medical_qa" 17 | "病人:请问服用黄体酮是不是可以让月经提前来? 18 | 请问药房有出售吗?\n医生:","吃黄体酮确实能提前来例假,连续吃七天,用药用药改变月经周期,月经周期改变对身体不好的,建议顺其自然就好,没必要把月经调到提前的,那样会把你的月经周期调乱,对于以后,有影响,平时多吃蔬菜水果多运动,保持气血充盛,身体健康就还好。","[]","medical_qa" 19 | "病人:医生说排卵是不固定的,由于我只剩下右侧输卵管,又好想赶紧怀孕,那要怎么才知道我这个月有排卵?\n医生:","你好,针对你的情况只有一侧输卵管受孕的几率大大降低,但是这侧卵巢的排卵正常,输卵管通畅,以及其他生育条件,包括男方的精子精液质量正常情况下,是可以受孕的。为了提高受孕几率,可以在孕前做好检查。,女性不孕的出现不仅仅会影响妇女的身体,还会导致妇科疾病的出现,因此,最好去医院的妇科做一下白带检查,找出病因后对症治疗,平时多注意自身卫生,保持会阴部皮肤清洁。","[]","medical_qa" 20 | "病人:问题描述:\n医生:"," 您好,建议你采用萎缩肿瘤血管的中草药治疗效果比较好,见效快,对晚期恶性肿瘤及静脉血管瘤都有独特的治疗效果,而且安全对身体不会产生任何的伤害,患者在短时间内就能看到治疗效果,但治愈也是希望比较大的. 21 | 以上是对“脖子静脉血管里长个瘤能治好吗?”这个问题的建议,希望对您有帮助,祝您健康! 22 | ","[]","medical_qa" 23 | "病人:以前去看过一次说是宫颈糜烂宫颈炎之类的病状开了吃的和洗的用的药吃的是抗宫颈炎软胶囊,用的是聚甲酚磺醛栓。曾经的治疗情况和效果:有些瘙痒有些豆腐渣类似于的白带再次出现在乎怎样的帮助:曾经人流过一次到今日已经有2年时间了一直没去看过医生最近有了男朋友后又再次出现了一些症状有些瘙痒有些豆腐渣类似于的白带再次出现味道也挺大的\n医生:","宫颈糜烂的早期症状:一般白带增多,异味重,外阴瘙痒疼痛。由于白带增多刺激,致使外阴炎或阴道炎,从而导致外阴痒痛。还会再次出现腰骶部疼痛、盆腔往下坠痛及痛经等症状。建议宫颈糜烂的治疗一般根据糜乱的程度来决定治疗方法。治疗宫颈糜烂的方法有一些,一般从西医来推测。西医的治疗方法比较有效:物理治疗适用于中度宫颈糜烂和重度宫颈糜烂患者。常用的方法有电熨法、激光疗法、冷冻疗法。和药物为好,具体医院治疗全程用药。","[]","medical_qa" 24 | "病人:最近胸口总是出现胸痛胸闷的情况,医院检查说是呼吸道疾病,但是吃药不怎么管用,最近 咳嗽加重,请问宝宝多大不得肺炎\n医生:","婴儿肺炎的症状之一就是吐泡泡和吐奶,不过吐泡泡并不能说明得了肺炎,这也是婴儿的一种自娱自乐的活动,婴儿太小,刚开始得了肺炎也不会有发烧症状,如果刚发病有可能听肺部也不一定能听出杂音,最好拍片。, 有很多种情况,患者是哪里的?全国有几个肺病医院,你可以去看看:北京京华友好医院,济南国医堂,武汉圣心医院","[]","medical_qa" 25 | "病人:治疗甲状腺疾病的老师门,问你们下,得了甲状腺功能亢进是什么病?好治疗不?\n医生:","甲状腺功能亢进就是我们所说的甲亢。这个病也不是一个很难,很严重的病。用药物治疗也能很有效的就控制了。按时按疗程服用药物治疗是可以很好的恢复健康的。,甲亢要根据患者病情和检查结果来选择治疗方法。想要得到病情缓解的话,患者还需要重视适当休息,饮食给予足够的营养和热量。","[]","medical_qa" 26 | "病人:女宝宝,目前7岁,刚开始,说自己咽东西疼,发现,咳嗽比较剧烈,并且,有点发烧也没精神,请问:幼儿扁桃体炎很难受如何合理饮食。\n医生:","孩子如果出现扁桃体发炎的情况,饮食上首先要保持清淡,可以以蔬菜和水果为主,因为很多水果都有清热解毒的作用,而且富含维生素,可帮助提高免疫力,抵御疾病,比如点梨,梨性凉,具有退烧、润喉、化痰、止痛的作用,可减轻急性扁桃体炎咽喉不适的症状,日常饮食还要注意易消化,好吞咽,所以建议以稀粥、面食为主,面食务必要煮的细软一些,在清淡饮食的同时还要少吃发物,例如家禽蛋、驴肉、牛羊肉等,饮食对扁桃体炎的治疗也是很关键的,务必注意。","[]","medical_qa" 27 | "病人:我老婆前几天仔细检查有点严重,他说他现在的月经都少了呢,妇科炎症会致使月经量少吗?\n医生:","妇科炎症是有可能会致使月经比较少的,如果月经突然间变少是不正常的,有可能是妇科炎症,也有可能是激素问题,也有可能是像重度贫血,卵巢肿瘤等全身性的炎症致使。建议及时到医院进一步仔细检查,子宫磁共振,激素水平等,根据化验结果及时对症治疗。调节身心健康,保持自身卫生.避免因抵抗力下降而导致细菌入侵。","[]","medical_qa" 28 | "病人:前几年的时候我就得了乳腺炎,也一直在用药物治疗,平时也总感觉乳房疼痛,最近这几天好像疼的厉害些,去医院检查,医生说我已经得了早期的乳腺癌,现在在医院接受治疗。想问下乳腺癌可以治好吗?\n医生:","一般情况下乳腺癌是能治好的,只要在癌细胞还没有出现扩散之前进行手术的摘除就能够让患者得到很好的治疗效果。但是很多人发现在进行手术之后很多的患者身体都非常的差,这样对于手术后的恢复非常的不利,所以最好可以根据情况来进行饮食方面的调整或者是药物的使用来提高患者的体质。 29 | 在进行治疗乳腺癌的时候最重要的一点就是要根据患者的身体情况来调整治疗的方案,所以在进行治疗的时候一定要提前的进行检查和确诊,很多的乳腺疾病的表现都和癌症类似,但是在进行细致的检查之后就会发现并不相同,所以在进行检查的时候一定要仔细一些。只有这样才能够准确的诊断乳腺癌,被给之后的治疗带了很多的方便之处。了解患者的身体情况和疾病的变化才能够让患者达到最好的抑制癌症发展的效果,并且在进行治疗的同时最好可以有效的根据患者的体质来进行药物的使用,如此就可以很好的配合之后的治疗,达到更好的疾病治疗的效果。 30 | 很多的患者和家属都在担心乳腺癌还能不能治好,事实上是可以的。在进行治疗的时候患者应该注意一点,单一的使用一个方法进行治疗的效果不会太好,只有使用综合的方法来进行治疗才可以有效的达到疾病的抑制效果。","[]","medical_qa" 31 | "病人:男性检查精液应该去看什么科?我和我老婆结婚三年了一直没有自己的孩子,我也没有抱怨什么,,但是老婆一直觉的这样会对不起我,我也经常安慰他,但是从心里来说,她也一直想要个属于自己的孩子,所以我想去检查一下,是不是我出现了问题\n医生:","您好,只要是男科医院,直接说做精子检查,就可以了、精液检查前应停止性交4~7天。检查前1周不能用丙酸睾丸酮、苯乙酸睾丸酮、苯丙酸诺龙。采取精液时,可用软皂或石蜡油做阴茎按摩,将标本收集在无菌的试管中;也可用避孕套(冲洗干净,不含杀精子药物)或采用性交中断法收集精液,但这样收集的量往往不多。如用上述方法采不到精液,可经直肠内按摩精囊及输精管末端、压迫采尿,检查沉渣中有无精子。不要将精液暴露在过热和过冷的环境中。及时交给医生备查,不得超过30分钟。冷天要注意保暖,送检时可放在内衣口袋里保温。","[]","medical_qa" 32 | "病人:最近食欲不好,而且身体有点浮肿了,浑身没力气,去医院检查说是肾病,请问肾结石隔多长时间打一针黄体酮\n医生:","肾结石如果疼的明显,可以用黄体酮,对于女性,这个药物对月经会有影响,还是顺其自然的好,如果您的月经周期是二十七天,黄体酮是18号打的,已经是排卵后了,估计对月经影响不大,不要用药为好,防止出现月经不调,肾病内科疾病病情很严重,建议患者及时对症治疗,希望患者可以根据医生的意见对症治疗。同时重视自身的护理工作,合理饮食,以免加重病情。上述的答案希望可以帮助到您,谢谢。","[]","medical_qa" 33 | "病人:无\n医生:","你好,宫颈切除手术建议住院治疗一周,术后对日常生活和工作没有影响,夫妻生活要待恢复两三个月后,才可以。","[]","medical_qa" 34 | "病人:只要每天躺着睡一想尿时便雄起只后便就遗精了而且是在我未醒时我除了早谢\n医生:","像这种情况的话,你也不必过度紧张和焦虑的,也有可能是由于性激素水平比较旺盛,有一定的关系,另外必要的话,可以到医院的泌尿外科和内分泌科,改进有关的仔细检查,剔除许多疾病的可能会对于遗精患者来说,及时救治是可以减低病发,如果不及时救治会影响到健康情况。因此患者要及时对症救治,并且日常生活中要以防过劳,留意自身卫生情况,祝你早日康复","[]","medical_qa" 35 | "病人:小孩子咳嗉 流鼻涕 嗓子疼两天前嗓子疼啊 曾经的救治情况和效果:血液化验未有异常药品有热炎宁核计阿莫西林颗粒小儿清热宁 头孢克洛在乎怎样的协助:症状如何象 流感H1N1除了吃要能一同吃吗\n医生:","诊断需要有进一步病原仔细检查方才能诊断。绝大多数发烧对症救治。指导意见:一般需要有看医生诊断病毒感染还是细菌感染引来的,如果是病毒性发烧,没什么特效药,可以服食利巴韦林颗粒或者小儿氨酚烷胺颗粒救治,另外就是照料好宝宝,减低症状,一般经过七至十天的调理,发烧就可以好了。如果是细菌引来的需要有医生指导下服食抗生素消炎药救治,","[]","medical_qa" 36 | "病人:我的妈妈很年轻的时候由于一次高烧就落下了癫痫病,这么多年来一直都控制得不错,一年到头也没有发作几次,正当我们大家都觉得欣慰的时候,过完年后的这几个月老妈居然频繁的发作了几次。\n医生:","你好,癫痫病复发的原因是很多的,要自己观察总结,比如是不是免疫力降低了,是不是遭受到情绪的打击了,是不是服用了不适当的药物了。","[]","medical_qa" 37 | "病人:我家宝宝属于早产孩子,一开始我就很担心孩子情况,最近孩子出现了这些一系列的情况,我也很担心,害怕孩子变得更严重,请问宝宝刚出生就是双眼皮吗\n医生:","这时候孩子在快速的生长,如果你看他一个月前的照片会发现他长相都不同了,孩子正处于快速生长发育的时期,这些变化都是正常的。,根据你说的症状主要是气机阻滞引起肠胀气的表现治疗应该顺气导滞,可以服用六磨汤,或四磨汤治疗,保持心情舒畅。","[]","medical_qa" 38 | "病人:现在瘘没有外口只是有硬结很痛,该怎么办?肛瘘封外口有两年了,又发作了,还没有外口该怎么办?瘘也会封口吗?谢谢!\n医生:","肛瘘的内口是初起感染生成肛瘘的入口,是发病的起源,因此,肛瘘都有其内口,同时,瘘管长期不能愈合,充分证明有病灶内口的存在。手术中的观察也证实了这点。 39 |   一般来说,绝大多数内口在肛窦内及其附近,集中在肛管后正中部两侧发病。内口可在直肠下部或肛管的任何部位,但多在内外括约肌连接处的平面上。有的有二处内口,一在肛管,一在直肠。临床中,若内口在直肠下部,表示瘘管复杂,手术操作较困难;若同一平面上有两个内口时,表示有两个瘘管,各有内口通入肛管。一般内口较小、圆形,在齿线附近可摸到变硬的凹陷;有的内口较大,形状不规则;内口较大的多为结核性肛瘘。 40 |   肛瘘的内口处理是治疗的关键所在。手术时如找不到内口,或内口处理失当,瘘管则不能完全治愈。即便有时伤口暂时愈合,因入口仍然存在,感染时仍易复发,形成肛瘘。因此,在手术之前,一定要仔细检查肛瘘的内口,完全切除或切开它,才能彻底治愈肛瘘。","[]","medical_qa" 41 | "病人:目前一般情况:无临床表现 42 | 病史:一直是小三阳十年了 43 | 以往的诊断和治疗经过及效果:只是检查过,因无临床症状所以没有治疗\n医生:","你的情况没有大问题的,肝功正常说明你很可能只是一个正常的携带者,是健康的带毒者。病毒量的多少对身体的伤害是不能成正比的,不管明天检查的结果怎么样,对你来说意义不大,只要肝功正常,b超没有太大的问题的话,大可不必过于担心。不过以后在生活上要注意不要喝酒,多休息。加强营养即可。","[]","medical_qa" 44 | "病人:前段时间身体各种不舒服,去医院检查得知是肿瘤疾病,非常担心能活多久,请问患有尖锐湿疣是否对胎儿有影响吗\n医生:","您好,建议治疗好后怀孕, 45 | 尖锐湿疣可以发生在孕前,也可发生在孕后各期。作者在临床上观察到妇女在妊娠期发生尖锐湿疣后,尖锐湿疣增长速度快,损害较广泛,治疗效果差。主要因素或病因可能是妇女在妊娠期间机体免疫功能下降,激素水平改变如孕酮水平升高等,随着子宫内胎儿增大压迫下肢大血管、淋巴管,使其血液、淋巴液回流减慢,导致下肢及外阴部充血水肿,加之阴道分泌物增多,外阴部湿润有利于尖锐湿疣进一步发生发展。 46 | 47 | 妇女妊娠期发生尖锐湿疣后其治疗较为困难,对要求生产的孕妇尖锐湿疣处理更是棘手。因为在治疗尖锐湿疣时要考虑孕妇及胎儿两方面,即在考虑治疗时要考虑所用药物或物理治疗等治疗的安全性,特别是要考虑所用疗法对胎儿和孕妇有无影响。由于一些疗法在孕妇中应用受到限制,如鬼臼毒素、5-Fu等化学药物局部应用后经皮肤黏膜组织吸收,可引起胎儿流产、早产、死产、畸形等,而手术切除、激光、电灼等方法可发生严重出血,并易致局部细菌感染,如蜂窝组织炎等,令临床医生和患者苦恼。但如果孕妇尖锐湿疣不治疗则损害会继续发展。病变巨大可发生溃疡出血,严重者可造成软产道的机械性阻塞。个别情况出现胎儿感染HPV后严重病例可引起呼吸道乳头状瘤致命并发症。因此,妊娠合并尖锐湿疣的治疗问题十分复杂。 48 | 49 | 对不愿意终止妊娠、并坚持要小孩者,要严密观察其病情发展,并注意以下治疗原则: 50 | 51 | 1保持外阴部清洁、干燥 52 | 患者要勤洗外阴部,保持外阴部清洁、卫生,保持局部干燥。 53 | 54 | 2注意休息,加强营养 55 | 患者要注意休息、避免疲劳,加强营养,提高机体免疫力,以提高抗病能力。 56 | 57 | 3改善下肢血液循环 58 | 患者要平卧,抬高下肢,以改善下肢血液循环,减轻外阴部水肿。 59 | 60 | 4选择对于孕妇和胎儿无影响的疗法 61 | 在治疗方面尽量选择对孕妇和胎儿均无影响的疗法。这些疗法要求:1.不容易经皮肤黏膜吸收引起全身性毒副作用的化学药物;2.避免全身性和局部损害内用易引起全身性反应的药物,以尽量减少孕妇的痛苦。对孕妇尖锐湿疣患者常选用的疗法有三氯醋酸局部治疗、冷冻疗法、激光疗法。尽管这些疗法较安全,但还是会给患者带来一定痛苦如激光疗法引起的疼痛等可能会导致流产。 62 | 63 | 在治疗过程中,若尖锐湿疣损害数目不多,可一次性彻底去除损害;若损害数目较多,应分批去除损害;若损害较多、较大、损害广泛、去除损害后很快复发、又是妊娠晚期即将分娩者,可采取保守的办法,即不进行治疗或是只去除个别较大损害,其余的损害不治疗,等在产后再作处理。但若出现下列情况者要进行治疗:1损害较大,出现压迫症状者;2阴道内或外阴尖锐湿疣损害容易出血者。 64 | 65 | 5预防流产或早产 66 | 对阴道或宫颈部有尖锐湿疣者,要尽可能避免反复多次使用扩阴器检查,以免引起流产或早产。 67 | 68 | 6避免经阴道分娩 69 | 妊娠晚期要行剖宫产,避免经阴道分娩,尤其是宫颈和阴道壁有尖锐湿疣者要注意,以免造成婴儿的尖锐湿疣感染。也有学者主张阴道分娩方式,认为剖宫产并不能阻止母婴尖锐湿疣传染。 70 | 71 | 7产后尖锐湿疣的处理 72 | 对孕妇产后尖锐湿疣的处理可先采取等待的办法,期望尖锐湿疣能自行消退。在临床上,孕妇尖锐湿疣在产后部分可自行消退。","[]","medical_qa" 73 | "病人:怀孕期间诊断为妊娠期糖尿病,现在刚刚生完孩子。\n医生:","您好,妊娠糖尿病指得是,妊娠前未发现糖尿病,妊娠后才确诊糖尿病。妊娠糖尿病在产后有可能会发展为糖尿病,也有可能恢复正常。是因人而异的。 74 | 指导意见: 75 | 您好,大多数妊娠期糖尿病患者在产后都会恢复正常的,建议您产后及时复查血糖,糖耐量等。","[]","medical_qa" 76 | "病人:出现了一块皮肤呈红色的状态,平时不痛不痒的还真的是没有发生具体是什么时候出现的皮损现象,昨天去医院的时候医生怀疑是红斑狼疮,后来给我做了血常规检查后说是可以诊断了。现在我的红斑狼疮到底怎么治疗好点呀?\n医生:","您好!红斑狼疮是一种原因不明、具有多系统、多器官损害的自身免疫性疾病;红斑狼疮最常累及皮肤、关节、肾脏、脑和血液等器官或系统。红斑狼疮病因尚不清楚,可能与遗传,感染,激素,环境,日晒,药物,妊娠等多种因素有关,一定 要到正规的医院诊疗,通过正规的检查、检验,确诊是否患有SLE,并在专科医生的指导和监控下进行治疗、用药。不可听信广告宣传,自行服药,或是凭着自我感觉,增减剂量或是停药.","[]","medical_qa" 77 | "病人:7岁半孩子精索囊肿需做手术吗?手术需要全麻吗? \n医生:","你好,这种情况一般需要进行手术治疗,如果孩子能自控的话,局部麻醉也可以 ,小孩子身体抵抗力比较差,所以很容易出现小儿泌外的,对于家长朋友们来说,不要心急,应该及时带孩子到专科医院接受检查和救治,而且注意给孩子进行常规检查,并且在医生的指导下对症治疗。","[]","medical_qa" 78 | "病人:无\n医生:"," 你好,这样的情况应该是由于病毒感染导致的严重的肺炎的 这样的情况是比较危险的,只能继续的进行住院抗病毒的治疗的,具体的恢复时间是不好判断的,要根据孩子的感染的程度还有身体的情况判断的 ","[]","medical_qa" 79 | "病人:我月经是正月初二来的,这次是二月十三开始有点见红,连续三天只有一点点,今天才见很多,并且下腹很涨,去医院查尿说是弱阳性,验血报告显示:绒毛膜促性腺激素62.94,参考值是:0-7,孕酮2.52,医生说很奇怪结果太低,不知道怎么回事,请问这情况是不是很危险啊?\n医生:","病情分析:你好,HCG和孕同太低了,会自然流产指导意见:建议流产后注意休息。加强营养,预防感染,一个月不能同房,注意避孕","[]","medical_qa" 80 | "病人:我今年53岁了,从4.20日我的左手有时颤抖一下,在虎骨穴上。 81 | \n医生:","你的这种情况可能是颈椎病压迫引起的,可以压迫颈脊髓、颈部神经、血管而产生一系列症状的临床综合征,建议先拍个片子检查一下颈椎,必要时做牵引治疗,神经内科患者在及时治疗之外,患者在生活中还需要注意保持合理饮食的好习惯,补充身体营养,希望上述的答案可以帮助到你,谢谢!","[]","medical_qa" 82 | "病人:无\n医生:","你好,考虑为内分泌失调引起的,会导致色素沉着及长斑的情况,也可能会导致月经紊乱 ,可以采用中草药进行调理,注意保暖充足睡眠对恢复周期有利。","[]","medical_qa" 83 | "病人:母亲有乙肝病毒装载,母乳喂养到一岁,是尽早断奶,还是正常吃到一岁多\n医生:","根据你的叙述,只要孩子体内有乙肝抗体,是干扰母乳的。建议你可以带孩子到医院检查一下乙肝五项,如果产生保护性抗体,就不需要忧心被感染。除此之外,患者在救治乙肝期间,除了要马上救治外,患者的饮食状况和心理状态也是尤为重要,患者一定要始终保持心情愉快,恰当饮食,以免对乙肝的彻底恢复引发了不必要的干扰。","[]","medical_qa" 84 | "病人:其实我也不知道是怎么的,最近就是懒得动,吃饭也很多,一会就想吃东西,然后吃的时候又不想,把我急死了,害怕得严重的疾病,就想咨询一下,请问空腹血糖6.1需要注意哪些\n医生:","你好,正常人的空腹血糖值为3.89~6.1mmol;空腹血糖6.1属于临界值但问题不大,需要在平常注意饮食清淡规律,禁甜食多加锻炼身体,少熬夜.,内分泌科疾病要根据患者病情和检测结果来选择治疗方法。想要得到病情改善的话,患者还需要重视自身护理,合理饮食。","[]","medical_qa" 85 | "病人:最近几天感觉肝部有疼痛感,笑或有所时有痛的感觉。\n医生:","需要静脉滴注或者是口服肌苷片、甘利欣、病毒唑和抗病毒、干扰素等药物治疗,平时禁止使用对肝功能有损的药物和食物。平时禁吃辛辣酒等刺激性食物。平时需要加强运动、增强体质。","[]","medical_qa" 86 | "病人:我的一个老战友,前几天我去他家的时候,他跟我莫名其妙的说他怀疑自己得了肾上腺肿瘤。\n医生:","你好,你说的情况可以手术治疗,也可以采用传统中药保守治疗,或者手术后采用有效的传统中药巩固治疗。祖国医学用传统中药有非常独到的治疗方法,建议你用传统中药虫草、猪苓、明党参、桑寄生、青阳参、香菇、红豆蔻、桑白皮、杜仲、降香、茯苓、白术、八月札、知母、片姜黄、制南星、山萸肉、木瓜、仙茅、制半夏、补骨脂、独活、石菖蒲、仙鹤草、大蓟、山奈、枸杞子、薏苡仁、地榆、白前、丹皮、射干、当归、土鳖虫、青黛、肉桂、苦参、金精粉、葫芦巴、白癣皮、赤芍、山豆根、远志、泽泻、金银花、乌术粉、制鳖甲、连翘、紫草、桃仁、三七治疗,见效快,疗效确切。其功效能在短期内缩小肿块,控制转移、减轻痛苦、稳定病情、疗效显著,同时增强机体免疫力,甚至达到临床彻底治好的目的。希望你正确治疗,早日康复!","[]","medical_qa" 87 | "病人: 88 | 6个月大的宝宝不能抬头,会翻身,食欲也正常,基本没什么异常,但是有时候回发抖,请问小儿癫痫发作时怎么办?\n医生:","您好,孩子在天天复发的时候,一定要确保身边有人照看,防止使孩子处在危险的环境当中。平时一定要确保室内安全,在桌角家具旁边都应当安个防撞条,并且地面上也应当铺一些泡沫。复发的时候应当在口腔内,塞一些衣物,防止如果发生舌咬伤。平时也要用药物控制疾病复发。","[]","medical_qa" 89 | "病人:无\n医生:","早泄引起的原因一般和肾虚,性功能低下,前列腺炎等原因引起的症状,要及时的结合患者的自己的症状及时的确诊在针对性的治疗的。肾虚引起的症状要口服金贵肾气丸,男宝等 药物治疗。同时要均衡营养多吃新鲜蔬菜水果,如果是其他的疾病导致的原因要根据病因治疗。","[]","medical_qa" 90 | "病人:无\n医生:","你好,一般在孕6周可见孕囊,6-7周可见胚芽的,孕8周可明显胎心,现在的情况可能是由于胎停育的可能,可以一周后复查,仍没有看到胚芽则考虑胎停,可以做清宫处理。","[]","medical_qa" 91 | "病人:2010年2月20日\n医生:","朋友你好.先天性的心脏病是有很多种类的,不同种类的治疗方法不完全一样.首先,要通过彩超,心脏造影等检查确定是什么类型的病变,然后才能考虑治疗.指导意见:目前对于小儿的先天性心脏病的治疗有了很大的进展,许多先心类疾病都可以通过手术解决.建议到正规的儿童医院或者三甲医院的儿童心脏外科就诊,确定疾病类型后,只要可以手术,并且手术成功,预后都是不错的.希望对你有所帮助,谢谢.","[]","medical_qa" 92 | "病人:无\n医生:","是可以的啊,如果没有疼痛的症状就是不用担心的.同时要均衡营养多吃新鲜蔬菜水果多喝水忌辛辣食物,补充多种维生素增强抵抗力。","[]","medical_qa" 93 | "病人:无\n医生:","先不要担心,低烧是指体温在37.3℃~38℃,长期低烧是指持续发烧两周以上,不包括间断发烧。宝宝长期低烧也可以是生理性的,即并非有病的表现。这种低烧多为37.2~37.5℃(腋下体温),孩子精神食欲好,无病症表现,通过各方面的检查也没有发现不正常","[]","medical_qa" 94 | "病人:本人男30岁交第一个女朋友时就发现自己好像存在阳痿的情况,期间5年时间试了很多方法也不能恢复正常,我都打算放弃了,但是父母一直催我结婚生子,我觉得很对不起父母,还是想再治疗一下,请问:手淫过多引起阳痿会如何治疗\n医生:","根据你的情况有频繁的性交,目前再次出现阳痿早泄考虑性交致使的肾经巨亏引来的,戒掉或者增加性交次数是前提,服食补肾益气药物治疗。平时用枸杞泡茶,食补韭菜、牛肉、羊肉,注意做提肛活动有助于恢复。然后,患者需要做到饮食有节,规律作息,调节身心健康,在生活中注意要保持良好的心情,要多吃清淡稀软的食物,多喝水也要多吃一些蔬菜与水果。","[]","medical_qa" 95 | "病人:无\n医生:","建议及时去医院检查血常规。明确是那种类型的贫血后治疗.在药物治疗的同时还要注意饮食.根据不同类型的贫血,补充相应的造血原料","[]","medical_qa" 96 | "病人:请问大夫小儿不愿吃饭与锌,钙,铅有哪些关系?期待你的回答。谢谢!\n医生:","小孩厌食与教养有关 97 | 目前小孩厌食除了疾病因素或病因外,更常见的是不良饮食习惯造成的,它与教养不当有密切关系.食欲与神经精神状态密切相关.不少独生子女家长担心孩子营养不够,采用哄、骗、骂,甚至打等方式强迫小儿进食,引起小儿产生反抗情绪和厌食的心理.还有吃饭不定时定量,吃0食过度,都会扰乱消化吸收的规律.有一些孩子很偏食,不爱吃肉、鱼、蛋等荤菜,以素食为主,这会引起人体一些必要的营养物质缺乏,如保持正常味觉的锌元素,它在一般植物类食物中含量很少,且不易被人体吸收.体内锌减低,就会吃食乏味,食欲不振.2是太多的蛋白质饮食也会使孩子食欲减退.因为一下子摄入太多高蛋白物质,使小儿娇嫩的胃肠承受不了.3是果糖、巧克力等甜食吃多了,对食欲也有影响,尤其在吃饭前吃甜食,容易引起血糖升高,中枢神经抑制,人就不想吃东西了.4是小孩不爱吃蔬菜食品,极易导致小孩维生素及微量元素缺乏,导致生长发育不好. 98 | 为让孩子食欲正常,健康成长,建议家长们注意以下几个方面:让孩子养成良好的饮食习惯,吃饭定时定量,不吃0食,不偏食,合理安排膳食,多安排蔬菜食品,注意营养平衡,营造舒适的就餐环境,让孩子适当参加些体育活动,增加热量消耗,以促进食欲. 99 | 小孩厌食的几种因素或病因 100 | 1、0食过多.有些家长经常买糖果、甜点心、巧克力、花生、水果等,给孩子随便拿着吃,孩子小嘴整日闲不住,到吃饭的时候当然就吃不下去了.长此下去,不会引起小孩消化吸收功能紊乱,发展为小儿疳疾病.2、食不定时.有的父母见孩子哭就喂奶或喂饭,进食没有一定的规律;也有的父母在婴幼儿吃奶、喂饭时逗孩子玩,致使孩子不能集中精神吃奶、吃饭;大一点的孩子边吃饭边看电视或看小人书,随便吃几口就急于到邻居家或外面玩,时间久了就会影响消化液的正常分泌,造成食欲不振.3、饮食无度.有些年轻父母生怕自己的孩子吃不饱、长不胖,于是不惜一切代价,给孩子吃大量的高蛋白、高糖饮食滋补品,顿顿鱼、肉,喝各种含糖饮料,伤及孩子娇嫩的胃肠,使胃肠不能正常消化、吸收,久而久之,食欲必然下降,引起厌食.4、精神因素的影响.有的父母在吃饭的时候,当着孩子的面经常争吵;有的在吃饭时,批评孩子的过错,对孩子的精神刺激很大;也有的父母对孩子要求不一致,一个严,一个偏爱,在这种情况下,孩子也会发生厌食. 101 | 家长宠出来的小儿神经性厌食 102 | 儿童厌食可由躯体疾病和精神因素引起.由精神因素引起的厌食称神经性厌食,在幼儿中颇为多见,小儿进食习惯不好,不仅影响营养的摄取,而且易患不少疾病,小儿神经性厌食就是其中之一.不良的饮食习惯会逐渐降低小儿食物中枢的兴奋性,引起小儿神经性厌食. 103 | 一、造成小儿神经性厌食常见的因素或病因有:1、常让孩子独自一人先吃,不与家人一起进食,没有饮食气氛.2、孩子进食时,父母或其他人过分紧张地注视,造成小儿精神紧张.3、用种种许诺诱惑小儿进食或者用玩具逗哄小儿进食,降低进食兴趣.4、孩子进食时注意力分散,边吃边看电视或画册,抑制消化液的分泌,影响消化功能.5、孩子拒食时,家长强迫其进食,造成孩子没有正常饥饿感,不能引起食欲.6、过量给孩子吃自认为高营养的食物,不注意变换食品花样,忽视了食物的多样性,造成饮食结构不合理,营养素不均衡.7、让孩子乱吃0食,特别是在饭前让孩子吃冰激淋、巧克力等0食,因为高蛋白、高糖的浓缩食品可使食欲下降.8、有的父母生怕孩子撒了饭菜弄脏了衣服和居室,不让孩子自己进食,使孩子缺乏吃饭的兴趣.9、父母在喂孩子吃饭时,催着孩子快吃、多吃,孩子稍有怠慢就发脾气,或用威胁的口吻及方式强迫喂养,使孩子十分反感.10、进食时父母唠叨不休,数落孩子的错误,造成气氛紧张和不愉快,抑制孩子的食欲.11、有些家长对孩子的自由过于限制,强迫孩子学画图、弹钢琴、背唐诗等,学得不好还要大声斥责,从而造成孩子情绪低落而食之无味. 104 | 2、神经性厌食的心理治疗主要是消除上述各种不良因素,帮助儿童建立进食时的愉快情绪,促进胃肠道腺体的分泌功能和消化功能,增加食欲.具体方法如下: 105 | 1、通过解释疏导孩子不良的心理因素,改变不良的饮食习惯.孩子在自行进食时,父母不要训斥孩子或包办代替,更不要采用强制手段让小儿进食,不让小孩子边吃边玩边看画册,也不应给小孩子多吃0食.2、培养孩子进食兴趣,尽量提供孩子爱吃的色、香、味俱全的食物.对年幼儿童,可在大人协助下尽量让孩子自己进食,增加进食兴趣,促进食欲.还可安排孩子与年龄相仿的小朋友共同进食,并在进餐时给予适当的鼓励和表扬.3、进食前半小时不让孩子做剧烈活动或听紧张的故事,让孩子集中精神进食.4、当孩子不愿进食时,家长不必强迫进食,等孩子饥饿而有食欲时再进食.5、对孩子进行鼓励和奖赏.家长可记录孩子每天的食物摄入量,这样能清楚地反映孩子进食情况,当孩子饭量增加,则给予奖赏:如带孩子郊游、看电视、讲故事等. 106 | 儿童厌食的纠正方法 107 | 不少家长为孩子不好好吃饭而着急,而孩子也为大人逼着他吃饭而厌烦.这样一来,吃饭问题成了年轻的父母伤透脑筋的一大问题.什么因素或病因使这些孩子不愿吃饭呢?其实,真正由于局部或全身疾病而影响消化功能、使食欲下降造成厌食的幼儿实属少数,而大多数幼儿是由于喂养不当和不良的饮食习惯引起的.那怎么办呢?就是要把已经颠倒了的饮食习惯重新纠正过来,养成孩子良好的饮食习惯,具体说有下列几条: 108 | 一是不要把0食当“主食”:已经这样做的,要纠正过来. 109 | 2是花样翻新,诱导食欲:给儿童吃的食物,要注意新鲜和品种多样化,不仅仅蛋类、肉类,还应有各种蔬菜瓜果,实践证明,饭菜多样化、艺术化、色香味俱全、是刺激儿童食欲的好方法. 110 | 3是要顺其自然:对已经有厌食习惯的孩子,遇到他不肯吃饭时,不要大惊小怪,而要不动声色地把食物拿开,孩子少吃一点或不吃一餐,是没有哪些问题的,这时仍要注意不随便给0食吃,孩子饿了,下餐饭自然会吃得好了,切不可再搞强迫或哄骗了. 111 | 4是饭前要保持愉快的情绪:愉快的情绪有助消化液的分泌,从而增进食欲.可在饭前给孩子看些有趣的画报,听些音乐,讲些笑话或者邀请其他孩子一同进餐,千万不要边吃饭,边训斥孩子,这会影响孩子的食欲. 112 | 5是培养良好的饮食习惯:不要随便给孩子吃0食,数量和次数应予以限制.尤其饭前两小时内,一定不能给0食吃.吃饭同时要定时,孩子每餐吃的量要大致固定下来,避免养成有时多吃、有时少吃或不吃的不良习惯. 113 | 目前的国人把补钙补锌补充鱼肝油当成了高级营养品了.好象不管是小孩出现的任何情况,只要一补钙补锌补充鱼肝油后,就可以包治百病了.这真是怪事啊.提醒家长们,是药3分毒啊.钙剂是用于治疗钙缺乏症的药品,不是用来养人的补品.还是要均衡的膳食营养才是补身体的好办法啊.这不是缺钙和缺锌的问题,而是是否缺乏均衡的营养素的问题.不要只想着给孩子服药,要多想想怎么给孩子平衡膳食,均衡营养. 114 | 补锌补钙不如调脾胃 115 | 在儿科门诊,经常见到一些孩子营养素缺乏,缺锌缺钙,消化功能紊乱,属于“饮食积滞,脾胃受损”.父母多数很紧张,要求医生一定多开点好药补补.专家说,补锌补钙,不如调理好孩子的脾胃.“脾胃为后天之本”,出现这些症状的根本因素或病因,在于孩子的脾胃功能受损.由于铁锌类制剂可剌激胃肠道,所以若还是严重缺乏,不必刻意去补,否则会加重消化不良.加之铁锌钙等微量元素,如果不同时补充的话,互相之间是会产生排斥的,补充单一的微量元素,会引起其他元素的吸收不足,从而导致另一元素的缺乏.如补钙多了,会引起铁和锌的缺乏,补铁多了,又会引起钙与锌的吸收不足. 116 | 因此,专家建议,最好带孩子到医院检查一下,是否真有微量元素缺乏,并在医生的指导下辩证用药.如属于脾虚伴有积滞,就不能单纯消积,而要用些健脾的或调理脾胃功能的中药,效果会更好.同时,父母要配合科学的喂养方法,做到膳食营养平衡,饮食有节,荤素合理搭配,且多吃蔬菜,使孩子从日常饭菜中吸收自身需要的营养素,身体自然会一天天强壮起来的. 117 | 人体必需的7大营养素与平衡膳食 118 | 人体必需的营养素有7种,即水、蛋白质、脂肪、碳水化合物、微量元素、维生素、膳食纤维.营养学家提出的“营养全面,比例合理,均衡膳食”及“一把蔬菜一把豆,一个鸡蛋加点肉,5谷杂粮要吃够”,很好地体现了膳食平衡的思想.只要我们认真做到了膳食平衡,保持身体健康是很容易的.一个能做到平衡膳食的人,是不需要额外补充某种单一营养素的.否则,反而会打乱体内各种营养素的平衡状态. 119 | 一、水:水是维持生命不可缺少的物质,占人体体重的2/3以上,水的生理作用:①水是人体体液的主要成分;②水是各种营养成分的溶剂;③水是物质运输的载体,对食物的吸收排泄有携带作用;④水可以调节体温;⑤水是体内的润滑剂;⑥水是廉价的又颇具治疗效果的奇药.水的正常需要摄入量成人为每天1.5~2升.小孩为每日每公斤体重25~35毫升.多饮水有利于体内毒素的排泄,减少患肝胆及泌尿系结石的患病率. 120 | 2、蛋白质:蛋白质是一切生命活动的物质基础,没有蛋白质就没有生命,可见蛋白质对人体是非常重要的,正常成人体内16~19%是蛋白质.生理功能:①构成人体组织与修复组织,人体任何组织器官,都以蛋白质为重要组成成分;②是构成体内各种酶、激素和抗体的重要物质;③供给机体能量;④维持体内正常的渗透压;⑤维持正常的酸碱平衡;⑥运输氧气和营养物质.参考摄入量:成人每天摄入按千克体重0.8克较好,以植物蛋白食物为主的,应按每千克体重1.0~1.2克为宜.儿童蛋白质每日摄入量为:按公斤体重乘以需要量系数,1~3岁为1.80;4~6岁为1.49;7~10岁为1.21(换算的蛋白质用量单位为克).瘦肉、鸡鸭肉、蛋类、鱼、牛奶、花生、豆类等食物中含有较高的蛋白质.且最好是动物蛋白与植物蛋白联合使用,以利于蛋白的互补作用.由于蛋白质在体内无法储存,因此只有每天摄入一定量的蛋白质,才能维持身体的需要. 121 | 3、脂肪:脂肪主要用来变成生长发育和维持健康的“能量”,正常人体含脂肪为14~19%.脂肪的生理功能:①储存能量,是人体含热量最高的能源物质;②维持体温;③是脏器的支持和保护者;④节约蛋白质作用;⑤机体重要构成成分;⑥增加饱腹感;⑦改善食物感观性状;⑧促进脂溶性维生素吸收.参考摄入量:儿童生长发育快,一般每天每千克体重需要2—4克脂肪.婴儿期占食物总摄入量的35~40%;幼儿期为30~35%;青少年期为25~30%;成人及老年人为20~30%.在乳类、蛋黄和肉类中含有大量脂肪.脂肪摄入不足会导致体质瘦弱,发育不好.过量则易至肥胖症发生. 122 | 4、碳水化合物(糖类):人体80%的热量来自碳水化合物,碳水化合物的生理功能:①储存和提供能量:②构成机体组织成分:③节约蛋白质、能保证蛋白质不被过多分解;④帮助脂肪氧化;⑤帮助肝脏解毒;⑥改善食物感观性状;⑦提供食物纤维.参考摄入量:中国营养学会推荐我国居民碳水化合物类饮食供给量占总能量的55~60%较为合理.儿童每天每千克体重需要10—20克碳水化合物.食物来源于谷类、豆类、薯类和食糖中.上面提到的“5谷杂粮”即是指碳水化合物. 123 | 5、微量元素:目前已发现有20种左右的元素是构成人体组织、维持生理功能、生化代谢所必需的,其中大于体重0.01%者,称常量元素,如钙、磷、钠、钾、氯、镁与硫等7种.机体中含量小于0.001%者称为微量元素,人体必需微量元素有铁、碘、锌、硒、铜、钴、氟、锰、铬、钼共10种:硅、镍、硼、钒为可能的必需元素.只要按照膳食营养素参考标准,给予了均衡的膳食,微量元素摄入量基本能满足生命活动和生长发育的需要.一个能做到平衡膳食的人,是不需要额外补充某种单一营养素的.否则,反而会打乱体内各种营养素的平衡状态,从而导致疾病的发生. 124 | 6、维生素:维生素是一些有机化合物,是人体组织正常发育以及健康生长所必需的营养物质.它们与碳水化合物、脂肪、蛋白质和水分等营养素不同的是,当人体内缺乏维生素或由于摄取、利用不当时,会导致人体各种缺乏症或综合征,严重影响身体健康.儿童缺乏维生素可致生长发育迟缓或导致佝偻病的发生.维生素摄入应以蔬菜水果为主,在蔬菜、水果、鱼肝油、牛奶、动物内脏等食品中含有丰富的维生素. 125 | 7、膳食纤维:膳食纤维的生理功能:①有利于食物的正常消化,富含纤维素的食物咀嚼时间长,可使食物与消化液充分接触,有利于食物的消化.②增强肠蠕动功能,有利于排便.大多数纤维素能促进肠蠕动,使肠肌肉保持健康和张力,还使粪便含水较多而体积增加和变软,有利于粪便排出,减少了对毒素的吸收.③控制体重和减肥,食物纤维,特别是可溶性纤维,可减缓食物由胃进入肠内的速度和吸水作用,从而产生饱腹感而减少能量的摄入,达到控制体重和减肥作用.④降低血糖作用,大多数可溶性食物纤维,能减少小肠对糖的吸收,减少体内胰岛素释放.⑤对结肠癌的影响:摄入抗性淀粉会增加粪便量,通便可及时稀释潜在致癌物,防止结肠癌的发生.⑥对脂质代谢的影响,各种食物纤维均有降胆固醇与3酰甘油的效果,尤其是可降低低密度脂蛋白胆固醇,因其可吸附胆汁酸、脂肪等成分,使其吸收率下降,摄入者其粪便中胆汁酸含量明显增加,因此有降血脂的作用.⑦不良反应:过多摄入食物纤维会致腹部不适,如增加肠蠕动和增加产气量,影响人体对蛋白质、维生素和微量元素的吸收. 126 | 8、蔬菜与水果的营养价值:①含糖类:蔬菜水果所含糖类包括简单糖、淀粉、纤维素和果胶等物质.②新鲜蔬菜水果是供给维生素的主要来源,只要每日摄入足量的蔬菜水果,就不会缺乏维生素.③蔬菜水果中含有丰富的矿物质,如钙、磷、铁、锌、钾、钠、镁、铜等,是饮食物矿物质的主要来源,对维持体内酸碱平衡起着重要作用.绿叶蔬菜通常每100克含钙在100mg以上;肝、肾、蛋黄、瘦肉、血、菠菜、油菜苔、红糖、黑木耳等食物中含有丰富的铁;肉类、蛋、乳、肝、卵、脑花、谷类、豆类、花生、黑米、豆腐、核桃、苹果、扁豆、白菜、卷心菜、莴笋、金针菇、海带、杏、菠萝、山楂等食物中含有丰富的锌.④含有对人体有宜的芳香物质、有机酸和色素.⑤蔬菜水果中还含有某些酶类、杀菌物质和具有特殊功能的生理活性成分. 127 | 维生素A、D中毒 128 | 警示语:不要小孩有事无事的,就只想着要补钙、补鱼肝油等,这些制剂是药品,不是食品.更不是包治百病的药,服用多了会有害处的.读一读下面的资料,你也许会明白一些道理的. 129 | 维生素A中毒 130 | 摄入大剂量维生素A,可致急性、慢性及致畸性毒性,急性毒性产生于1次或多次连续摄入成人参考摄入量(RNI)100倍,或儿童大于其(RNI)120倍时,其早期症状为恶心、呕吐、头痛、眩晕、视觉模糊、肌肉失调、婴儿囟门突起.当剂量很大时,可有嗜睡、厌食、少动、反复呕吐.据报道有位体重2.25kg,1个月龄的男婴,在11天内接受了14000μg维生素A后中毒死亡.慢性中毒比急性中毒常见,维生素A使用剂量为其(RNI)10倍以上时可发生,常见症状是头痛、脱发、肝大、长骨末端外局部疼痛、肌肉僵硬、皮肤瘙痒等.动物实验证明,维生素A摄入过量可导致胚胎吸收、流产、出生缺陷.孕妇在妊娠早期每天大剂量摄入,娩出畸形儿相对危险度为25.6.摄入普通食物通常不会导致维生素A过多,绝大多数过多摄入维生素A浓缩剂所致,也有食用狗肝、熊肝或红色肝致维生素A中毒的报道. 131 | 大量摄入类胡萝卜素可出现高胡萝卜素血症,易出现类似黄疸的皮肤,但停止使用类胡萝卜素后,症状会逐渐消失,未发现其他毒性. 132 | 维生素A最好的食物来源:各种动物肝、鱼肝油、鱼卵、全奶、奶油、禽蛋等;维生素A原良好来源是深色蔬菜和水果,如冬汗菜、菠菜、苜蓿、空心菜、莴笋叶、芹菜叶、胡萝卜、豌豆苗、红心红薯、辣椒、芒果、杏子及柿子等. 133 | 维生素D中毒 134 | 由于维生素D可以在体内蓄积,如果摄入过多,就会引起中毒,出现高血钙和高尿钙.但有报道幼童每天摄入维生素D3仅45μg(1800U),即出现维生素D过多症症状.某些病例维生素D中毒量仅为(RNI)5倍,表现为食欲缺乏、体重减轻、恶心、呕吐、头痛、多尿、烦渴、发热,腹泻、便秘交替出现;血清钙磷增高,以至发展成动脉、心肌、肺、肾、气管等软组织转移性钙化和肾结石,严重者将因肾、心脏和大动脉钙化而死亡.1996年某地193名婴儿给予维生素D3针剂,每周1次,每次1支(7500μg或15000μg),其中187名确诊为维生素D3中毒,出现腕关节X线改变、肾钙质沉着及颅脑CT改变等异常.维生素D中毒后,首先应停服,限制钙摄入,重症者可静脉注射乙2胺4乙酸(EDTA),促使钙排出. 135 | 维生素D最好的来源:经常晒太阳是人体廉价获得充足有效的维生素D3的最好来源,一个人只要每天晒太阳接受紫外线照射20分钟,就会自己生成维生素D1天的需要量.在阳光不足或空气污染严重地区,可用紫外线灯做预防性照射.只要经常接触阳光,在日常饮食条件下,不会发生维生素D缺乏病. 136 | 食物来源:维生素D主要存在于海水鱼,如沙丁鱼、鲨鱼,动物肝、蛋黄等动物性食品及鱼肝油制剂中.我国不少地区使用维生素A、维生素D强化牛奶,使维生素D缺乏症得到有效控制. 137 | 微量元素钙:当人体缺钙时,会引起骨骼、牙齿发育不正常,骨质疏松软化,肌肉痉挛、凝血障碍、流血不止等症状.钙是无毒元素,但补钙过量,超过了血液的溶解能力,便会在人体其他组织中沉积溶解.如沉积在关节,会引起关节疼痛;沉积在肌肉里,会形成坚硬的结节;沉积在心脏里,则会引起传导障碍,导致心律紊乱.少年儿童可导致骨垢过早钙化长骨生长停滞而影响身高的发育. 138 | 钙的食物来源就考虑两个方面,钙含量和吸收利用率.奶与奶制品含钙丰富,吸收率也高,是婴幼儿理想的钙来源;水产品中小虾皮含钙特别多,其次是海带;豆类及其制品及油料种子和蔬菜含钙也不少,特别是黄豆及其制品,黑豆、赤小豆、各种瓜子、芝麻酱、海带、发菜等钙含量均丰富. 139 | 微量元素铁:铁缺乏常见于营养不良引起的缺铁性贫血,婴幼儿、孕妇及乳母容易发生. 140 | 铁过量:口服铁剂和输血可致铁摄入过多.急性铁中毒的局部影响为胃肠出血性坏死,全身性影响包括凝血不良、代谢性酸中毒和休克.机体铁储存过多可致慢性铁中毒,如损伤多器官的血色素沉着症,常表现为器官纤维化,组织中含有极高浓度的铁,大部分为血铁黄素. 141 | 铁的食物来源:铁丰富来源为动物血、肝、大豆等;良好来源为瘦肉、鱼类、红糖、蛋黄、干果等,牛奶为贫铁食物.蔬菜中含铁量不高,油菜、苋菜、菠菜、韭菜等含铁,但利用率不高. 142 | 微量元素锌:锌缺乏表现为生长迟缓、认知行为改变等症状.生长期儿童锌缺乏最大,常有食欲缺乏、味觉迟钝甚至丧失、皮肤创作不易愈合、易感染、第2性征发育障碍、性功能减退、精子产生过少等症状. 143 | 锌过量:成人1次摄入2g以上的锌可导致锌中毒,表现为上腹疼痛、腹泻、恶心、呕吐.长期补充大量锌可导致贫血、免疫功能下降、高密度脂蛋白胆固醇降低等.锌过量常致铜继发性缺乏,损害免疫器官及免疫功能和降低巨噬细胞活力,抑制趋化作用和吞噬作用及细胞杀伤能力. 144 | 锌来源广泛,但动植性食物锌含量与吸收率有很大差异.海产品、红色肉类、动物内脏是锌极好来源,干果类、谷类胚芽和麦麸也富含锌.植物性食物含锌较低,食物中大部分锌与蛋白质和核酸结合.按每100g含锌量(mg)计算,以牡蛎最高达100以上,畜禽肉及肝、蛋类为2~5,鱼及其他海产品为1.5左右,畜禽制品为0.3~0.5,豆类及谷类为1.5~2.0,而蔬菜及水果类含量较低为1.0以下. 145 | 另外还应注意,补充单一的微量元素,还会引起其他元素的吸收不足,从而导致另一元素的缺乏.如补钙多了,会引起铁和锌的缺乏,补铁多了,又会引起钙与锌的吸收不足.","[]","medical_qa" 146 | "病人:无\n医生:","腮腺是人体最大的一对分泌唾液的腺体,做手术后饮食要特别注意不要吃刺激性的食物。特别是酸性的东西,这些东西很容易刺激腮腺分泌口水,引起腮腺瘘。","[]","medical_qa" 147 | "病人:重度宫颈糜烂\n医生:","你好,宫颈糜烂分为轻中重三度,也可以分为一二三度,是想对应的,一般情况下有性生活的人或多或少都会有点宫颈炎症,不同程度的宫颈糜烂治疗方法是不同的,需要根据医院检查结果对症治疗。","[]","medical_qa" 148 | "病人:姐姐刚刚发现癫痫病没有多久,现在已经发做有两次了,当她发做的时候,我们都不知道怎么办,都没有什么应急措施,就是她手脚按住,嘴里塞一些东西时去,怕她咬到舌头,尽量减少她的伤害,也不知道我们这样的做法对不对,到底需要怎么做好呢。\n医生:","你好啊,一旦家属发现病人出现癫痫持续状态时,不可以在患者口中塞入东西:有些人为防止患者咬伤舌头而强行往患者口中塞入木筷、勺子等。这样有可能导致患者牙齿断裂、松动。同时应尽快送医院抢救。如在医院,可静脉注射安定,尽快终止癫痫状态。癫痫持续状态患者常伴有缺氧、脑水肿、感染、高热等症状,应注意给氧,防止脱水,控制感染,并注意保持呼吸道通畅,避免吸人异物,防止骨折。","[]","medical_qa" 149 | "病人:不孕症FHS下降怎么办到现在到没有孩子,我自己也很着急,不知道是不是自己的问题,让我老公去检查他不去,很害怕自己的病变得严重,请问怎么回事\n医生:","你是需要有调养好月经,查好排卵日同房怀孕的机率比较.当饮食,留意歇.消化叶酸和交联维他命,钙不足的,多喝牛奶,铁和锌也一样重要,不推荐药补,有胃口就尽量食.始终保持心情愉.可多吃水果,多吃蔬.消化适当动物植物蛋.少吃辛辣食品,清淡一些,如豆芽,祝你早.孕症是一种容易病发的妇科疾病,在用药期间,女性需要有看重自身的护理,尤其是护理方面,建议患者多留意留意阴部卫生,饮食清淡为基础,最后祝女性患者可以尽快康复!","[]","medical_qa" 150 | "病人:我老婆怀孕1个多月了,现在准备出行,能否坐飞机啊\n医生:","你好,可以做,坚持运动。运动并不仅限于健身房,室外随时随地的有氧运动更有助于你孕力的保持和提高。快走、慢跑、游泳、瑜伽是最,提高身体柔韧度,增强身体平衡感,且对身体内部器官有按摩的过程。坚持运动,会让你看起来更年轻有活力,更重要的是增强免疫力。","[]","medical_qa" 151 | "病人:大夫,我有个亲戚,一直以来全家人都特别忧心他吧,因为他一直脑供血不足血压还低?家里搞不清楚便这究竟是怎么回事,想问问我怎么回事,但是我也不清楚,所以进行咨询你。\n医生:","您所说的这种情况应当考虑是由低血压导致的脑供血不足,与家族隔代遗传,个人体质,营养不良,不良生活习惯等多种不同因素关于。服用益气养血,养阴生津等药物医治,同时增强调养,增强营养,确保充足深度睡眠,饮食规律,就可以稳定低血压的症状,只要低血压医治好了,脑供血不足的症状自然就会消失。","[]","medical_qa" 152 | "病人:有过多年晕倒情况,去年12月7日晕倒时间较长(据说半个小时),到现在都还是头晕,走路打飘,在温州B超说左侧颈动脉完全堵塞,右侧颈动脉堵塞严重,建议手术。\n医生:","左侧颈动脉闭塞可能是造成你晕倒的原因,是否完全闭塞,需要做颈动脉造影检查,如果确实已经完全闭塞,则手术开通的风险很大,应该将右侧严重狭窄的颈动脉做支架扩张成型,改善大脑供血,预防再次发生脑梗。如果左侧颈动脉闭塞,做右侧颈动脉斑块切除手术,会使你术中脑部耐受缺血的能力降低,属于颈动脉斑块切除手术的高危因素。一般首选支架治疗。","[]","medical_qa" 153 | "病人:一年内不定时经常咳,吃了许多抗生素都不管用,药物我觉着对孩子已经不起作用了 曾经的治疗情况和效果:无在乎怎样的帮助:收藏什么样的保健品可稳定这样的情况\n医生:","孩子咳去查一查呼吸系统有问题没。可以服食转移因子口服液,服食的时间为六合个小周期,可以稳定体质,增加免疫力,平时多吃鲜水果青菜,做个微量原素检验,看一看可有缺锌。锌的缺少也会引来免疫力差。比加灵魂阳光牛初乳,它除了所含丰富的优质蛋白质、维生素和矿物质等营养成份外,更含有活性免疫球蛋白,能抑止病菌驯化,守护其免遭病原肆虐,降低身体的免疫力和抵抗力。","[]","medical_qa" 154 | "病人:患者性别女 155 | 详细病情及咨询目的:患病有三年以上,现在医生说有几个血栓,至于有几个是否要做造影才知道?血栓支架多少钱一个?进口和国产的各什么价?\n医生:","冠脉支架植入的价格要看你植入进口的还是国产的,而且还要根据你血管病变情况看需要用多少个支架。一般进口的支架大概是两万五一个,国产的大概是一万一个,一般第二个支架价格要便宜一点。比如你安置了两个进口支架价格可能就是四万左右而不是五万。冠脉造影 支架术目前是一项成熟技术,小到县医院都在做,但一点风险没有是不能的,这与操作者熟练程度有密切相关。","[]","medical_qa" 156 | "病人:和女朋友那个第一次没做安全措施射进去一点会怀孕吗\n医生:","当然是可能导致怀孕的。处女有可能怀孕的。是否是怀孕与是否是处女,与第几次性生活是没有关系的,与处女膜是否是破裂是没有关系的。有的怀孕后处女膜也可能没有破裂 。有的说第一次性生活不会怀孕是非常错误的。所以一定注意避孕 。,妇科疾病的出现不仅仅会影响妇女的生活,还会导致妇科疾病的出现,因此,最好去医院的妇科做一下白带检查,找出病因后对症治疗,平时多注意自身卫生,保持会阴部皮肤清洁。","[]","medical_qa" 157 | "病人:孩子最近仔细检查说扁桃体发炎,流鼻涕,鼻涕有血丝,嘴唇上有时候有像奶瓣样的东西,总流口水,感觉不好好喝奶,但是吃晚饭还可以,打过一针,喝药三天了,怎么还没好?请问:5岁宝宝因扁桃体发炎怎么医治比较靠谱?\n医生:","这考虑是扁桃体炎引来的,可以服食阿莫西林的,同时可以服食小儿咽扁颗粒。同时还要始终保持室内合适的温度和湿度,空气新鲜,实施饮食调理,以清淡易消化饮食为宜,再辅助一些清爽去火,柔嫩多汁的食品摄取。其实得了扁桃体发炎并不可怕,患者要认为自己是可以战胜病魔的,只要及时发现症状,并且对症治疗,缓解病情及康复的几率都非常大。","[]","medical_qa" 158 | "病人:03年时发觉传染已肝,是携带者,那时病毒几百万,肝功能正常,医生给我开了两种很普通清热解毒的中成药,我吃了二个月,查了一下,病毒降了一次方,效果很好,医生说用不着救治了,过了段时间,时常便秘,不知晓怎么解决,现在肝脏有了症状,主要是疼,怎么治疗,乙肝病毒携带者要怎么治疗效果好?\n医生:","目前还没有药物能彻底清除乙肝病毒,如果肝功能正常,一般不须救治,但必须注意如下几点,由于各种抗病毒药物很难有所作为不宜一昧最求阳转阴,应办到调理劳逸和随诊的三结合。降低个人免疫功能和抗病毒能力,力求彻底消除乙肝病毒和始终保持不再病发,不定期复检肝功能,不喝啤酒不抽烟6不吃刺激性重的食物,保证深度睡眠注意休息。一定要有个好心情。肝病患者在及时救治之外,患者在生活中还需要有注意要注意始终保持深度睡眠,充足的深度睡眠方才能帮你尽快远离此病,期望上述的答案可以协助到你,","[]","medical_qa" 159 | "病人:由胆囊炎引起的胰腺炎如何治疗\n医生:","首先要把胰腺炎控制好,然后尽量根除引起胆囊炎的原因,常见病因为胆囊结石,尽量挣取手术治疗,因为反复的胆囊炎可引起胰腺炎的再发. ,患者们一直关心胰腺炎这个大问题,除了服药治疗此病外,患者还需要重视饮食方面,例如饮食清淡,避免辛辣刺激食物。与此同时患者还要注意选择一家正规医院诊治,这样才能得到良好的治疗效果。","[]","medical_qa" 160 | "病人:无\n医生:","你好,如果月经推迟7-10天的话建议做早试纸检查,如果是2根红线表示阳性,表示怀孕的可能.一般是晨尿检查最好,此外同房后7天后也可以到医院做血hcg检查。","[]","medical_qa" 161 | "病人:宝宝一个月了,家里有人感冒,怎样能防止传染给宝宝?\n医生:","感冒是有可能传染给宝宝的,感冒绝大多数都是病毒感染的,可以通过呼吸道散播的感冒的人不要抱宝宝,不能够跟宝宝待在一起,及时救治感冒,可以使用 感康、利巴韦林这些药物救治,多喝水,饮食清淡,不要吃辛辣刺激的食物,不要暴饮暴食,注意休息,不要熬夜。","[]","medical_qa" 162 | "病人:右侧睾丸大小30mm X 15mm X 22mm,体积7.03ml ,左侧睾丸大小 50mm X 32mm X 39mm,体积44.3ml ,右侧睾丸外形偏小,回声分布均匀。左侧睾丸被一枚低回声团块占据,正常组织受压菲薄,该团块大小46*33mm,边界欠清,形态欠规则,呈分叶状,内见多发散在强回声,最大2.8mm,该团块内见多发片状低回声区,范围6*7mm,CDFI 可见团块内部血流丰富,低回声区内血流较少。 163 | 右侧附睾头厚9mm,尾厚5mm,左侧附睾头厚9mm,尾厚6mm,双侧附睾大小形态正常,回声分布均匀。\n医生:","睾丸肿瘤,需要高位探查手术,术中冰冻肿瘤病理检查,良性切除肿瘤,恶性切除睾丸。","[]","medical_qa" 164 | "病人:孩子今年1岁了,患得癫痫病,想咨询一下,小儿癫痫病早期症状是什么\n医生:","1、 小儿全身性发作:小儿癫痫症状表现为意识突然丧失,呼吸暂停、口吐白沫、面色青紫、瞳孔散大,抽搐开始为四肢的强直、握拳、两眼上翻或偏斜一方,然后小儿面部及四肢肌肉呈阵挛性抽动,呼吸急促不整,常有舌咬伤,可以有大小便失禁。2、小儿躯体局部肌肉或肢体的抽搐发作:这种小儿癫痫持续时间可能比较长,一般没有意识丧失,严重发作以后抽搐部位的肌肉可有暂时性麻痹。","[]","medical_qa" 165 | "病人:新生儿主要症状:孕期32周仔细检查胎儿肾盂分离个0。7个0。8,宝宝降生以后多长时间去医院仔细检查比较好?\n医生:","对绝大多数的在胎儿期发觉的肾积水患儿,在降生后一周时需要有实施正规的泌尿系统的磁共振仔细检查,如果有肾盂融合≥10毫米,(你的孩子融合不是太大,下面我还要说)就需要有在专科医生指导下实施全面仔细检查,抱括核素肾显像,代谢性膀胱输尿管造影等,明确病因;如果肾盂融合在4-10毫米之间,需要有在生后3个月和6个月时复检磁共振仔细检查;如果肾盂融合4毫米可以视作正常。","[]","medical_qa" 166 | "病人:第一针乙肝跟第二针乙肝最多间隔多长时间?是一个月么时补种第一针乙肝。现在过了一个月了。他生理性腹泻。能不能打第一针乙肝?如果推迟打的话,最多能隔多长时间第一针乙肝不过期。 \n医生:","孩子由于恶心呕吐的原因,麻醉乙肝疫苗必须要延后,以免再次出现不良反应增强的情况。所以这个情况可以延后麻醉,待孩子腹泻转好后就可以去麻醉疫苗,但一般不能够延后低于一个月的时间,第二针可以按时接种疫苗就可以,用不着延后的,期望我的回覆对你有所帮助!","[]","medical_qa" 167 | "病人:老人家已经得了有老年痴呆症一年多了,最近一段时间就老是喊头晕,头疼。我姐姐说是高血压引来的,我们之后也给他吃了降压药。现在就是饮食方面,想问下医生,高血压的人应当注意什么?\n医生:","1.首先患者需要有增加盐分的摄入,盐一般一天的摄取量不能够大于六克。2.注意血压需要有及时治疗,防止出现许多其他的严重病情,比如说可能会再次出现脑出血等情况。3.饮食一定要注意清淡,不能够吃太过油腻的食物,尤其是所含脂肪量高的食物,注意多加休息。","[]","medical_qa" 168 | "病人:这几天也不知道怎么了,总是觉得尿很急,但是去上厕所又感觉没多少尿,有时候就那么一滴两滴的,晨尿时还发现自己尿分叉了,请问:如何鉴别得了前列腺肥大呢\n医生:","依据你的叙述综合分析;前列腺肥大,小便困难。一般治疗、前列腺推拿、药物注入、前列腺周围组织隔离、联手运用抗生素等。另外可以互相配合中药治疗。前列腺增生治疗上可以考虑中医药物结合物理疗法,治疗可用非那雄胺。舒张前茅脾平滑肌,緩解症状。但需在医生指导下实施规范治疗。","[]","medical_qa" 169 | "病人:12年确诊慢再,在天津血液研究所门诊吃了15个月药效果不大,13年11月加重,进行atg治疗至今\n医生:","环孢素浓度看谷浓度的,要200以上,你才一半,效果自然不好。峰浓度无意义,我从不给患者测,浪费血和钱。 最关键环抱浓度没抓住,其他还搞了堆杂七杂八药物。","[]","medical_qa" 170 | "病人:小腿困乏 \n医生:","肝炎治疗的总体目标是:最大限度地长期HBV,减轻肝细胞炎性坏死及肝纤维化,延缓和减少肝脏失代偿、肝硬化、HCC及其并发症的发生,从而改善生活质量和延长存活时间。口服中药治疗和抗病毒药物治疗的,提醒患者们,如果乙肝病情复发,除了再服用药物改善病情外,患者还需要适当做一些有氧运动,并且合理饮食,这样可以帮助患者缓解乙肝症状,希望对您有帮助,祝您健康!","[]","medical_qa" 171 | "病人:普通内科都能看什么的病?请问男性雌二醇高一点如何解决\n医生:","您的雌二醇只是高一点,如果您的肝功不是很异常,也没有肝硬化之类的话,一般不会那么严重的,您只有26岁,有可能只是暂时性的一过性的升高,可以复查一个激素和肝功的,必要的时候去消化内科看一下啊。,我们都知道内科疾病对患者的影响比较的,一旦发现后就该及时救治,同时患者日常中还需要重视自身的护理,并且建议多饮水,饮食上一定要注意,希望内科疾病患者可以及时得到救治!","[]","medical_qa" 172 | "病人:医院能自愈早泄吗?我最近一直觉着很我总是不能够在房间里站下来。有时我不能够在不到的两分钟的时间里捉住我的室友。我妻子说我可能有早泄和早泄。我还是那么年恐怕我会一直这样。阳萎和早泄能不能够通过活动和饮食来调整?\n医生:","首性爱是男性朋友运动的一小部分。90%的男性有性爱的习但是长时间的性爱会致使前列腺疾病。随着时间的流条件射精的构成会很所以性爱的次数不能够太多。现在你要插进它是由条件射精刺激引来的。慢慢地舍弃性举办适当的体育锻炼。现在这种情况不能够说是早这是由性交快速射精引来的条件反射。通常多吃含锌食然后吃谷维素来减低植物神经的敏感性。彻底摆脱性你会好下来的。祝你身体健康。","[]","medical_qa" 173 | "病人:半月前,肿痛,没就诊\n医生:","你的这种情况可能是结节状甲状腺炎或多发性甲状腺瘤,建议做红外扫描,一般可以考虑用活血散结一类的中药进行治疗,严重时必要时可以考虑手术治疗,等到肿瘤与疼痛病情得到缓解的时候,患者切忌盲目饮食,最好以清淡食物为主,如果选择了手术治疗,术后一定要重视自身的护理工作,并且需要加强营养,适当外出运动,希望患者病情可以得到缓解。","[]","medical_qa" 174 | "病人:甲亢为什么脖子不肿大,眼睛不突,反而从双三年前患甲亢,因为不严重所以没怎么治,现\n医生:","根据您的情况考虑是轻度甲亢的症状,积极治疗一般是可以停药的。建议规律用药控制,预防复发。注意清淡饮食,忌辛辣刺激性食物和避免食用高碘食物,定期检查。","[]","medical_qa" 175 | "病人:我在一家私家医院做的手术.因为当时什么都不懂就听医生说这样呀那样呀.怕急了后来朋友建议我去大医院仔细检查看一看.结果仔细检查出的是根本就没做但是期间也漫过血呀.我现在才19岁不知晓对以后受孕可有影响?在乎怎样的帮助:对以后的受孕可有影响?现在要怎么治疗?\n医生:","女性,19岁,宫颈糜烂,没做手术,如何影响受孕严重的宫颈糜烂可能会影响怀孕,但也不是绝对的,仍然有患者患宫颈糜烂的同时怀孕了。尽管如此,但是仍然建议将宫颈糜烂治好后再怀孕。建议做宫颈细胞学检查,结果未见异常就可以决定药物治疗。宫颈糜烂的再次出现严重影响了女性的健康,患者需要有生活中注意经期后复检,清淡饮食,不可以吃辛辣刺激食物。","[]","medical_qa" 176 | "病人:病情描述:患者女,22岁,此次病情:排尿过程中无明显痛感排尿快结束时有血,之前尿液是正常的颜色患病之前因嗓子哑,吃过黄氏响声丸和枇杷糖腹部有点不舒服的感觉,但不疼曾经治疗情况和效果:自己吃过盐酸环丙沙星还有克拉霉素,情况没有好转想得到怎样的帮助:大概是什么病因应该吃什么药\n医生:","考虑泌尿系感染问题导致,建议正规医院泌尿科进一步检查确诊,一般需要查尿常规检查确诊,确诊后可以口服或者静脉滴注抗炎药物治疗,头孢类或者青霉素类药物都可以,根据您描述的情况可能是尿路感染或肾结石引起的不适,建议您去医院泌尿外科检查,明确病情,对症治疗。多喝水,不要憋尿,不要吃辛辣刺激性食物。希望回答帮助到您,祝您健康快乐!","[]","medical_qa" 177 | "病人:最近我的膝盖非常的疼痛,特别是上楼梯和下楼梯的时候,就疼痛的厉害。我最近去医院做了个尿酸仔细检查,结果显示尿酸值偏高,医生说拥有痛风性关节炎。如何治疗痛风性关节炎?\n医生:","中医相信痛风是由于人体内部正气不足,肝肾亏虚,后因外感风寒湿热之邪,而使气血运转不畅,不通则痛而致使的。膝盖疼痛明显主要考量是因为体内尿酸下降致使的痛风性关节炎,这种可能会是因为最近这段时间吃动物内脏或者喝啤酒以后致使的。具体需要有到医院进一步仔细检查,平时也可以服食消炎镇痛的药物,具体用药请遵医嘱,同时每天要多喝点温水,建议你要干扰食用如动物的内脏、海鲜、豆制品等一切含有嘌呤的食物,禁酒令,尽快采取中医疗法积极救治。","[]","medical_qa" 178 | "病人:月经一直不是很规律,有时候会45天来一次,有时候又是正常的28天来一次,半年前跟我老公结婚想要孩子,所以每次同房都不做保护措施,上个月同房后居然出血了,这月经不调性生活时出血是怎么回事?\n医生:","月经如果不规律,需要有来月经期间检查一下激素水平,看一下激素6项如何紊乱,同房再次出现出血的情况,需要有做个宫颈筛查,而且需要有做个阴道镜检查宫颈看宫颈如何有炎症,如何有炎症,具体是什么情况,如果平时白带多的话还需要有仔细检查白带常规。妇科病是一种容易复发的妇科疾病,在服药期间,女性需要有看重自身的护理,尤其是护理方面,建议患者多注意注意阴部卫生,饮食清淡为基础。","[]","medical_qa" 179 | "病人:朋友生二胎后,没注意避孕,结果又怀孕了,只好做人流,人流手术塘沽哪里好?\n医生:","人流手术是可以去当地的公立医院来做,其中大学附属医院,正规医院,除了妇幼保健院,这些都是做为合适的,是可以挂妇科的号,先遵从医嘱,做个妇科B超。明确一下孕囊的大小,明确一下孕周,然后再考虑恰当的手术方案,最好不要去私立的专科医院,省得可能会乱收费。","[]","medical_qa" 180 | "病人:起床时头晕本次发病及持续的时间:2分钟目前一般情况:起床时头晕病史:每年出现1-3次以往的诊断和治疗经过及效果:无\n医生:","中医认为,颈椎病为风寒湿邪所致,瘀邪交结、凝而不散,五 枝膏 治疗颈椎病是以祛风散寒、活血化淤为目的,遵循中医通则不痛的原理,所以效果彻底。还要注意防寒保暖。,脊髓型颈椎病患者在马上治疗之外,患者在生活中还需要注意要保持良好的心情,好的心情对疾病的恢复很有帮助,希望上述的答案可以帮助到你,谢谢!","[]","medical_qa" 181 | "病人:外阴白色病变,外阴萎缩.该吃什么药有什么办法解决,很难受困扰很久心里也不舒服求解决办法\n医生:","外阴白色病变是女性外阴皮肤再次发生变性和色素减退的一组慢性疾病,最新的试验证明该病主要是皮肤的真皮层再次发生炎症。患者主要表现为外阴奇痒难忍和皮肤变白等症状。目前采取海扶磁共振聚焦于知识救治外阴白色病变,不仅能有效缓解瘙痒症状,而且可使炎症的皮肤恢复正常。详细情况可以点击回复单位实施理解。外阴萎缩的治疗方法有一些,但是由于患者病情不同所以采用的治疗方法也就不一样,因此患者需要有及时仔细检查诊断,方才能对症救治。","[]","medical_qa" 182 | "病人:去年年初胃镜检查是糜烂性胃炎和食管发炎,最近一直觉得腹部胀,有时会有反流现象。总觉得腹部胀,好像腹部和背部有痛感,大便也很正常,食欲很好,只是不敢多吃,在昆山人民医院和中医院治疗过。\n医生:","你好,可以在医生指导下服用得必泰颗粒以及奥美拉唑肠溶胶囊 阿莫西林胶囊 克拉霉素治疗,一般需要服用2--4周.避免暴饮暴食和生冷食物.辛辣刺激性饮食.不能吸烟喝酒.祝早日康复,除此之外,患者在治疗胃炎期间,除了要及时治疗外,患者的饮食状况和心理状态也是十分重要,患者一定要避免精神上过度的紧张和忧虑,以免对胃炎的恢复造成了不必要的影响。","[]","medical_qa" 183 | "病人:无\n医生:","流产最好人流,安全有保证,药物流产容易流产不全,最好在宫腔镜指导致下行清宫术,术后没有残留物,一般不会导致大出血,","[]","medical_qa" 184 | "病人:无\n医生:","可能感冒引起的症状,建议你平时要注意休息,清淡饮食,避免疲劳,建议服用三九冲剂及清开灵及左氧氟沙星片及枇杷止咳糖浆治疗,待感冒好些建议服用转移因子口服液增强抵抗力。","[]","medical_qa" 185 | "病人:女,51岁,精神最近不是很好,然后才得知生病了,请问:卵巢囊肿腹腔镜手术后一直未排气怎么回事\n医生:","根据你说的情况。考虑腹腔镜下手术以后一直没排气。阴道出血。建议可以用对症药物肛门麻醉。或者口服四磨汤迫使排气。适当运动。阴道极少量破皮是手术所致。疾病的治疗方法有很多,但是由于患者病情不同所以采取的医治方法也就不一样,因此需要患者尽快去专业一样进行详细检测,才能对症下药。","[]","medical_qa" 186 | "病人:宝宝30周慢慢的身体就不舒服,也不知道怎么了,似乎没有精神请问:宝宝感冒流鼻涕怎么救治疗比较好的快点\n医生:","小孩子抵抗力弱,容易再次发生感冒症状,家长也不要太过忧心。可以给孩子喝一些感冒灵颗粒,并且作好鼻部的护理,防止局部皮肤受分泌物刺激。留意防寒,饮食清淡。如果再次出现发烫,咳及时就诊救治。不要有任何的心理压力,保持愉快的心情,而且期间要注意多休息,同时饮食也要保持清单,避免油腻和辛辣,这样对你自己和腹中的胎儿都是有好处的。","[]","medical_qa" 187 | "病人:家里有一些红枣,想带去给亲戚,可是有个亲戚得了乳腺增生结节。您好医生,有乳腺增生结节的人能吃红枣吗?吃了红枣后会不会缓解病情?有乳腺增生节结的人能吃什么?不能够吃什么?\n医生:","如果有乳腺增生乳腺结节的人可以足量的吃点红枣,但是不要吃多了,吃多了容易致使闹肚子,乳腺增生的症状缓解。有这种疾病的时候,平时还需要有注意不要吃辛辣刺激性的食物,始终保持心情舒畅,不能够总是着急和生气,如果心情不舒畅的时候,就会再次出现乳腺增生的症状缓解。","[]","medical_qa" 188 | "病人:我昨天去做了唐氏综合症筛查,如何看化验单判断是否患有唐氏综合症?\n医生:","对于新生儿来说,一般先天性愚笨的孩子都会有断掌纹,这就是所谓的唐氏综合征,也是判断的标志之一。但并非所有手掌截肢的新生儿都有唐氏综合症。而且,在您怀孕期间,您应该进行相关的孕期检查,孕期检查,如果有问题,这种情况应该在怀孕期间检查,因为一般这种情况下孕妇会选择流产自己的孩子。如果你的孕检和产检结果正常,我认为你的孩子绝对不是“唐氏综合症”。","[]","medical_qa" 189 | "病人:医生我有前列腺炎已经纤维化了现在阴茎下腹感觉有点酸痛,现在勃起不坚除了早泄除了晚上睡午觉神经衰弱舌胎肥大两边有齿痕。怎么办?\n医生:","前列腺钙化,有可能是前列腺炎遗留下的疤痕,也有可能是因为前列腺结石的前兆。勃起不好和前列腺炎是有关系的。对于前列腺炎可以使用前列康前茅舒通胶囊等药物。对于前列腺患者来说,及时治疗是可以减低复发,如果不及时治疗会影响到受孕情况。因此患者要及时对症治疗,并且日常生活中要以防过劳,注意自身卫生情况。","[]","medical_qa" 190 | "病人:无\n医生:","经期过性生活跟月经延迟之间没有必然的联系。但不提倡经期性生活,因为对容易造成女性生殖系统感染,如果长期如此,则有可能影响生育能力","[]","medical_qa" 191 | "病人:女宝宝,目前6岁,一开始,说自己咽东西疼,发现,说话的时候声音有点沙哑,另外,现在已经高烧不退了,请问:小儿扁桃体发炎哭闹该如何治疗才好。\n医生:","治疗的话首先可根据孩子症状给予对症消炎药,局部治疗的话建议选择激光治疗或是药剂冲洗,如孩子咽痛症状尤甚,建议选用一些镇痛药缓解症状,要的有发烧的情况,那么根据体温选择降温的方法,38.5摄氏度以下可物理降温,高于38.5摄氏度的话则可口服退烧药,如果你的孩子经常发生这种情况,那么在病情得到控制后,可以考虑手术治疗的,以免反反复复,治疗期间还要注意保持饮食卫生,以及足够的休息时间。","[]","medical_qa" 192 | "病人:宫颈息肉大米粒大小,做过HPV检查,阴性现外阴科长出疙瘩,有点疼是怎么回事\n医生:","根据所说的情况来看,霉菌性阴道炎和滴虫性阴道炎都是平时卫生留意不到的和身体抵抗力上升引来的,建议不要紧张,始终保持心情愉快,平时留意局部卫生,夫妻双方都留意,祝早日康复此外,滴虫性阴道炎患者在救治期间,患者的饮食状况和护理也是很关键的,患者一定要消化维生素,预防工作闹肚子,并且清淡饮食,以免引发不必要的伤害,期望上述的答案可以协助到,谢谢。","[]","medical_qa" 193 | "病人:幽门螺杆菌230会致使什么病刑事幽门螺杆菌=230,,是什么意思?\n医生:","正常情况下,胃壁有一连串改进的自我守护机制(胃酸、蛋白酶的排泄功能,不溶性与可溶性粘液层的守护效用,有规律的活动等),能抵挡经口而入的千百种微生物的肆虐。幽门螺杆菌刺破粘液层在胃上皮细胞表面移居,对胃上皮细胞等起摧毁效用的毒素因子;各种炎症细胞及炎症介质。幽门螺杆菌过高会致使慢性胃炎,胃溃疡。","[]","medical_qa" 194 | "病人:患了妇科炎症,已经有在喝药调养身子了,但其他方面不是很清楚,您好妇科炎症需要有留意什么?\n医生:","有妇科炎症的女性要约束性生活以防止性生活加剧炎症。在治疗方面可以使用妇科病洗液清热解毒或左氧氟沙星进行抗炎症治疗。如果症状没稳定,建议到正规医院的妇科进行系统的仔细检查,明确病因后再确认具体的治疗方案,感谢您的进行咨询,期望对您有所帮助。在生活上也要注意卫生情况。","[]","medical_qa" 195 | "病人:50岁女性,年轻时体力活做的比较多,落下腰疼的毛病,最近参加一次登山活动,回来腰疼的很,常站不起来,邀椎部分连肉都是硬硬的,有可能是什么情况?\n医生:","您的这种情况需要具体分析了,多为腰肌劳损或者腰椎间盘病变引起的疼痛不适,您最好去医院检查一下ct,如果为腰肌劳损,需要及时的腰部减少活动,可以口服氯唑沙宗片、独一味胶囊等药物治疗,多可自行缓解。如果为腰椎键盘病变可以进行腰椎牵引,避免久坐久站,口服腰痛宁,?侗云?纫┪镏瘟啤=ㄒ槟?ヒ皆壕咛寮觳橐幌拢?辔??±退鹨?穑??切枰?懦?幌伦导渑掏怀觥","[]","medical_qa" 196 | "病人:出现这种情况我是很害怕的,动不动小腹疼痛,不知道怎么解决呢,所以我过来咨询,请问妊娠期糖尿病生产后多久能恢复\n医生:","根据你的描述一般分娩后是可以恢复的,需要激素治疗,胰岛素治疗增加营养补充维生素微量元素,易消化易吸收饮食,避免不良刺激。,一般来说,医生会建议有妊娠期糖尿病危险迹象的妇女应合理饮食,远离辛辣刺激以及寒冷食物。此外,患者还应创造一个有利于情绪稳定和释放紧张的环境。祝愿患者健康分娩。","[]","medical_qa" 197 | "病人:无\n医生:","有必要做宫颈癌防治筛查,因为,宫颈癌的罪魁祸首是HPV,感染了HPV的女性比没有感染HPV的女性得宫颈癌的概率要高出几十甚至几百倍。提前做好预防是很有必要的,预防重于","[]","medical_qa" 198 | "病人:无\n医生:","你好,甲状腺疾病现在很常见,你的甲状腺彩超结果说明你有甲状腺结节,该结节呈囊性。一般甲状腺囊性结节中的强回声光点就会伴有慧星尾征,这种伪像和大量的胶质有关系,而大量的胶质一般表明是良性结节,具体的需要病理检查。甲状腺结节是很常见的疾病,很多人终生都有,但因无症状而未被发现。但是结节分很多种,有单纯性的,也有容易产生变性的,因此鉴别良恶性的最好的方法就是做病理检查。","[]","medical_qa" 199 | "病人:无\n医生:","男宝宝才会有的症状,被自己的尿憋的,即便很严重产后及时治疗就没事了!宝妈不要太担心。如果是轻微的就没有关系。不到十公分应该没事的。","[]","medical_qa" 200 | "病人:早孕先兆流产,生长发育异常只有胎囊伴腹痛,医生建议人流,本月23号做的,当天出血量挺多,我喝了两大杯红糖水就休息了第三天下午就干净了,一直到25号晚上都是干净的,可是我家开了饭店25号夜晚亲戚朋友过去我就去帮帮忙了,大概忙了有三个小时左右,然后就破皮了。\n医生:","根据你所叙述的这种情况,做完人工流产以后应当注意休息,活动量大了累了阴道就可以破皮,而且量是比较多的。鉴于以上你所说的这种情况,如果这几天没破皮,量并不多,应当问题不大,如果出血量一直比较多,但又肚子疼呢,最好去医院做个B超,剔除一下宫内可有残存的情况。","[]","medical_qa" 201 | "病人:小孩子右边小气肠有一个多月了. 曾经的救治情况和效果:上次仔细检查过,这次病发了.在乎怎样的协助:我8个半月的女儿小气肠需要有动手术吗?\n医生:","2岁以后如果没自行转好再手术救治。而且最好还是手术救治。2岁以前都可能会自行转好的。但是如果再次发生嵌顿任何时候都是需要有紧急手术救治的啊。平常只需要有留意以防便秘,消化不良,哭啼这些腹压增强的因素就可能会自行结疤的。如果能买到疝气袋来堵上疝气薄弱的部位能更放慢增强自行结疤的可能会。","[]","medical_qa" 202 | "病人:我生了2个宝宝,现在和老公做爱每次我都满足不了他,做了那么久他都射不出来\n医生:","病情分析:不射精症通常是指阴茎虽然能正常勃起和性交,但就是达不到性高潮和获得性快感,不能射出精液;或是在其他情况下可射出精液,而在阴道内不射精.两者统称为不射精症.指导意见:器质性不射精症多见于先天性泌尿生殖系统发育异常,脊髓损伤,输精管梗阻,某些颅脑病变,女性阴道过于宽松和服用某些药物等,没有精神性不射精症多见.不射精症影响生殖健康,可引起男性不育.另外,不射精症由于在性交中无性高潮,使性的兴趣大减,因而往往可伴有性欲减退,夫妻之间也可能出现一定程度的感情危机,因此应主动就医.不射精症的治疗要区别不同病因,采取病因学治疗.","[]","medical_qa" 203 | "病人:无\n医生:","你好,据你所述的情况,是有这个可能的,这是胃炎的症状建议你做胃镜检查,确诊后服用奥美拉唑,吗丁啉和胃炎颗粒治疗,","[]","medical_qa" 204 | "病人:一直以来就这样,性交不到一分钟。以前经常过手淫,坐久了睾丸会胀痛,在东莞口岸医院做过背神经手术,广州军区医院治疗过\n医生:","早泄原因是多方面的:首先男性阴茎包皮过长、紧身内裤等过度刺激龟头都会导致男性出现早泄,其次是心理性早泄,引发男性射精过快神因素包括很多方面。男性性生活的紧张情绪一直延续,同时长期的性生活失败又会出现反作用,造成患者心理上的恶性循环。最后是器质性病变:很多男性疾病都会使男性的射精中枢兴奋度降低,也就是更容易发生射精,比如尿道炎、精囊炎、前列腺炎等炎症。治疗可以针灸按摩,药物金匮肾气丸,五子衍宗丸调理","[]","medical_qa" 205 | "病人:我家的孩子是男宝宝,1岁,这一周,孩子说自己耳朵又痒又疼,另外,发现耳屎是脓状的,有点黄,另外,食欲也不好,嗓子也不舒服,请问:孩子中耳炎耳朵流黄水应怎样医治。\n医生:","如果孩子得了中耳炎的话,首先可以用点对症的抗生素药物,可以做耳部分泌物细菌培养,根据检查结果使用消炎型的滴耳液,孩子如果耳痛比较厉害的话,建议是可以根据情况给点镇痛药的,孩子要是伴有发烧家长可以给孩子给予一些有退烧的药物或者马上送孩子去医院,除了这些药物治疗的方法之外,如果孩子情况严重出现耳膜穿孔是需要去医院进行手术治疗的,治疗的同时也要注意给孩子安排清淡的饮食,加强营养的补充,帮助尽早康复。","[]","medical_qa" 206 | "病人:眩晕症在广州哪家医院治疗较好?\n医生:","你好,你说的这种情况通过我们的分析认为可以到当地正规三甲医院咨询治疗.","[]","medical_qa" 207 | "病人:我是反流性食管炎,贲门炎,慢性非萎缩性胃炎,十二指肠炎HP+,请问我该如何治疗呢?\n医生:","慢性胃炎需要有慢慢调理。胃拥有情绪器官,始终保持乐观、高兴的心情对于胃病的自我彻底恢复非常重要。俗话说,十人九胃,不要着急,饮食留意不要吃过极冷、油腻的食物,不要过饥和过饱,必要时少吃多餐。多吃水果和蔬菜。水果留意不要吃过凉性和热性的水果,苹果很不错。胃病缓解期建议吃点中药的汤药。还可以配上雷贝拉唑钠等西药胃药来吃。可以吃点守护胃粘膜的药物。","[]","medical_qa" 208 | "病人:包皮过长,经常性交打飞机,现在一分钟不到的就收工了,有时候跟女生一同抱一抱就都出的了,现在感觉勃起的时间也短了,也没以前那么勃起有力了\n医生:","这种情况可能会跟包皮过长有关,建议最好去三甲医院泌尿外科检查一下,可以考量手术摘除救治。如果不能够稳定,可以口服锁阳固精丸,肾宝胶囊救治。此外,男科病患者在救治期间,患者的饮食状况和护理也是很关键的,患者一定要留意歇息,可以适当活动,以免引发不必要的伤害。","[]","medical_qa" 209 | "病人:我家农村的,乡里医生说宝宝是手足口病,用不着到医院仔细检查,怎么治疗\n医生:","手足口病是一种由肠道病毒引来的、好发于小儿的传染病,救治手足口病采取中药效果最好,一般用内服药和口腔涂药相结合,无并发症者一周约莫即可康复预后良好要定时让患儿用温水冲洗脸腔;禁食冰冷或辛辣有影响的食物,不要给与咸食,以免引来疼痛而拒食;饮食要易消化,吃许多清淡、质软、温性的饭菜,多喝温开水。孩子被手足口病所危害,因此,家人一定要带孩子立即就诊救治,避免出现种种误区,要及时对症救治","[]","medical_qa" 210 | "病人:我家的邻居说他的父亲时不时的会出现眼睛发直,口吐白沫,叫不醒,等症状,然后过一会儿就又没事了,经常是在晚上的时候发作,去医院说这是癫痫的症状,现在该怎么办呢?\n医生:","你好,根据你的病情描述,你的邻居的父亲存在眼睛发直,口吐白沫,呼之不应症状,考虑是间歇性癫痫发作引起。 211 | 意见建议:建议去医院神经内科就诊,完善头颅磁共振,脑电图协助诊断。如果是间歇性癫痫引起,可使用丙戊酸钠或者卡马西平进行治疗。","[]","medical_qa" 212 | "病人:我27岁,男最近老是阳萎,由于上班忙,也没过多的担心这事,但近段时间越来越严重,我就已经开始担心了,在老婆面前很不好意思的,请问治疗阳痿需要多少时间\n医生:","关键引来早泄的原因许多,需要有通过仔细检查明确具体引来早泄的原因,以后再针对性救治,我想救治的时间就比较短。前列腺炎容引来早泄,激素水平上升容易引来早泄,生殖道的炎症也容易引来早泄血管炎症也容易引来早泄,要针对这些方面具体的检查一下。患者日常要养成良好的生活习惯,规律作息,禁烟酒,多增加日常锻炼以此来提高患者免疫力,避免病情复发。","[]","medical_qa" 213 | "病人:已经怀上8个月了,2月20的预产期,上次仔细检查是2018年12月28日,医生说宝宝很好,补钙很好,胎位正,什么都好,就是有点贫血。今天1月4日,去理发店做了软化,药水味重,药水没贴到头皮,不知晓对宝宝可有什么干扰 \n医生:","怀上期间最好不要去做头发,因为化学制剂对胎儿是会有一些干扰的,具体干扰多大,现在也无法推断。建议你留意歇息,防止操劳,多散步,增强顺产的几率。平时要多食用含铁丰富的食物,不定期做产检。以上是对“已经怀上8个月了,2月20的预产期”这个问题的建议,期望对您有帮助,祝您健康!","[]","medical_qa" 214 | "病人:详细病情及咨询目的:头晕头痛,高血压高血脂,天天如此 215 | 目前一般情况:头晕头痛,高血压高血脂,天天如此\n医生:","患了高血压病,一要在全球高血压联盟推荐的6类降压药中选择,且主张联合应用;二要尽可能选用长效降压药,一日1次用药便可维持血压24小时稳定,减少波动;三要与生活方式改善及饮食调理紧密结合,特别注意低盐、低脂、控制体重和体育锻炼。 全球高血压联盟推荐的6类降压药是利尿剂、血管紧张素转化酶抑制剂(ACEI)、血管紧张素Ⅱ受体拮抗剂、-受体阻滞剂、钙拮抗剂和抗胆碱药。缬沙坦是不错的,可以考虑。","[]","medical_qa" 216 | "病人:无\n医生:","你好,考虑为残留,可以做B超检查帮助诊断,发现有残留,体积较小者可以采用益母草膏及消炎药进行治疗,较大者药物治疗不好,可以采用清宫进行处理,术后注意会阴部的卫生很重要,不吃辛辣刺激性的食物。","[]","medical_qa" 217 | "病人:普通内科都能看什么的病?请问血小板平均体积偏低是什么原因\n医生:","血小板平均体积偏低,对身体一般没有影响的。血常规检查中关于血小板的项目中有意义的是血小板计数,其它明显是根据血小板数计算出来的,如血小板正常,没有异常出血,轻微异常,意义不大,无需治疗。,我们都知道内科疾病对患者的危害比较的,一旦发现后就该及时救治,同时患者日常中还需要重视自身的调节,并且合理饮食,病情好转后适当的运动,希望内科疾病患者可以及时得到救治!","[]","medical_qa" 218 | "病人:半年前确诊的食道癌,一个朋友给我们说有一个偏方,说可以先试试,于是就用了一段时间的偏方,刚开始用的时候好像还有一点效果,后来慢慢就没有效果了。也不清楚偏方里的成分是什么。有没有毒副作用?y\n医生:","您好!中医治疗食道癌,讲究的是辩证施治,对症治疗,一人一方,针对患者不同的体质,病变不同的阶段,所用的药物都不一样。偏方治疗食道癌疗效并不确切,也很难做到一人一方,对症施治,因此对食道癌的治疗还是应该要重视起来,选择合适的专业的治疗手段才能延长患者的生命,不要盲目偏信偏方,以免耽误病情。","[]","medical_qa" 219 | "病人:无\n医生:","你好,产后42天一般主要检查恶露排出情况,和子宫复旧是否正常。内分泌指标等方面的情况,若是没有其他问题,注意保持良好的饮食和生活习惯即可。","[]","medical_qa" 220 | "病人:孩子晚上睡觉太冷,总是爱踢被子,着凉了,白天就流鼻涕,鼻子红通通的,晚上睡觉的时候就鼻塞、鼻子呼吸困难了,而且感觉嗓子里有痰一样。新生儿鼻塞、鼻子呼吸困难怎么办?\n医生:","当孩子鼻塞,呼吸困难时,建议妈妈用干净的毛巾或纱布,蘸上热开水,分层包好。小心别把孩子烧了。然后把包好的布放在孩子鼻子根部(即眉毛下面一点)热敷。热敷时间一定要长,你可以换一次开水,再煮几次。这样可以刺激孩子的鼻子,可以减少孩子打喷嚏,也可以使孩子鼻子不堵,鼻子呼吸困难,使孩子呼吸顺畅。","[]","medical_qa" 221 | "病人:皮肤上起了很多黑色的像斑点的东西,又痒又痛,还会脱皮,去医院检查是黑色素瘤,请问黑色素瘤有法自愈吗?\n医生:","你好,根据你的叙述黑色素瘤是起源于皮肤色素演化出细胞的一种皮肤癌,黑色素瘤没再次发生扩散,黑色素瘤的手术及治愈率可达到百分百,如果再次发生扩散根据扩散情况经过手术治疗5年生活率可能会为50%到70%,但是患黑色素瘤的患者可能会有再生长黑素瘤的危险,建议不定期实施皮肤仔细检查。除了正规治疗黑色素瘤外,患者还需要有看重护理方面,比如日常清淡饮食,多出外活动。","[]","medical_qa" 222 | "病人:癌症晚期能不能治好 怎么治\n医生:","你好!根据你的情况考虑对于癌症晚期主要是指恶性肿瘤发展到比较严重的阶段,已经失去了治疗机会的时期建议目前对于癌症晚期还没有特殊的治疗手段与方法,主要以对症治疗及阳光治疗为主也就是安慰治疗,目的是提高患者的生活质量,并减轻患者的痛苦,尽可能延长生存时间。祝健康","[]","medical_qa" 223 | "病人:无\n医生:","怀孕前三个月,主要是器官发育的时间,胎儿还没有长大,这个时候主要出现的是早孕反应,而不是你说的尿频症状,没有也是正常的,定期产检就可以了,应该是没有问题的,请你不用担心。","[]","medical_qa" 224 | "病人:医生你好,我今天去健康检查了,之前医生说是先兆流产可是我都没破皮,我当时还打了黄体酮和绒毛素,但是现在啥事都没,想问一下医生,我现在恢复正常了吗?\n医生:","如何有先兆流产一般需要有通过B超仔细检查来推测的,有的时候并不一定破皮,但是宫腔里面如果有积血液,就可以推测为先兆流产。建议需要有按照临床诊断医生的医嘱结合具体情况来针对性的对症治疗,多注意休息,减少行走,注意仔细观察自身症状,积极的实施保胎治疗,不定期复检彩超,仔细观察胎儿的生长发育指标。","[]","medical_qa" 225 | "病人:肺癌静脉输液0.9%氯化钠银杏达莫疼痛\n医生:","晚期肺癌一般已经出现扩散转移的现象,如果允许手术,可以做手术治疗,这对延长生存期是有帮助的,同时可以服用人参皂苷Rh2,具有抗癌的左右,同时提高免疫力,缓解晚期一些常见的并发症,提高患者生活质量。,等到肺癌病情得到缓解的时候,患者切忌停药或者更换药物治疗,如果选择了手术治疗,术后一定要重视自身的护理工作,并且注意补充维生素,多吃清淡的食物,希望患者病情可以得到缓解。","[]","medical_qa" 226 | "病人:我儿子今年6岁这3天一到下午和晚上就发高烧而晚上睡午觉全身流汗 曾经的救治情况和效果:以前吃过奇星虚汗停在乎怎样的协助:您好用什么药\n医生:","发烫主要考量是细菌或病毒感染,或者是支原体感染,致使再次出现的情况,最好化验几下血常规,同时实施支原体的化验仔细检查,实施明确确诊,主要是运用许多抗炎抗病毒的药物,如果是支原体感染,主要是运用许多红霉素类的抗菌药物实施调养救治。以上是对“小孩白天晚上睡午觉全身流汗”这个问题的建议,期望对您有协助,祝您健康!","[]","medical_qa" 227 | "病人: 228 | 最近不知道怎么回事,消化一直不怎好,吃东西很久也不消化而且还有胀气,吃了要没有什么明显效果,每天都特难受,请问肚子很闷是什么原因\n医生:","你的这种情况可能是消化不良,建议不要吃油腻之品,可以用保和丸加减治疗,或用萝卜籽炒熟后去壳煎服,效果比较好。,这种情况可能是脾胃虚弱,主要表现在胃胀,胃痛,呃逆,食少,饭后胀满,可以用香砂六君丸调理,有一定效果,饮食宜清淡,不能吃辛辣之品","[]","medical_qa" 229 | "病人:我的孩子9岁了,这两天不知晓怎么回事晚上来尿都不知晓下来,前几天晚上还下来三到四遍,请医生帮我解惑几下 \n医生:","根据你讲述的这种情况,孩子晚上尿不知晓下来的问题,可能会是过度操劳引发的。你这种情况,首先要让孩子充分的歇息,不要过度的运动,到时间排尿的时候及时喊醒。以上是对“我的孩子9岁了,这两天不知晓怎么回事晚上来尿都不知”这个问题的建议,期望对您有帮助,祝您健康!","[]","medical_qa" 230 | "病人:病情描述:专家: 231 | 您好!我女儿11岁,身高157厘米,体重88斤。近日连续两次出现早晨起床头晕、恶心、胸闷、气短,在顺义区医院查心电图、血均正常,血压50—80,请问她是什么病?应去哪家医院诊治?谢谢!!第一次问题补充:低血压低怎么办\n医生:","病情分析:你好:试试下面的饮食看一下:一、乌骨鸡1只(约重1500克)。将鸡去毛剖肚洗净,放人鸡腹肚中当归头60克,黄芪50克,红糖150克,米酒50克,再将鸡肚皮缝紧,入锅隔水蒸熟,吃肉喝汤,每半月吃一次,连吃两月。 232 | 二、红枣15枚去核,粟子150克,净鸡1只,鸡切成块状,大火煸炒,后加佐料,煮至八成熟,加红枣、栗子焖熟食之。 233 | 三、鲫鱼1条,糯米60克。将鱼洗净(不要去鳞)与糯米共煮成粥,每周用2次,连服两月。 234 | 四、嫩母鸡1只,黄芪30克,新鲜天麻100克(干品15克)。鸡洗净入沸水中焯一下,用凉水冲洗。将天麻、黄芪切片装入鸡肚内。将鸡放于沙锅中,加葱、姜适量,盐、酒、陈皮15克,水适量,用文火炖至鸡烂熟,加胡椒粉2克,即可食用。 235 | 五、猪心1个,黄芪20克,当归12克,党参30克,川芎6克,加水炖熟,吃猪心喝汤。 236 | 六、红枣20克,沙参15克,生熟地各10克,加水适量用炖盅隔水蒸3小时后,加蜂蜜适量每日分两次吃完,连服15天。 237 | 七、韭菜适量,捣烂取汁,每日早晨服1杯,常服用,可使血压恢复正常。 238 | 八、当归、黄芪、红枣各50克,鸡蛋4只同煮熟,吃蛋喝汤,每日早晚各1次,空腹吃。","[]","medical_qa" 239 | -------------------------------------------------------------------------------- /figure/coq.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scutcyr/BianQue/38c5b3b15df68de375e8bab5394e0a3734336483/figure/coq.png -------------------------------------------------------------------------------- /figure/dataset_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scutcyr/BianQue/38c5b3b15df68de375e8bab5394e0a3734336483/figure/dataset_example.png -------------------------------------------------------------------------------- /figure/example_multi_turn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scutcyr/BianQue/38c5b3b15df68de375e8bab5394e0a3734336483/figure/example_multi_turn.png -------------------------------------------------------------------------------- /figure/example_test1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scutcyr/BianQue/38c5b3b15df68de375e8bab5394e0a3734336483/figure/example_test1.png -------------------------------------------------------------------------------- /figure/example_test2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scutcyr/BianQue/38c5b3b15df68de375e8bab5394e0a3734336483/figure/example_test2.png -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 Research Center of Body Data Science from South China University of Technology. All rights reserved. 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | __version__ = "1.0.0" 17 | 18 | # 关键包版本说明: 19 | # pytorch: 1.9.0+ 20 | # transformers: 4.11.3 21 | 22 | from transformers.utils import ( 23 | is_torch_available, 24 | ) 25 | 26 | # 模型类 27 | if is_torch_available(): 28 | from . import ( 29 | t5 30 | ) 31 | -------------------------------------------------------------------------------- /models/t5/__init__.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | # There's no way to ignore "F401 '...' imported but unused" warnings in this 3 | # module, but to preserve other warnings. So, don't check this module at all. 4 | 5 | # Copyright 2020 The HuggingFace Team. All rights reserved. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | 19 | from typing import TYPE_CHECKING 20 | 21 | from .tokenization_t5 import T5Tokenizer 22 | 23 | from .modeling_t5 import ( 24 | T5_PRETRAINED_MODEL_ARCHIVE_LIST, 25 | T5EncoderModel, 26 | T5ForConditionalGeneration, 27 | T5Model, 28 | T5PreTrainedModel, 29 | load_tf_weights_in_t5, 30 | ) 31 | -------------------------------------------------------------------------------- /models/t5/configuration_t5.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2020, The T5 Authors and HuggingFace Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """ T5 model configuration""" 16 | from typing import Mapping 17 | 18 | from transformers.configuration_utils import PretrainedConfig 19 | from transformers.onnx import OnnxSeq2SeqConfigWithPast 20 | from transformers.utils import logging 21 | 22 | 23 | logger = logging.get_logger(__name__) 24 | 25 | T5_PRETRAINED_CONFIG_ARCHIVE_MAP = { 26 | "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json", 27 | "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json", 28 | "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json", 29 | "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json", 30 | "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json", 31 | } 32 | 33 | 34 | class T5Config(PretrainedConfig): 35 | r""" 36 | This is the configuration class to store the configuration of a [`T5Model`] or a [`TFT5Model`]. It is used to 37 | instantiate a T5 model according to the specified arguments, defining the model architecture. Instantiating a 38 | configuration with the defaults will yield a similar configuration to that of the T5 39 | [t5-small](https://huggingface.co/t5-small) architecture. 40 | 41 | Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the 42 | documentation from [`PretrainedConfig`] for more information. 43 | 44 | Arguments: 45 | vocab_size (`int`, *optional*, defaults to 32128): 46 | Vocabulary size of the T5 model. Defines the number of different tokens that can be represented by the 47 | `inputs_ids` passed when calling [`T5Model`] or [`TFT5Model`]. 48 | d_model (`int`, *optional*, defaults to 512): 49 | Size of the encoder layers and the pooler layer. 50 | d_kv (`int`, *optional*, defaults to 64): 51 | Size of the key, query, value projections per attention head. `d_kv` has to be equal to `d_model // 52 | num_heads`. 53 | d_ff (`int`, *optional*, defaults to 2048): 54 | Size of the intermediate feed forward layer in each `T5Block`. 55 | num_layers (`int`, *optional*, defaults to 6): 56 | Number of hidden layers in the Transformer encoder. 57 | num_decoder_layers (`int`, *optional*): 58 | Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set. 59 | num_heads (`int`, *optional*, defaults to 8): 60 | Number of attention heads for each attention layer in the Transformer encoder. 61 | relative_attention_num_buckets (`int`, *optional*, defaults to 32): 62 | The number of buckets to use for each attention layer. 63 | relative_attention_max_distance (`int`, *optional*, defaults to 128): 64 | The maximum distance of the longer sequences for the bucket separation. 65 | dropout_rate (`float`, *optional*, defaults to 0.1): 66 | The ratio for all dropout layers. 67 | layer_norm_eps (`float`, *optional*, defaults to 1e-6): 68 | The epsilon used by the layer normalization layers. 69 | initializer_factor (`float`, *optional*, defaults to 1): 70 | A factor for initializing all weight matrices (should be kept to 1, used internally for initialization 71 | testing). 72 | feed_forward_proj (`string`, *optional*, defaults to `"relu"`): 73 | Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. T5v1.1 uses the 74 | `"gated-gelu"` feed forward projection. Original T5 uses `"relu"`. 75 | use_cache (`bool`, *optional*, defaults to `True`): 76 | Whether or not the model should return the last key/values attentions (not used by all models). 77 | """ 78 | model_type = "t5" 79 | keys_to_ignore_at_inference = ["past_key_values"] 80 | attribute_map = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} 81 | 82 | def __init__( 83 | self, 84 | vocab_size=32128, 85 | d_model=512, 86 | d_kv=64, 87 | d_ff=2048, 88 | num_layers=6, 89 | num_decoder_layers=None, 90 | num_heads=8, 91 | relative_attention_num_buckets=32, 92 | relative_attention_max_distance=128, 93 | dropout_rate=0.1, 94 | layer_norm_epsilon=1e-6, 95 | initializer_factor=1.0, 96 | feed_forward_proj="relu", 97 | is_encoder_decoder=True, 98 | use_cache=True, 99 | pad_token_id=0, 100 | eos_token_id=1, 101 | **kwargs 102 | ): 103 | self.vocab_size = vocab_size 104 | self.d_model = d_model 105 | self.d_kv = d_kv 106 | self.d_ff = d_ff 107 | self.num_layers = num_layers 108 | self.num_decoder_layers = ( 109 | num_decoder_layers if num_decoder_layers is not None else self.num_layers 110 | ) # default = symmetry 111 | self.num_heads = num_heads 112 | self.relative_attention_num_buckets = relative_attention_num_buckets 113 | self.relative_attention_max_distance = relative_attention_max_distance 114 | self.dropout_rate = dropout_rate 115 | self.layer_norm_epsilon = layer_norm_epsilon 116 | self.initializer_factor = initializer_factor 117 | self.feed_forward_proj = feed_forward_proj 118 | self.use_cache = use_cache 119 | 120 | act_info = self.feed_forward_proj.split("-") 121 | self.dense_act_fn = act_info[-1] 122 | self.is_gated_act = act_info[0] == "gated" 123 | 124 | if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2: 125 | raise ValueError( 126 | f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer." 127 | "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " 128 | "'gated-gelu' or 'relu'" 129 | ) 130 | 131 | # for backwards compatibility 132 | if feed_forward_proj == "gated-gelu": 133 | self.dense_act_fn = "gelu_new" 134 | 135 | super().__init__( 136 | pad_token_id=pad_token_id, 137 | eos_token_id=eos_token_id, 138 | is_encoder_decoder=is_encoder_decoder, 139 | **kwargs, 140 | ) 141 | 142 | 143 | class T5OnnxConfig(OnnxSeq2SeqConfigWithPast): 144 | @property 145 | def inputs(self) -> Mapping[str, Mapping[int, str]]: 146 | common_inputs = { 147 | "input_ids": {0: "batch", 1: "encoder_sequence"}, 148 | "attention_mask": {0: "batch", 1: "encoder_sequence"}, 149 | } 150 | if self.use_past: 151 | common_inputs["attention_mask"][1] = "past_encoder_sequence + sequence" 152 | common_inputs["decoder_input_ids"] = {0: "batch"} 153 | common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"} 154 | else: 155 | common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"} 156 | common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"} 157 | 158 | if self.use_past: 159 | self.fill_with_past_key_values_(common_inputs, direction="inputs") 160 | 161 | return common_inputs 162 | 163 | @property 164 | def default_onnx_opset(self) -> int: 165 | return 13 166 | -------------------------------------------------------------------------------- /models/t5/tokenization_t5.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 T5 Authors and HuggingFace Inc. team. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """ Tokenization class for model T5.""" 16 | 17 | 18 | import os 19 | import re 20 | import warnings 21 | from shutil import copyfile 22 | from typing import Any, Dict, List, Optional, Tuple 23 | 24 | import sentencepiece as spm 25 | 26 | from transformers.tokenization_utils import PreTrainedTokenizer 27 | from transformers.utils import logging 28 | 29 | 30 | logger = logging.get_logger(__name__) 31 | 32 | VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"} 33 | 34 | PRETRAINED_VOCAB_FILES_MAP = { 35 | "vocab_file": { 36 | "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model", 37 | "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model", 38 | "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model", 39 | "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model", 40 | "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model", 41 | } 42 | } 43 | 44 | 45 | # TODO(PVP) - this should be removed in Transformers v5 46 | PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { 47 | "t5-small": 512, 48 | "t5-base": 512, 49 | "t5-large": 512, 50 | "t5-3b": 512, 51 | "t5-11b": 512, 52 | } 53 | 54 | 55 | class T5Tokenizer(PreTrainedTokenizer): 56 | """ 57 | Construct a T5 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece). 58 | 59 | This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to 60 | this superclass for more information regarding those methods. 61 | 62 | Args: 63 | vocab_file (`str`): 64 | [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that 65 | contains the vocabulary necessary to instantiate a tokenizer. 66 | eos_token (`str`, *optional*, defaults to `""`): 67 | The end of sequence token. 68 | 69 | 70 | 71 | When building a sequence using special tokens, this is not the token that is used for the end of sequence. 72 | The token used is the `sep_token`. 73 | 74 | 75 | 76 | unk_token (`str`, *optional*, defaults to `""`): 77 | The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this 78 | token instead. 79 | pad_token (`str`, *optional*, defaults to `""`): 80 | The token used for padding, for example when batching sequences of different lengths. 81 | extra_ids (`int`, *optional*, defaults to 100): 82 | Add a number of extra ids added to the vocabulary for use as sentinels. These tokens are 83 | accessible as "" where "{%d}" is a number between 0 and extra_ids-1. These tokens can be 84 | retrieved by calling get_sentinel_tokens method and token ids can be by calling get_sentinel_token_ids 85 | method 86 | additional_special_tokens (`List[str]`, *optional*): 87 | Additional special tokens used by the tokenizer. 88 | sp_model_kwargs (`dict`, *optional*): 89 | Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for 90 | SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things, 91 | to set: 92 | 93 | - `enable_sampling`: Enable subword regularization. 94 | - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout. 95 | 96 | - `nbest_size = {0,1}`: No sampling is performed. 97 | - `nbest_size > 1`: samples from the nbest_size results. 98 | - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) 99 | using forward-filtering-and-backward-sampling algorithm. 100 | 101 | - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for 102 | BPE-dropout. 103 | 104 | Attributes: 105 | sp_model (`SentencePieceProcessor`): 106 | The *SentencePiece* processor that is used for every conversion (string, tokens and IDs). 107 | """ 108 | 109 | vocab_files_names = VOCAB_FILES_NAMES 110 | pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP 111 | max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES 112 | model_input_names = ["input_ids", "attention_mask"] 113 | 114 | def __init__( 115 | self, 116 | vocab_file, 117 | eos_token="", 118 | unk_token="", 119 | pad_token="", 120 | extra_ids=100, 121 | additional_special_tokens=None, 122 | sp_model_kwargs: Optional[Dict[str, Any]] = None, 123 | **kwargs 124 | ) -> None: 125 | # Add extra_ids to the special token list 126 | if extra_ids > 0 and additional_special_tokens is None: 127 | additional_special_tokens = [f"" for i in range(extra_ids)] 128 | elif extra_ids > 0 and additional_special_tokens is not None: 129 | # Check that we have the right number of extra_id special tokens 130 | extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens))) 131 | if extra_tokens != extra_ids: 132 | raise ValueError( 133 | f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" 134 | " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids" 135 | " tokens" 136 | ) 137 | 138 | self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs 139 | 140 | super().__init__( 141 | eos_token=eos_token, 142 | unk_token=unk_token, 143 | pad_token=pad_token, 144 | extra_ids=extra_ids, 145 | additional_special_tokens=additional_special_tokens, 146 | sp_model_kwargs=self.sp_model_kwargs, 147 | **kwargs, 148 | ) 149 | 150 | self.vocab_file = vocab_file 151 | self._extra_ids = extra_ids 152 | 153 | self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) 154 | self.sp_model.Load(vocab_file) 155 | 156 | @staticmethod 157 | def _eventually_correct_t5_max_length(pretrained_model_name_or_path, max_model_length, init_max_model_length): 158 | if pretrained_model_name_or_path in T5Tokenizer.max_model_input_sizes: 159 | deprecated_max_model_length = T5Tokenizer.max_model_input_sizes[pretrained_model_name_or_path] 160 | if init_max_model_length is not None and init_max_model_length != max_model_length: 161 | return init_max_model_length 162 | elif init_max_model_length is None: 163 | warnings.warn( 164 | "This tokenizer was incorrectly instantiated with a model max length of" 165 | f" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this" 166 | " behavior is kept to avoid breaking backwards compatibility when padding/encoding with" 167 | " `truncation is True`.\n- Be aware that you SHOULD NOT rely on" 168 | f" {pretrained_model_name_or_path} automatically truncating your input to" 169 | f" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences" 170 | f" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with" 171 | " `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please" 172 | " instantiate this tokenizer with `model_max_length` set to your preferred value.", 173 | FutureWarning, 174 | ) 175 | 176 | return max_model_length 177 | 178 | @property 179 | def vocab_size(self): 180 | return self.sp_model.get_piece_size() + self._extra_ids 181 | 182 | def get_vocab(self): 183 | vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} 184 | vocab.update(self.added_tokens_encoder) 185 | return vocab 186 | 187 | def get_special_tokens_mask( 188 | self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False 189 | ) -> List[int]: 190 | """ 191 | Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding 192 | special tokens using the tokenizer `prepare_for_model` method. 193 | 194 | Args: 195 | token_ids_0 (`List[int]`): 196 | List of IDs. 197 | token_ids_1 (`List[int]`, *optional*): 198 | Optional second list of IDs for sequence pairs. 199 | already_has_special_tokens (`bool`, *optional*, defaults to `False`): 200 | Whether or not the token list is already formatted with special tokens for the model. 201 | 202 | Returns: 203 | `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. 204 | """ 205 | if already_has_special_tokens: 206 | return super().get_special_tokens_mask( 207 | token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True 208 | ) 209 | 210 | # normal case: some special tokens 211 | if token_ids_1 is None: 212 | return ([0] * len(token_ids_0)) + [1] 213 | return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1] 214 | 215 | def get_sentinel_tokens(self): 216 | return list( 217 | set(filter(lambda x: bool(re.search(r"", x)) is not None, self.additional_special_tokens)) 218 | ) 219 | 220 | def get_sentinel_token_ids(self): 221 | return [self._convert_token_to_id(token) for token in self.get_sentinel_tokens()] 222 | 223 | def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]: 224 | """Do not add eos again if user already added it.""" 225 | if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id: 226 | warnings.warn( 227 | f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated" 228 | " eos tokens being added." 229 | ) 230 | return token_ids 231 | else: 232 | return token_ids + [self.eos_token_id] 233 | 234 | def create_token_type_ids_from_sequences( 235 | self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None 236 | ) -> List[int]: 237 | """ 238 | Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make 239 | use of token type ids, therefore a list of zeros is returned. 240 | 241 | Args: 242 | token_ids_0 (`List[int]`): 243 | List of IDs. 244 | token_ids_1 (`List[int]`, *optional*): 245 | Optional second list of IDs for sequence pairs. 246 | 247 | Returns: 248 | `List[int]`: List of zeros. 249 | """ 250 | eos = [self.eos_token_id] 251 | 252 | if token_ids_1 is None: 253 | return len(token_ids_0 + eos) * [0] 254 | return len(token_ids_0 + eos + token_ids_1 + eos) * [0] 255 | 256 | def build_inputs_with_special_tokens( 257 | self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None 258 | ) -> List[int]: 259 | """ 260 | Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and 261 | adding special tokens. A sequence has the following format: 262 | 263 | - single sequence: `X ` 264 | - pair of sequences: `A B ` 265 | 266 | Args: 267 | token_ids_0 (`List[int]`): 268 | List of IDs to which the special tokens will be added. 269 | token_ids_1 (`List[int]`, *optional*): 270 | Optional second list of IDs for sequence pairs. 271 | 272 | Returns: 273 | `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens. 274 | """ 275 | token_ids_0 = self._add_eos_if_not_present(token_ids_0) 276 | if token_ids_1 is None: 277 | return token_ids_0 278 | else: 279 | token_ids_1 = self._add_eos_if_not_present(token_ids_1) 280 | return token_ids_0 + token_ids_1 281 | 282 | def __getstate__(self): 283 | state = self.__dict__.copy() 284 | state["sp_model"] = None 285 | return state 286 | 287 | def __setstate__(self, d): 288 | self.__dict__ = d 289 | 290 | # for backward compatibility 291 | if not hasattr(self, "sp_model_kwargs"): 292 | self.sp_model_kwargs = {} 293 | 294 | self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) 295 | self.sp_model.Load(self.vocab_file) 296 | 297 | def _tokenize(self, text: str) -> List[str]: 298 | """Take as input a string and return a list of strings (tokens) for words/sub-words""" 299 | return self.sp_model.encode(text, out_type=str) 300 | 301 | def _convert_token_to_id(self, token): 302 | """Converts a token (str) in an id using the vocab.""" 303 | if token.startswith("", token) 305 | num = int(match.group(1)) 306 | return self.vocab_size - num - 1 307 | return self.sp_model.piece_to_id(token) 308 | 309 | def _convert_id_to_token(self, index): 310 | """Converts an index (integer) in a token (str) using the vocab.""" 311 | if index < self.sp_model.get_piece_size(): 312 | token = self.sp_model.IdToPiece(index) 313 | else: 314 | token = f"" 315 | return token 316 | 317 | def convert_tokens_to_string(self, tokens): 318 | """Converts a sequence of tokens (string) in a single string.""" 319 | current_sub_tokens = [] 320 | out_string = "" 321 | prev_is_special = False 322 | for token in tokens: 323 | # make sure that special tokens are not decoded using sentencepiece model 324 | if token in self.all_special_tokens: 325 | if not prev_is_special: 326 | out_string += " " 327 | out_string += self.sp_model.decode(current_sub_tokens) + token 328 | prev_is_special = True 329 | current_sub_tokens = [] 330 | else: 331 | current_sub_tokens.append(token) 332 | prev_is_special = False 333 | out_string += self.sp_model.decode(current_sub_tokens) 334 | return out_string.strip() 335 | 336 | def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: 337 | if not os.path.isdir(save_directory): 338 | logger.error(f"Vocabulary path ({save_directory}) should be a directory") 339 | return 340 | out_vocab_file = os.path.join( 341 | save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] 342 | ) 343 | 344 | if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): 345 | copyfile(self.vocab_file, out_vocab_file) 346 | elif not os.path.isfile(self.vocab_file): 347 | with open(out_vocab_file, "wb") as fi: 348 | content_spiece_model = self.sp_model.serialized_model_proto() 349 | fi.write(content_spiece_model) 350 | 351 | return (out_vocab_file,) 352 | -------------------------------------------------------------------------------- /proactivehealthgpt_py38.yml: -------------------------------------------------------------------------------- 1 | name: proactivehealthgpt_py38 2 | channels: 3 | - defaults 4 | dependencies: 5 | - _libgcc_mutex=0.1=main 6 | - _openmp_mutex=5.1=1_gnu 7 | - argon2-cffi=21.3.0=pyhd3eb1b0_0 8 | - argon2-cffi-bindings=21.2.0=py38h7f8727e_0 9 | - asttokens=2.0.5=pyhd3eb1b0_0 10 | - babel=2.11.0=py38h06a4308_0 11 | - backcall=0.2.0=pyhd3eb1b0_0 12 | - beautifulsoup4=4.12.0=py38h06a4308_0 13 | - bleach=4.1.0=pyhd3eb1b0_0 14 | - brotlipy=0.7.0=py38h27cfd23_1003 15 | - ca-certificates=2023.01.10=h06a4308_0 16 | - certifi=2022.12.7=py38h06a4308_0 17 | - cffi=1.15.1=py38h5eee18b_3 18 | - comm=0.1.2=py38h06a4308_0 19 | - dbus=1.13.18=hb2f20db_0 20 | - debugpy=1.5.1=py38h295c915_0 21 | - decorator=5.1.1=pyhd3eb1b0_0 22 | - defusedxml=0.7.1=pyhd3eb1b0_0 23 | - entrypoints=0.4=py38h06a4308_0 24 | - executing=0.8.3=pyhd3eb1b0_0 25 | - expat=2.4.9=h6a678d5_0 26 | - flit-core=3.8.0=py38h06a4308_0 27 | - fontconfig=2.14.1=h4c34cd2_2 28 | - freetype=2.12.1=h4a9f257_0 29 | - giflib=5.2.1=h5eee18b_3 30 | - glib=2.69.1=he621ea3_2 31 | - gst-plugins-base=1.14.1=h6a678d5_1 32 | - gstreamer=1.14.1=h5eee18b_1 33 | - icu=58.2=he6710b0_3 34 | - idna=3.4=py38h06a4308_0 35 | - importlib_metadata=6.0.0=hd3eb1b0_0 36 | - importlib_resources=5.2.0=pyhd3eb1b0_1 37 | - ipykernel=6.19.2=py38hb070fc8_0 38 | - ipython=8.12.0=py38h06a4308_0 39 | - ipython_genutils=0.2.0=pyhd3eb1b0_1 40 | - ipywidgets=8.0.4=py38h06a4308_0 41 | - jedi=0.18.1=py38h06a4308_1 42 | - jinja2=3.1.2=py38h06a4308_0 43 | - jpeg=9e=h5eee18b_1 44 | - json5=0.9.6=pyhd3eb1b0_0 45 | - jsonschema=4.17.3=py38h06a4308_0 46 | - jupyter=1.0.0=py38h06a4308_8 47 | - jupyter_client=8.1.0=py38h06a4308_0 48 | - jupyter_console=6.6.3=py38h06a4308_0 49 | - jupyter_core=5.3.0=py38h06a4308_0 50 | - jupyter_server=1.23.4=py38h06a4308_0 51 | - jupyterlab=3.5.3=py38h06a4308_0 52 | - jupyterlab_pygments=0.1.2=py_0 53 | - jupyterlab_server=2.22.0=py38h06a4308_0 54 | - jupyterlab_widgets=3.0.5=py38h06a4308_0 55 | - krb5=1.19.4=h568e23c_0 56 | - ld_impl_linux-64=2.38=h1181459_1 57 | - lerc=3.0=h295c915_0 58 | - libclang=14.0.6=default_hc6dbbc7_1 59 | - libclang13=14.0.6=default_he11475f_1 60 | - libdeflate=1.17=h5eee18b_0 61 | - libedit=3.1.20221030=h5eee18b_0 62 | - libevent=2.1.12=h8f2d780_0 63 | - libffi=3.4.2=h6a678d5_6 64 | - libgcc-ng=11.2.0=h1234567_1 65 | - libgomp=11.2.0=h1234567_1 66 | - libllvm14=14.0.6=hdb19cb5_2 67 | - libpng=1.6.39=h5eee18b_0 68 | - libpq=12.9=h16c4e8d_3 69 | - libsodium=1.0.18=h7b6447c_0 70 | - libstdcxx-ng=11.2.0=h1234567_1 71 | - libtiff=4.5.0=h6a678d5_2 72 | - libuuid=1.41.5=h5eee18b_0 73 | - libwebp=1.2.4=h11a3e52_1 74 | - libwebp-base=1.2.4=h5eee18b_1 75 | - libxcb=1.15=h7f8727e_0 76 | - libxkbcommon=1.0.1=h5eee18b_1 77 | - libxml2=2.10.3=hcbfbd50_0 78 | - libxslt=1.1.37=h2085143_0 79 | - lxml=4.9.2=py38h5eee18b_0 80 | - lz4-c=1.9.4=h6a678d5_0 81 | - matplotlib-inline=0.1.6=py38h06a4308_0 82 | - mistune=0.8.4=py38h7b6447c_1000 83 | - nbclassic=0.5.4=py38h06a4308_0 84 | - nbclient=0.5.13=py38h06a4308_0 85 | - nbconvert=6.5.4=py38h06a4308_0 86 | - nbformat=5.7.0=py38h06a4308_0 87 | - ncurses=6.4=h6a678d5_0 88 | - nest-asyncio=1.5.6=py38h06a4308_0 89 | - notebook=6.5.3=py38h06a4308_0 90 | - notebook-shim=0.2.2=py38h06a4308_0 91 | - nspr=4.33=h295c915_0 92 | - nss=3.74=h0370c37_0 93 | - openssl=1.1.1t=h7f8727e_0 94 | - packaging=23.0=py38h06a4308_0 95 | - pandocfilters=1.5.0=pyhd3eb1b0_0 96 | - parso=0.8.3=pyhd3eb1b0_0 97 | - pcre=8.45=h295c915_0 98 | - pexpect=4.8.0=pyhd3eb1b0_3 99 | - pickleshare=0.7.5=pyhd3eb1b0_1003 100 | - pip=23.0.1=py38h06a4308_0 101 | - pkgutil-resolve-name=1.3.10=py38h06a4308_0 102 | - ply=3.11=py38_0 103 | - prometheus_client=0.14.1=py38h06a4308_0 104 | - prompt-toolkit=3.0.36=py38h06a4308_0 105 | - prompt_toolkit=3.0.36=hd3eb1b0_0 106 | - ptyprocess=0.7.0=pyhd3eb1b0_2 107 | - pure_eval=0.2.2=pyhd3eb1b0_0 108 | - pycparser=2.21=pyhd3eb1b0_0 109 | - pyopenssl=23.0.0=py38h06a4308_0 110 | - pyqt=5.15.7=py38h6a678d5_1 111 | - pyqt5-sip=12.11.0=py38h6a678d5_1 112 | - pysocks=1.7.1=py38h06a4308_0 113 | - python=3.8.16=h7a1cb2a_3 114 | - python-dateutil=2.8.2=pyhd3eb1b0_0 115 | - python-fastjsonschema=2.16.2=py38h06a4308_0 116 | - pyzmq=23.2.0=py38h6a678d5_0 117 | - qt-main=5.15.2=h8373d8f_8 118 | - qt-webengine=5.15.9=hbbf29b9_6 119 | - qtconsole=5.4.2=py38h06a4308_0 120 | - qtpy=2.2.0=py38h06a4308_0 121 | - qtwebkit=5.212=h3fafdc1_5 122 | - readline=8.2=h5eee18b_0 123 | - send2trash=1.8.0=pyhd3eb1b0_1 124 | - setuptools=65.6.3=py38h06a4308_0 125 | - sip=6.6.2=py38h6a678d5_0 126 | - six=1.16.0=pyhd3eb1b0_1 127 | - soupsieve=2.4=py38h06a4308_0 128 | - sqlite=3.41.1=h5eee18b_0 129 | - stack_data=0.2.0=pyhd3eb1b0_0 130 | - terminado=0.17.1=py38h06a4308_0 131 | - tinycss2=1.2.1=py38h06a4308_0 132 | - tk=8.6.12=h1ccaba5_0 133 | - toml=0.10.2=pyhd3eb1b0_0 134 | - tomli=2.0.1=py38h06a4308_0 135 | - tornado=6.2=py38h5eee18b_0 136 | - traitlets=5.7.1=py38h06a4308_0 137 | - typing_extensions=4.4.0=py38h06a4308_0 138 | - urllib3=1.26.15=py38h06a4308_0 139 | - webencodings=0.5.1=py38_1 140 | - websocket-client=0.58.0=py38h06a4308_4 141 | - wheel=0.38.4=py38h06a4308_0 142 | - widgetsnbextension=4.0.5=py38h06a4308_0 143 | - xz=5.2.10=h5eee18b_1 144 | - zeromq=4.3.4=h2531618_0 145 | - zlib=1.2.13=h5eee18b_0 146 | - zstd=1.5.5=hc292b87_0 147 | - pip: 148 | - absl-py==1.4.0 149 | - accelerate==0.18.0 150 | - aiohttp==3.8.4 151 | - aiosignal==1.3.1 152 | - altair==4.2.2 153 | - anyio==3.6.2 154 | - appdirs==1.4.4 155 | - async-timeout==4.0.2 156 | - attrs==22.2.0 157 | - backports-zoneinfo==0.2.1 158 | - bcrypt==4.0.1 159 | - blessed==1.20.0 160 | - blinker==1.6 161 | - cachetools==5.3.0 162 | - cfgv==3.3.1 163 | - chardet==5.1.0 164 | - charset-normalizer==3.1.0 165 | - click==8.1.3 166 | - colossalai==0.2.8 167 | - contexttimer==0.3.3 168 | - cryptography==40.0.1 169 | - dataclasses-json==0.5.7 170 | - datasets==2.11.0 171 | - deepspeed==0.9.0 172 | - dill==0.3.6 173 | - distlib==0.3.6 174 | - docker-pycreds==0.4.0 175 | - fabric==3.0.0 176 | - fastapi==0.95.0 177 | - filelock==3.10.7 178 | - frozenlist==1.3.3 179 | - fsspec==2023.3.0 180 | - gitdb==4.0.10 181 | - gitpython==3.1.31 182 | - google-auth==2.17.2 183 | - google-auth-oauthlib==1.0.0 184 | - gpustat==1.0.0 185 | - greenlet==2.0.2 186 | - grpcio==1.53.0 187 | - hjson==3.1.0 188 | - huggingface-hub==0.13.3 189 | - identify==2.5.22 190 | - importlib-metadata==6.1.0 191 | - importlib-resources==5.12.0 192 | - invoke==2.0.0 193 | - langchain==0.0.127 194 | - loralib==0.1.1 195 | - markdown==3.4.3 196 | - markdown-it-py==2.2.0 197 | - markupsafe==2.1.2 198 | - marshmallow==3.19.0 199 | - marshmallow-enum==1.5.1 200 | - mdurl==0.1.2 201 | - multidict==6.0.4 202 | - multiprocess==0.70.14 203 | - mypy-extensions==1.0.0 204 | - ninja==1.11.1 205 | - nodeenv==1.7.0 206 | - numpy==1.24.2 207 | - nvidia-ml-py==11.495.46 208 | - oauthlib==3.2.2 209 | - pandas==1.5.3 210 | - paramiko==3.1.0 211 | - pathtools==0.1.2 212 | - pillow==9.4.0 213 | - platformdirs==3.2.0 214 | - pre-commit==3.2.1 215 | - protobuf==3.20.3 216 | - psutil==5.9.4 217 | - py-cpuinfo==9.0.0 218 | - pyarrow==11.0.0 219 | - pyasn1==0.4.8 220 | - pyasn1-modules==0.2.8 221 | - pydantic==1.10.7 222 | - pydeck==0.8.0 223 | - pygments==2.14.0 224 | - pympler==1.0.1 225 | - pynacl==1.5.0 226 | - pyrsistent==0.19.3 227 | - pytz==2023.3 228 | - pytz-deprecation-shim==0.1.0.post0 229 | - pyyaml==6.0 230 | - regex==2023.3.23 231 | - requests==2.28.2 232 | - requests-oauthlib==1.3.1 233 | - responses==0.18.0 234 | - rich==13.3.3 235 | - rsa==4.9 236 | - sentencepiece==0.1.97 237 | - sentry-sdk==1.18.0 238 | - setproctitle==1.3.2 239 | - smmap==5.0.0 240 | - sniffio==1.3.0 241 | - sqlalchemy==1.4.47 242 | - sse-starlette==1.3.3 243 | - starlette==0.26.1 244 | - streamlit==1.21.0 245 | - streamlit-chat==0.0.2.2 246 | - tenacity==8.2.2 247 | - tensorboard==2.12.1 248 | - tensorboard-data-server==0.7.0 249 | - tensorboard-plugin-wit==1.8.1 250 | - tokenizers==0.13.2 251 | - toolz==0.12.0 252 | - torch==1.13.1 253 | - torchaudio==0.13.1 254 | - torchvision==0.14.1 255 | - tqdm==4.65.0 256 | - transformers==4.28.0 257 | - typing-extensions==4.5.0 258 | - typing-inspect==0.8.0 259 | - tzdata==2023.3 260 | - tzlocal==4.3 261 | - validators==0.20.0 262 | - virtualenv==20.21.0 263 | - wandb==0.14.0 264 | - watchdog==3.0.0 265 | - wcwidth==0.2.6 266 | - werkzeug==2.2.3 267 | - xxhash==3.2.0 268 | - yarl==1.8.2 269 | - zipp==3.15.0 270 | prefix: ~/anaconda3/envs/proactivehealthgpt_py38 271 | -------------------------------------------------------------------------------- /py38_conda_env.yml: -------------------------------------------------------------------------------- 1 | name: py38 2 | channels: 3 | - defaults 4 | dependencies: 5 | - _libgcc_mutex=0.1=main 6 | - _openmp_mutex=5.1=1_gnu 7 | - argon2-cffi=21.3.0=pyhd3eb1b0_0 8 | - argon2-cffi-bindings=21.2.0=py38h7f8727e_0 9 | - asttokens=2.0.5=pyhd3eb1b0_0 10 | - babel=2.11.0=py38h06a4308_0 11 | - backcall=0.2.0=pyhd3eb1b0_0 12 | - beautifulsoup4=4.12.0=py38h06a4308_0 13 | - bleach=4.1.0=pyhd3eb1b0_0 14 | - brotlipy=0.7.0=py38h27cfd23_1003 15 | - ca-certificates=2023.01.10=h06a4308_0 16 | - certifi=2022.12.7=py38h06a4308_0 17 | - cffi=1.15.1=py38h5eee18b_3 18 | - comm=0.1.2=py38h06a4308_0 19 | - dbus=1.13.18=hb2f20db_0 20 | - debugpy=1.5.1=py38h295c915_0 21 | - decorator=5.1.1=pyhd3eb1b0_0 22 | - defusedxml=0.7.1=pyhd3eb1b0_0 23 | - entrypoints=0.4=py38h06a4308_0 24 | - executing=0.8.3=pyhd3eb1b0_0 25 | - expat=2.4.9=h6a678d5_0 26 | - flit-core=3.8.0=py38h06a4308_0 27 | - fontconfig=2.14.1=h4c34cd2_2 28 | - freetype=2.12.1=h4a9f257_0 29 | - giflib=5.2.1=h5eee18b_3 30 | - glib=2.69.1=he621ea3_2 31 | - gst-plugins-base=1.14.1=h6a678d5_1 32 | - gstreamer=1.14.1=h5eee18b_1 33 | - icu=58.2=he6710b0_3 34 | - idna=3.4=py38h06a4308_0 35 | - importlib_metadata=6.0.0=hd3eb1b0_0 36 | - importlib_resources=5.2.0=pyhd3eb1b0_1 37 | - ipykernel=6.19.2=py38hb070fc8_0 38 | - ipython=8.12.0=py38h06a4308_0 39 | - ipython_genutils=0.2.0=pyhd3eb1b0_1 40 | - ipywidgets=8.0.4=py38h06a4308_0 41 | - jedi=0.18.1=py38h06a4308_1 42 | - jinja2=3.1.2=py38h06a4308_0 43 | - jpeg=9e=h5eee18b_1 44 | - json5=0.9.6=pyhd3eb1b0_0 45 | - jsonschema=4.17.3=py38h06a4308_0 46 | - jupyter=1.0.0=py38h06a4308_8 47 | - jupyter_client=8.1.0=py38h06a4308_0 48 | - jupyter_console=6.6.3=py38h06a4308_0 49 | - jupyter_core=5.3.0=py38h06a4308_0 50 | - jupyter_server=1.23.4=py38h06a4308_0 51 | - jupyterlab=3.5.3=py38h06a4308_0 52 | - jupyterlab_pygments=0.1.2=py_0 53 | - jupyterlab_server=2.22.0=py38h06a4308_0 54 | - jupyterlab_widgets=3.0.5=py38h06a4308_0 55 | - krb5=1.19.4=h568e23c_0 56 | - ld_impl_linux-64=2.38=h1181459_1 57 | - lerc=3.0=h295c915_0 58 | - libclang=14.0.6=default_hc6dbbc7_1 59 | - libclang13=14.0.6=default_he11475f_1 60 | - libdeflate=1.17=h5eee18b_0 61 | - libedit=3.1.20221030=h5eee18b_0 62 | - libevent=2.1.12=h8f2d780_0 63 | - libffi=3.4.2=h6a678d5_6 64 | - libgcc-ng=11.2.0=h1234567_1 65 | - libgomp=11.2.0=h1234567_1 66 | - libllvm14=14.0.6=hdb19cb5_2 67 | - libpng=1.6.39=h5eee18b_0 68 | - libpq=12.9=h16c4e8d_3 69 | - libsodium=1.0.18=h7b6447c_0 70 | - libstdcxx-ng=11.2.0=h1234567_1 71 | - libtiff=4.5.0=h6a678d5_2 72 | - libuuid=1.41.5=h5eee18b_0 73 | - libwebp=1.2.4=h11a3e52_1 74 | - libwebp-base=1.2.4=h5eee18b_1 75 | - libxcb=1.15=h7f8727e_0 76 | - libxkbcommon=1.0.1=h5eee18b_1 77 | - libxml2=2.10.3=hcbfbd50_0 78 | - libxslt=1.1.37=h2085143_0 79 | - lxml=4.9.2=py38h5eee18b_0 80 | - lz4-c=1.9.4=h6a678d5_0 81 | - matplotlib-inline=0.1.6=py38h06a4308_0 82 | - mistune=0.8.4=py38h7b6447c_1000 83 | - nbclassic=0.5.4=py38h06a4308_0 84 | - nbclient=0.5.13=py38h06a4308_0 85 | - nbconvert=6.5.4=py38h06a4308_0 86 | - nbformat=5.7.0=py38h06a4308_0 87 | - ncurses=6.4=h6a678d5_0 88 | - nest-asyncio=1.5.6=py38h06a4308_0 89 | - notebook=6.5.3=py38h06a4308_0 90 | - notebook-shim=0.2.2=py38h06a4308_0 91 | - nspr=4.33=h295c915_0 92 | - nss=3.74=h0370c37_0 93 | - openssl=1.1.1t=h7f8727e_0 94 | - packaging=23.0=py38h06a4308_0 95 | - pandocfilters=1.5.0=pyhd3eb1b0_0 96 | - parso=0.8.3=pyhd3eb1b0_0 97 | - pcre=8.45=h295c915_0 98 | - pexpect=4.8.0=pyhd3eb1b0_3 99 | - pickleshare=0.7.5=pyhd3eb1b0_1003 100 | - pip=23.0.1=py38h06a4308_0 101 | - pkgutil-resolve-name=1.3.10=py38h06a4308_0 102 | - ply=3.11=py38_0 103 | - prometheus_client=0.14.1=py38h06a4308_0 104 | - prompt-toolkit=3.0.36=py38h06a4308_0 105 | - prompt_toolkit=3.0.36=hd3eb1b0_0 106 | - ptyprocess=0.7.0=pyhd3eb1b0_2 107 | - pure_eval=0.2.2=pyhd3eb1b0_0 108 | - pycparser=2.21=pyhd3eb1b0_0 109 | - pyopenssl=23.0.0=py38h06a4308_0 110 | - pyqt=5.15.7=py38h6a678d5_1 111 | - pyqt5-sip=12.11.0=py38h6a678d5_1 112 | - pysocks=1.7.1=py38h06a4308_0 113 | - python=3.8.16=h7a1cb2a_3 114 | - python-dateutil=2.8.2=pyhd3eb1b0_0 115 | - python-fastjsonschema=2.16.2=py38h06a4308_0 116 | - pyzmq=23.2.0=py38h6a678d5_0 117 | - qt-main=5.15.2=h8373d8f_8 118 | - qt-webengine=5.15.9=hbbf29b9_6 119 | - qtconsole=5.4.2=py38h06a4308_0 120 | - qtpy=2.2.0=py38h06a4308_0 121 | - qtwebkit=5.212=h3fafdc1_5 122 | - readline=8.2=h5eee18b_0 123 | - send2trash=1.8.0=pyhd3eb1b0_1 124 | - setuptools=65.6.3=py38h06a4308_0 125 | - sip=6.6.2=py38h6a678d5_0 126 | - six=1.16.0=pyhd3eb1b0_1 127 | - soupsieve=2.4=py38h06a4308_0 128 | - sqlite=3.41.1=h5eee18b_0 129 | - stack_data=0.2.0=pyhd3eb1b0_0 130 | - terminado=0.17.1=py38h06a4308_0 131 | - tinycss2=1.2.1=py38h06a4308_0 132 | - tk=8.6.12=h1ccaba5_0 133 | - toml=0.10.2=pyhd3eb1b0_0 134 | - tomli=2.0.1=py38h06a4308_0 135 | - tornado=6.2=py38h5eee18b_0 136 | - traitlets=5.7.1=py38h06a4308_0 137 | - typing_extensions=4.4.0=py38h06a4308_0 138 | - urllib3=1.26.15=py38h06a4308_0 139 | - webencodings=0.5.1=py38_1 140 | - websocket-client=0.58.0=py38h06a4308_4 141 | - wheel=0.38.4=py38h06a4308_0 142 | - widgetsnbextension=4.0.5=py38h06a4308_0 143 | - xz=5.2.10=h5eee18b_1 144 | - zeromq=4.3.4=h2531618_0 145 | - zlib=1.2.13=h5eee18b_0 146 | - zstd=1.5.5=hc292b87_0 147 | - pip: 148 | - absl-py==1.4.0 149 | - accelerate==0.18.0 150 | - aiohttp==3.8.4 151 | - aiosignal==1.3.1 152 | - altair==4.2.2 153 | - anyio==3.6.2 154 | - appdirs==1.4.4 155 | - async-timeout==4.0.2 156 | - attrs==22.2.0 157 | - backports-zoneinfo==0.2.1 158 | - bcrypt==4.0.1 159 | - blessed==1.20.0 160 | - blinker==1.6 161 | - cachetools==5.3.0 162 | - cfgv==3.3.1 163 | - chardet==5.1.0 164 | - charset-normalizer==3.1.0 165 | - click==8.1.3 166 | - colossalai==0.2.8 167 | - contexttimer==0.3.3 168 | - cryptography==40.0.1 169 | - dataclasses-json==0.5.7 170 | - datasets==2.11.0 171 | - deepspeed==0.9.0 172 | - dill==0.3.6 173 | - distlib==0.3.6 174 | - docker-pycreds==0.4.0 175 | - fabric==3.0.0 176 | - fastapi==0.95.0 177 | - filelock==3.10.7 178 | - frozenlist==1.3.3 179 | - fsspec==2023.3.0 180 | - gitdb==4.0.10 181 | - gitpython==3.1.31 182 | - google-auth==2.17.2 183 | - google-auth-oauthlib==1.0.0 184 | - gpustat==1.0.0 185 | - greenlet==2.0.2 186 | - grpcio==1.53.0 187 | - hjson==3.1.0 188 | - huggingface-hub==0.13.3 189 | - identify==2.5.22 190 | - importlib-metadata==6.1.0 191 | - importlib-resources==5.12.0 192 | - invoke==2.0.0 193 | - langchain==0.0.127 194 | - loralib==0.1.1 195 | - markdown==3.4.3 196 | - markdown-it-py==2.2.0 197 | - markupsafe==2.1.2 198 | - marshmallow==3.19.0 199 | - marshmallow-enum==1.5.1 200 | - mdurl==0.1.2 201 | - multidict==6.0.4 202 | - multiprocess==0.70.14 203 | - mypy-extensions==1.0.0 204 | - ninja==1.11.1 205 | - nodeenv==1.7.0 206 | - numpy==1.24.2 207 | - nvidia-ml-py==11.495.46 208 | - oauthlib==3.2.2 209 | - pandas==1.5.3 210 | - paramiko==3.1.0 211 | - pathtools==0.1.2 212 | - pillow==9.4.0 213 | - platformdirs==3.2.0 214 | - pre-commit==3.2.1 215 | - protobuf==3.20.3 216 | - psutil==5.9.4 217 | - py-cpuinfo==9.0.0 218 | - pyarrow==11.0.0 219 | - pyasn1==0.4.8 220 | - pyasn1-modules==0.2.8 221 | - pydantic==1.10.7 222 | - pydeck==0.8.0 223 | - pygments==2.14.0 224 | - pympler==1.0.1 225 | - pynacl==1.5.0 226 | - pyrsistent==0.19.3 227 | - pytz==2023.3 228 | - pytz-deprecation-shim==0.1.0.post0 229 | - pyyaml==6.0 230 | - regex==2023.3.23 231 | - requests==2.28.2 232 | - requests-oauthlib==1.3.1 233 | - responses==0.18.0 234 | - rich==13.3.3 235 | - rsa==4.9 236 | - sentencepiece==0.1.97 237 | - sentry-sdk==1.18.0 238 | - setproctitle==1.3.2 239 | - smmap==5.0.0 240 | - sniffio==1.3.0 241 | - sqlalchemy==1.4.47 242 | - sse-starlette==1.3.3 243 | - starlette==0.26.1 244 | - streamlit==1.21.0 245 | - streamlit-chat==0.0.2.2 246 | - tenacity==8.2.2 247 | - tensorboard==2.12.1 248 | - tensorboard-data-server==0.7.0 249 | - tensorboard-plugin-wit==1.8.1 250 | - tokenizers==0.13.2 251 | - toolz==0.12.0 252 | - torch==1.13.1 253 | - torchaudio==0.13.1 254 | - torchvision==0.14.1 255 | - tqdm==4.65.0 256 | - transformers==4.28.0 257 | - typing-extensions==4.5.0 258 | - typing-inspect==0.8.0 259 | - tzdata==2023.3 260 | - tzlocal==4.3 261 | - validators==0.20.0 262 | - virtualenv==20.21.0 263 | - wandb==0.14.0 264 | - watchdog==3.0.0 265 | - wcwidth==0.2.6 266 | - werkzeug==2.2.3 267 | - xxhash==3.2.0 268 | - yarl==1.8.2 269 | - zipp==3.15.0 270 | prefix: ~/anaconda3/envs/py38 271 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | protobuf 2 | transformers==4.28.0 3 | cpm_kernels 4 | torch>=1.10 5 | gradio 6 | mdtex2html 7 | sentencepiece 8 | accelerate -------------------------------------------------------------------------------- /scripts/run_train_model_bianque.sh: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 Research Center of Body Data Science from South China University of Technology. All rights reserved. 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | # File: run_train_model_bianque.sh 17 | # Description: training model scripts 18 | # Repository: https://github.com/scutcyr 19 | # Mail: [eeyirongchen@mail.scut.edu.cn](mailto:eeyirongchen@mail.scut.edu.cn) 20 | # Date: 2023/03/15 21 | # Usage: 22 | # $ ./run_train_model_bianque.sh 23 | 24 | 25 | # 路径配置 26 | WORK_DIR="" 27 | PRETRAINED_MODEL="scutcyr/BianQue-1.0" 28 | 29 | # 指定csv格式数据集文件,其中csv文件当中input列为输入,target列为参考答案 30 | PREPROCESS_DATA="$WORK_DIR/data/cMedialog_example.csv" 31 | 32 | MODEL_TYPE=t5 33 | MODEL_COMMENT=20230407_0600 34 | 35 | # cd working path 36 | cd $WORK_DIR 37 | 38 | # 指定可以显卡,注意--nproc_per_node数目需要和这里的可用卡数一致 39 | export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 40 | 41 | # 混合精度训练:--autocast 42 | torchrun --nnodes=1 --nproc_per_node=8 --master_addr=127.0.0.1 --master_port=9903 train_model.py \ 43 | --model_type=t5 \ 44 | --model_name_or_path=$PRETRAINED_MODEL \ 45 | --data_path=$PREPROCESS_DATA \ 46 | --dataset_sample_frac=1 \ 47 | --train_radio_of_dataset=0.999 \ 48 | --dataset_input_column_name=input \ 49 | --dataset_target_column_name=target \ 50 | --max_source_text_length=512 \ 51 | --max_target_text_length=512 \ 52 | --output_dir=$WORK_DIR/runs/${MODEL_TYPE}_${MODEL_COMMENT} \ 53 | --seed=42 \ 54 | --save_optimizer_and_scheduler \ 55 | --per_gpu_train_batch_size=1 \ 56 | --per_gpu_eval_batch_size=1 \ 57 | --optimizer=AdamW \ 58 | --scheduler=get_constant_schedule \ 59 | --learning_rate=5e-5 \ 60 | --num_train_epochs=1 \ 61 | --save_total_limit=3 \ 62 | --gradient_accumulation_steps=4 \ 63 | --overwrite_output_dir \ 64 | --not_find_unused_parameters 65 | 66 | 67 | -------------------------------------------------------------------------------- /train_model.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 Research Center of Body Data Science from South China University of Technology. All rights reserved. 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | 17 | # File: train_model.py 18 | # Description: The training model code 19 | # Repository: https://github.com/scutcyr 20 | # Mail: [eeyirongchen@mail.scut.edu.cn](mailto:eeyirongchen@mail.scut.edu.cn) 21 | # Date: 2023/03/14 22 | 23 | 24 | import re 25 | import os 26 | import copy 27 | import json 28 | import glob 29 | import time 30 | import torch 31 | import random 32 | import logging 33 | import shutil 34 | import numpy as np 35 | import pandas as pd 36 | from pprint import pformat 37 | from tqdm import tqdm, trange 38 | from typing import Dict, List, Tuple 39 | 40 | from torch import nn 41 | import torch.nn.functional as F 42 | from torch.cuda.amp import autocast, GradScaler 43 | from torch.optim import AdamW as torch_AdamW 44 | from torch.nn.utils.rnn import pad_sequence 45 | from torch.utils.data.distributed import DistributedSampler 46 | from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler 47 | # 优化器 48 | from transformers.optimization import (AdamW, Adafactor) 49 | # 学习率模式 50 | from transformers.optimization import (get_linear_schedule_with_warmup, get_constant_schedule_with_warmup, 51 | get_constant_schedule, get_cosine_schedule_with_warmup, get_adafactor_schedule) 52 | 53 | # 导入数据类 54 | from utils import PromptDataSetClass 55 | from train_model_args import parser # 导入模型所需参数 56 | 57 | try: 58 | from torch.utils.tensorboard import SummaryWriter 59 | except ImportError: 60 | from tensorboardX import SummaryWriter 61 | 62 | logger = logging.getLogger(__file__) 63 | 64 | 65 | def setup_seed(seed, n_gpu): 66 | ''' 设置随机种子 ''' 67 | torch.manual_seed(seed) 68 | if n_gpu > 0: 69 | torch.cuda.manual_seed_all(seed) 70 | np.random.seed(seed) 71 | random.seed(seed) 72 | torch.backends.cudnn.deterministic = True 73 | 74 | 75 | def average_distributed_scalar(scalar, args): 76 | ''' Average a scalar over the nodes if we are in distributed training. We use this for distributed evaluation. ''' 77 | if args.local_rank == -1: 78 | return scalar 79 | scalar_t = torch.tensor(scalar, dtype=torch.float, device=args.device) / torch.distributed.get_world_size() 80 | torch.distributed.all_reduce(scalar_t, op=torch.distributed.ReduceOp.SUM) 81 | return scalar_t.item() 82 | 83 | 84 | def _sorted_checkpoints(args, checkpoint_prefix="checkpoint", use_mtime=False) -> List[str]: 85 | ''' 对所有的checkpoints进行排序 ''' 86 | ordering_and_checkpoint_path = [] 87 | glob_checkpoints = glob.glob(os.path.join(args.output_dir, "{}-*".format(checkpoint_prefix))) 88 | 89 | for path in glob_checkpoints: 90 | if use_mtime: 91 | ordering_and_checkpoint_path.append((os.path.getmtime(path), path)) 92 | else: 93 | regex_match = re.match(".*{}-([0-9]+)".format(checkpoint_prefix), path) 94 | if regex_match and regex_match.groups(): 95 | ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path)) 96 | 97 | checkpoints_sorted = sorted(ordering_and_checkpoint_path) 98 | checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted] 99 | return checkpoints_sorted 100 | 101 | 102 | def _rotate_checkpoints(args, checkpoint_prefix="checkpoint", use_mtime=False) -> None: 103 | ''' 删除多出的checkpoint ''' 104 | if not args.save_total_limit or args.save_total_limit <= 0: 105 | return 106 | # Check if we should delete older checkpoint(s) 107 | checkpoints_sorted = _sorted_checkpoints(args, checkpoint_prefix, use_mtime) 108 | if len(checkpoints_sorted) <= args.save_total_limit: 109 | return 110 | 111 | number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - args.save_total_limit) 112 | checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete] 113 | for checkpoint in checkpoints_to_be_deleted: 114 | logger.info("Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoint)) 115 | shutil.rmtree(checkpoint) 116 | 117 | 118 | def train(args, model, tokenizer, train_dataset, eval_dataset=None): 119 | ''' 120 | Training the model 121 | ''' 122 | logger.info("***** Preparing for training *****") 123 | if args.local_rank in [-1, 0]: 124 | os.makedirs(args.output_dir, exist_ok=True) 125 | tb_writer = SummaryWriter(log_dir=args.output_dir) 126 | 127 | def collate_train(examples): 128 | #print(examples) 129 | source_ids = list(map(lambda x: x[0], examples)) 130 | source_mask = list(map(lambda x: x[1], examples)) 131 | target_ids = list(map(lambda x: x[2], examples)) 132 | target_mask = list(map(lambda x: x[3], examples)) 133 | 134 | source_ids = torch.vstack(source_ids) 135 | source_mask = torch.vstack(source_mask) 136 | target_ids = torch.vstack(target_ids) 137 | target_mask = torch.vstack(target_mask) 138 | 139 | return { 140 | "source_ids": source_ids.to(dtype=torch.long), 141 | "source_mask": source_mask.to(dtype=torch.long), 142 | "target_ids": target_ids.to(dtype=torch.long), 143 | "target_ids_y": target_ids.to(dtype=torch.long), 144 | } 145 | 146 | # RandomSampler:随机采样;DistributedSampler:分布式采样 147 | train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 or args.model_parallel else DistributedSampler(train_dataset, shuffle=True, seed=args.seed) 148 | train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size, collate_fn=collate_train) 149 | 150 | # 计算总的训练step数目:max_steps 151 | if args.max_steps > 0: 152 | t_total = args.max_steps 153 | args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1 154 | else: 155 | t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs 156 | 157 | # 设置需要进行L2正则化的参数 158 | no_decay = ["bias", "LayerNorm.weight"] 159 | optimizer_grouped_parameters = [ 160 | {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": args.weight_decay}, 161 | {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0,} 162 | ] 163 | 164 | # 训练时的优化器选择 165 | if args.optimizer == "Adam": 166 | optimizer = torch.optim.Adam(optimizer_grouped_parameters, lr=args.learning_rate) 167 | elif args.optimizer == "AdamW": 168 | optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) 169 | elif args.optimizer == "Adafactor": 170 | optimizer = Adafactor(optimizer_grouped_parameters, lr=None, eps=(1e-30, 1e-3), clip_threshold=1.0, scale_parameter=True, relative_step=True, warmup_init=True) 171 | elif args.optimizer == "Adafactor-srwf": 172 | # 此种情形无需scheduler 173 | optimizer = Adafactor(optimizer_grouped_parameters, lr=args.learning_rate, eps=(1e-30, 1e-3), clip_threshold=1.0, scale_parameter=False, relative_step=False, warmup_init=False) 174 | 175 | # 学习率模式选择,2022/08/30 新增 by Yirong Chen 176 | if args.scheduler == "get_linear_schedule_with_warmup": 177 | scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(args.warm_up_ratio*t_total), num_training_steps=t_total) 178 | elif args.scheduler == "get_constant_schedule_with_warmup": 179 | scheduler = get_constant_schedule_with_warmup(optimizer, num_warmup_steps=int(args.warm_up_ratio*t_total)) 180 | elif args.scheduler == "get_constant_schedule": 181 | scheduler = get_constant_schedule(optimizer) 182 | elif args.scheduler == "get_cosine_schedule_with_warmup": 183 | scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=int(args.warm_up_ratio*t_total), num_training_steps=t_total, num_cycles=0.5) 184 | elif args.scheduler == "get_adafactor_schedule": 185 | # 配合Adafactor进行使用 186 | # min_step = 1e-6 * param_state["step"] if param_group["warmup_init"] else 1e-2 187 | # KeyError: 'step' 188 | scheduler = get_adafactor_schedule(optimizer, initial_lr=args.learning_rate) 189 | elif args.scheduler == "no_schedule": 190 | logger.info("***** Not use any scheduler!!! *****") 191 | 192 | # Check if saved optimizer or scheduler states exist 193 | if (args.model_name_or_path and os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt")) and os.path.isfile(os.path.join(args.model_name_or_path, "scheduler.pt"))): 194 | optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt"))) 195 | if args.scheduler != "no_schedule": 196 | scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt"))) 197 | 198 | if args.autocast: # 混合精度训练 199 | # 参考: https://pytorch.org/docs/1.9.0/amp.html?highlight=torch%20cuda%20amp%20gradscaler 200 | # https://pytorch.org/docs/1.9.0/notes/amp_examples.html#amp-examples 201 | scaler = GradScaler() # pytorch版本要求:1.6+ 202 | 203 | # multi-gpu training (should be after apex fp16 initialization) 204 | if args.n_gpu > 1 and args.local_rank == -1 and not args.model_parallel: 205 | model = torch.nn.DataParallel(model) 206 | # Distributed training (should be after apex fp16 initialization) 207 | if args.local_rank != -1 and not args.model_parallel: 208 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, 209 | find_unused_parameters=not args.not_find_unused_parameters) 210 | 211 | # Train! 212 | logger.info("***** Running training *****") 213 | logger.info(" Num examples = %d", len(train_dataset)) 214 | logger.info(" Num Epochs = %d", args.num_train_epochs) 215 | logger.info(" Train batch size = %d", args.train_batch_size) 216 | logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size) 217 | logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d", 218 | args.train_batch_size * args.gradient_accumulation_steps * (torch.distributed.get_world_size() if args.local_rank != -1 else 1)) 219 | logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) 220 | logger.info(" Total optimization steps = %d", t_total) 221 | 222 | global_step = 0 223 | epochs_trained = 0 224 | steps_trained_in_current_epoch = 0 225 | 226 | 227 | # Check if continuing training from a checkpoint 228 | if args.model_name_or_path and os.path.exists(args.model_name_or_path): 229 | try: 230 | # set global_step to gobal_step of last saved checkpoint from model path 231 | checkpoint_suffix = args.model_name_or_path.split("-")[-1].split("/")[0] 232 | global_step = int(checkpoint_suffix) 233 | epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps) 234 | steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps) 235 | logger.info(" Continuing training from checkpoint, will skip to saved global_step") 236 | logger.info(" Continuing training from epoch %d", epochs_trained) 237 | logger.info(" Continuing training from global step %d", global_step) 238 | logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch) 239 | except ValueError: 240 | logger.info(" Starting fine-tuning.") 241 | 242 | 243 | tr_loss, logging_loss = 0.0, 0.0 244 | 245 | model.zero_grad() 246 | train_iterator = trange(epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0]) 247 | setup_seed(args.seed, args.n_gpu) 248 | 249 | 250 | for epoch_i in train_iterator: 251 | epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0]) 252 | time1=time.time() 253 | for step, batch in enumerate(epoch_iterator): 254 | # Skip past any already trained steps if resuming training 255 | if steps_trained_in_current_epoch > 0: 256 | steps_trained_in_current_epoch -= 1 257 | continue 258 | 259 | # 输入数据规范化 260 | if args.model_parallel: 261 | y = batch["target_ids"].to(model.encoder.first_device, dtype=torch.long) 262 | y_ids = y[:, :-1].contiguous() # target, from start to end(except end of token, ). e.g. "你好吗?" 263 | lm_labels = y[:, 1:].clone().detach() # target, for second to end.e.g."好吗?" 264 | lm_labels[y[:, 1:] == tokenizer.pad_token_id] = -100 # releted to pad_token and loss. for detail, check here: https://github.com/Shivanandroy/T5-Finetuning-PyTorch/issues/3 265 | ids = batch["source_ids"].to(model.encoder.first_device, dtype=torch.long) # input. e.g. "how are you?" 266 | mask = batch["source_mask"].to(model.encoder.first_device, dtype=torch.long) 267 | else: 268 | y = batch["target_ids"].to(args.device, dtype=torch.long) 269 | y_ids = y[:, :-1].contiguous() # target, from start to end(except end of token, ). e.g. "你好吗?" 270 | lm_labels = y[:, 1:].clone().detach() # target, for second to end.e.g."好吗?" 271 | lm_labels[y[:, 1:] == tokenizer.pad_token_id] = -100 # releted to pad_token and loss. for detail, check here: https://github.com/Shivanandroy/T5-Finetuning-PyTorch/issues/3 272 | ids = batch["source_ids"].to(args.device, dtype=torch.long) # input. e.g. "how are you?" 273 | mask = batch["source_mask"].to(args.device, dtype=torch.long) 274 | 275 | # 设置模型为train()模式 276 | model.train() 277 | # 模型前向计算 278 | 279 | if args.autocast: 280 | # 开启了混合精度训练 281 | with autocast(): 282 | outputs = model( 283 | input_ids=ids, 284 | attention_mask=mask, 285 | decoder_input_ids=y_ids, 286 | labels=lm_labels) 287 | 288 | # 获得模型的loss 289 | loss = outputs[0] 290 | # 对于DDP训练模式,需要将loss求平均 291 | if args.n_gpu > 1: 292 | loss = loss.mean() 293 | # 当设置的gradient_accumulation_steps大于1时,对loss进行loss除以gradient_accumulation_steps 294 | if args.gradient_accumulation_steps > 1: 295 | loss = loss / args.gradient_accumulation_steps 296 | 297 | # 梯度后向计算更新参数 298 | scaler.scale(loss).backward() 299 | #scaler.scale(loss).backward(retain_graph=args.retain_graph) 300 | # retain_graph here is unrelated to amp, it's present because in this both backward() calls share some sections of graph. 301 | 302 | # 记录累积loss 303 | tr_loss += loss.item() 304 | # 梯度裁剪、优化器和学习率模式更新 305 | if (step + 1) % args.gradient_accumulation_steps == 0: 306 | # 参考:https://pytorch.org/docs/1.9.0/notes/amp_examples.html#amp-examples 307 | # Unscales the gradients of optimizer's assigned params in-place 308 | scaler.unscale_(optimizer) 309 | # Since the gradients of optimizer's assigned params are unscaled, clips as usual 310 | parameters_to_clip = [p for p in model.parameters() if p.grad is not None] 311 | torch.nn.utils.clip_grad_norm_(parameters_to_clip, args.max_grad_norm) 312 | scaler.step(optimizer) 313 | scaler.update() 314 | optimizer.zero_grad() 315 | global_step += 1 316 | 317 | 318 | else: 319 | outputs = model( 320 | input_ids=ids, 321 | attention_mask=mask, 322 | decoder_input_ids=y_ids, 323 | labels=lm_labels) 324 | # 获得模型的loss 325 | loss = outputs[0] 326 | # 对于DDP训练模式,需要将loss求平均 327 | if args.n_gpu > 1: 328 | loss = loss.mean() 329 | # 当设置的gradient_accumulation_steps大于1时,对loss进行loss除以gradient_accumulation_steps 330 | if args.gradient_accumulation_steps > 1: 331 | loss = loss / args.gradient_accumulation_steps 332 | # 梯度后向计算更新参数 333 | loss.backward() 334 | # 记录累积loss 335 | tr_loss += loss.item() 336 | # 梯度裁剪、优化器和学习率模式更新 337 | if (step + 1) % args.gradient_accumulation_steps == 0: 338 | parameters_to_clip = [p for p in model.parameters() if p.grad is not None] 339 | torch.nn.utils.clip_grad_norm_(parameters_to_clip, args.max_grad_norm) 340 | optimizer.step() 341 | if args.scheduler != "no_schedule": 342 | scheduler.step() # Update learning rate schedule 343 | model.zero_grad() 344 | global_step += 1 345 | 346 | 347 | 348 | # 打印日志到终端以及保存到Tensorboard文件 349 | if (args.local_rank in [-1, 0] and args.log_steps > 0 and (global_step % args.log_steps == 0) and (global_step > 0 )): 350 | if args.scheduler != "no_schedule": 351 | tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step) 352 | tb_writer.add_scalar("train/loss", (tr_loss - logging_loss) / args.log_steps, global_step) 353 | time2=time.time() 354 | epoch_iterator.set_postfix(loss=f'{((tr_loss - logging_loss) / args.log_steps):.4f}', time_per_step=f'{(float(time2-time1)/float(step+0.0001)):.4f}') 355 | logging_loss = tr_loss 356 | 357 | # 每个 epoch 保存一次模型 358 | if args.local_rank in [-1, 0]: 359 | checkpoint_prefix = "checkpoint" 360 | # Save model checkpoint 361 | output_dir = os.path.join(args.output_dir, "{}-{}".format(checkpoint_prefix, epoch_i)) 362 | os.makedirs(output_dir, exist_ok=True) 363 | model_to_save = model.module if hasattr(model, "module") else model # Take care of distributed/parallel training 364 | model_to_save.save_pretrained(output_dir) 365 | tokenizer.save_pretrained(output_dir) 366 | torch.save(args, os.path.join(output_dir, "training_args.bin")) 367 | logger.info("Saving model checkpoint to %s", output_dir) 368 | _rotate_checkpoints(args, checkpoint_prefix) 369 | if args.save_optimizer_and_scheduler: 370 | # 文件太大了,非必要不保存,需要指定--save_optimizer_and_scheduler才保存 371 | torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) 372 | if args.scheduler != "no_schedule": 373 | torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) 374 | logger.info("Saving optimizer and scheduler states to %s", output_dir) 375 | 376 | if args.max_steps > 0 and global_step > args.max_steps: 377 | epoch_iterator.close() 378 | break 379 | 380 | if args.max_steps > 0 and global_step > args.max_steps: 381 | train_iterator.close() 382 | break 383 | 384 | if args.local_rank in [-1, 0]: 385 | tb_writer.close() 386 | 387 | return global_step, tr_loss/global_step 388 | 389 | def main(): 390 | ''' 391 | 训练的主函数入口 392 | 393 | ''' 394 | # Get the arguments for training model 395 | args = parser.parse_args() 396 | 397 | print(args) 398 | 399 | 400 | # 导入模型类 401 | if args.autocast: 402 | # 与原来的transformers提供的区别是,在T5ForConditionalGeneration的forward函数增加了@autocast()注解 403 | # 参考:https://pytorch.org/docs/1.9.0/notes/amp_examples.html#amp-examples 404 | from models.t5 import T5Tokenizer, T5ForConditionalGeneration 405 | else: 406 | from transformers import T5Tokenizer, T5ForConditionalGeneration 407 | 408 | # Setup args.local_rank and args.world_size 409 | if args.no_cuda or args.model_parallel: 410 | args.local_rank = -1 411 | args.world_size = 1 412 | else: 413 | args.world_size = 1 # 默认值 414 | if "LOCAL_RANK" in os.environ: # 需要使用torchrun才有! 415 | args.local_rank = int(os.environ["LOCAL_RANK"]) 416 | if "WORLD_SIZE" in os.environ: 417 | args.world_size = int(os.environ["WORLD_SIZE"]) # 节点数*每个节点地方任务数 418 | 419 | # Load model from checkpoints for continue training 420 | if args.should_continue: 421 | sorted_checkpoints = _sorted_checkpoints(args) 422 | if len(sorted_checkpoints) == 0: 423 | raise ValueError("Used --should_continue but no checkpoint was found in --output_dir.") 424 | else: 425 | args.model_name_or_path = sorted_checkpoints[-1] 426 | if (os.path.exists(args.output_dir) and os.listdir(args.output_dir) and not args.overwrite_output_dir and not args.should_continue): 427 | raise ValueError("Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(args.output_dir)) 428 | 429 | # Setup CUDA, GPU & distributed training 430 | if args.local_rank == -1 or args.no_cuda: 431 | device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu") 432 | args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count() 433 | 434 | else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs 435 | # 数据并行DDP训练方式 436 | torch.cuda.set_device(args.local_rank) 437 | device = torch.device("cuda", args.local_rank) 438 | torch.distributed.init_process_group(backend="nccl") 439 | args.n_gpu = 1 440 | args.device = device 441 | 442 | # Setup logging 443 | logging.basicConfig(format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 444 | datefmt="%m/%d/%Y %H:%M:%S", 445 | level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN) 446 | logger.warning("Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), args.fp16) 447 | 448 | # Set seed 449 | setup_seed(args.seed, args.n_gpu) 450 | 451 | # Initialize the model and tokenizer 452 | # 根据模型类型确定模型类以及tokenizer 453 | if args.model_type == 't5': 454 | model_class, tokenizer_class = T5ForConditionalGeneration, T5Tokenizer 455 | ''' 456 | # Add new model class here 457 | elif args.model_type == "XXX": 458 | model_class, tokenizer_class = ModelClassName, TokenizerClassName 459 | ''' 460 | 461 | # 加载tokenizer 462 | tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) 463 | if args.add_special_tokens: 464 | if not os.path.exists(args.add_special_tokens): 465 | raise ValueError("Additional special tokens file {args.add_special_tokens} not found}") 466 | with open(args.add_special_tokens, "rb") as handle: 467 | special_tokens_dict = json.load(handle) 468 | num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) 469 | logger.info(f"Added {num_added_toks} tokens") 470 | logger.info(f"All special tokens: {tokenizer.all_special_tokens}") 471 | 472 | # Load model from pretrained 473 | model = model_class.from_pretrained(args.model_name_or_path) 474 | 475 | # Set model parallel training 476 | # 本部分用于配置模型分配不同的层到不同的GPU卡上进行训练,通常参数达到上十亿的模型才需要 477 | if args.model_parallel and not args.no_cuda and torch.cuda.is_available(): 478 | logger.info("parallelizing...") 479 | model.parallelize() # 自动计算模型层数,将模型切分到不同的显卡 480 | else: 481 | logger.info("put model to GPU") 482 | model.to(args.device) 483 | 484 | #if args.local_rank not in [-1, 0]: 485 | # torch.distributed.barrier() # Barrier to make sure only the first process in distributed training process the dataset, and the others will use the cache 486 | 487 | 488 | if args.no_cuda: 489 | # 辅助调试代码 490 | print(model) 491 | print(model.config) 492 | 493 | logger.info("Training/evaluation parameters %s", args) 494 | 495 | 496 | # Set args.train_batch_size and args.eval_batch_size 497 | if args.model_parallel: # 模型流水线并行 498 | args.train_batch_size = args.per_gpu_train_batch_size 499 | args.eval_batch_size = args.per_gpu_eval_batch_size 500 | else: # 分布式训练 501 | args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) 502 | args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) 503 | 504 | 505 | 506 | # Load Dataset 507 | logger.info("Loading Dataset...") 508 | df = pd.read_csv(args.data_path) 509 | df = df.sample(frac=args.dataset_sample_frac) 510 | print("df.head:",df.head(n=5)) 511 | print("df.shape:",df.shape) 512 | 513 | df = df[[args.dataset_input_column_name, args.dataset_target_column_name]] # 输入和输出的列名 514 | 515 | train_dataset = df.sample(frac=args.train_radio_of_dataset, random_state=args.seed) # 采样得到训练集 516 | val_dataset = df.drop(train_dataset.index).reset_index(drop=True) # 采样得到验证集 517 | train_dataset = train_dataset.reset_index(drop=True) 518 | 519 | logger.info(f"FULL Dataset: {df.shape}") 520 | logger.info(f"TRAIN Dataset: {train_dataset.shape}") 521 | logger.info(f"TEST Dataset: {val_dataset.shape}\n") 522 | 523 | training_set = PromptDataSetClass( 524 | train_dataset, 525 | tokenizer, 526 | args.max_source_text_length, 527 | args.max_target_text_length, 528 | args.dataset_input_column_name, 529 | args.dataset_target_column_name, 530 | ) 531 | val_set = PromptDataSetClass( 532 | val_dataset, 533 | tokenizer, 534 | args.max_source_text_length, 535 | args.max_target_text_length, 536 | args.dataset_input_column_name, 537 | args.dataset_target_column_name, 538 | ) 539 | 540 | # Training the model 541 | if not args.no_train: # 如果不指定--no_train,则进行模型训练 542 | logger.info("***************Training***************") 543 | global_step, train_loss = train(args=args, model=model, tokenizer=tokenizer, train_dataset=training_set, eval_dataset=val_set) 544 | logger.info(" global_step = %s, average loss = %s", global_step, train_loss) 545 | 546 | # Saving best-practices: if you use save_pretrained for the model and tokenizer, you can reload them using from_pretrained() 547 | if args.local_rank == -1 or torch.distributed.get_rank() == 0: 548 | if args.local_rank in [-1, 0]: 549 | os.makedirs(args.output_dir, exist_ok=True) 550 | logger.info("Saving model checkpoint to %s", args.output_dir) 551 | model_to_save = (model.module if hasattr(model, "module") else model) # Take care of distributed/parallel training 552 | model_to_save.save_pretrained(args.output_dir) 553 | tokenizer.save_pretrained(args.output_dir) 554 | torch.save(args, os.path.join(args.output_dir, "training_args.bin")) 555 | with open(os.path.join(args.output_dir, "training_args.json"),'w',encoding='utf-8') as json_file: 556 | json.dump(pformat(args),json_file,ensure_ascii=False) 557 | logger.info("Finishing Train and save model checkpoint!!!") 558 | 559 | 560 | if __name__ == '__main__': 561 | main() 562 | -------------------------------------------------------------------------------- /train_model_args.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 Research Center of Body Data Science from South China University of Technology. All rights reserved. 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | 17 | # File: train_model_args.py 18 | # Description: The training model code for SCUTChatLM 19 | # Repository: https://github.com/scutcyr 20 | # Mail: [eeyirongchen@mail.scut.edu.cn](mailto:eeyirongchen@mail.scut.edu.cn) 21 | # Date: 2023/03/14 22 | # Usage: 23 | # from train_model_args import parser 24 | # args = parser.parse_args() 25 | 26 | 27 | import argparse 28 | 29 | parser = argparse.ArgumentParser() 30 | 31 | 32 | parser.add_argument( 33 | "--model_type", 34 | default="t5", 35 | type=str, 36 | choices=['t5'], 37 | help="The model architecture to be trained or fine-tuned.", 38 | ) 39 | 40 | 41 | 42 | # model_parallel: 设置模型是否并行,也就是将一个超大模型放在多张GPU上 43 | parser.add_argument( 44 | "--model_parallel", 45 | action="store_true", 46 | help="Set model_parallel=True", 47 | ) 48 | # 预训练模型路径或名称或者初始化配置路径 49 | parser.add_argument( 50 | "--model_name_or_path", 51 | default="scutcyr/BianQue-1.0", 52 | type=str, 53 | required=True, 54 | help="The model checkpoint for weights initialization. Leave None if you want to train a model from scratch.", 55 | ) 56 | # 增加的special token 57 | parser.add_argument( 58 | "--add_special_tokens", 59 | default=None, 60 | type=str, 61 | help="Optional file containing a JSON dictionary of special tokens that should be added to the tokenizer.", 62 | ) 63 | # 训练的数据集csv格式文件,包含以下列:input、target、answer_choices、type 64 | parser.add_argument( 65 | "--data_path", 66 | type=str, 67 | default="./data/cMedialog_example.csv", 68 | help='the path of the dataset for training model' 69 | ) 70 | parser.add_argument( 71 | "--dataset_sample_frac", 72 | default=1, 73 | type=float, 74 | help="数据集的采样率,范围:0~1" 75 | ) 76 | parser.add_argument( 77 | "--train_radio_of_dataset", 78 | default=0.94, 79 | type=float, 80 | help="数据集的训练样本比例,范围:0~1" 81 | ) 82 | parser.add_argument( 83 | "--dataset_input_column_name", 84 | default="input", 85 | type=str, 86 | help="column name of source text", 87 | ) 88 | parser.add_argument( 89 | "--dataset_target_column_name", 90 | default="target", 91 | type=str, 92 | help="column name of target text", 93 | ) 94 | 95 | parser.add_argument( 96 | "--max_source_text_length", 97 | default=512, 98 | type=int, 99 | help="max length of source text, 512", 100 | ) 101 | parser.add_argument( 102 | "--max_target_text_length", 103 | default=512, 104 | type=int, 105 | help="max length of target text, 512", 106 | ) 107 | 108 | # 模型保存的路径 109 | parser.add_argument( 110 | "--output_dir", 111 | required=True, 112 | type=str, 113 | help="The model checkpoint saving path", 114 | ) 115 | 116 | parser.add_argument( 117 | "--seed", 118 | default=42, 119 | type=int, 120 | help="The seed setting.", 121 | ) 122 | # 模型从output_dir继续运行 123 | parser.add_argument( 124 | "--should_continue", 125 | action="store_true", 126 | help="Whether to continue from latest checkpoint in output_dir", 127 | ) 128 | parser.add_argument( 129 | "--save_optimizer_and_scheduler", 130 | action="store_true", 131 | help="save optimizer and scheduler in the checkpoint", 132 | ) 133 | parser.add_argument( 134 | "--overwrite_output_dir", 135 | action="store_true", 136 | help="Overwrite the content of the output directory", 137 | ) 138 | parser.add_argument( 139 | "--no_cuda", action="store_true", help="Avoid using CUDA when available" 140 | ) 141 | 142 | parser.add_argument( 143 | "--log_steps", default=10, type=int, help="logging output steps." 144 | ) 145 | 146 | 147 | parser.add_argument( 148 | "--per_gpu_train_batch_size", 149 | default=1, 150 | type=int, 151 | help="Batch size per GPU/CPU for training.", 152 | ) 153 | parser.add_argument( 154 | "--per_gpu_eval_batch_size", 155 | default=1, 156 | type=int, 157 | help="Batch size per GPU/CPU for evaluation.", 158 | ) 159 | 160 | # 训练的优化器和学习率下降模式设置 161 | parser.add_argument( 162 | "--optimizer", 163 | type=str, 164 | default="Adam", 165 | choices=['Adam', 'AdamW', 'Adafactor', 'Adafactor-srwf'], 166 | help="For optimizer.", 167 | ) 168 | # 学习率下降模式 169 | parser.add_argument( 170 | "--scheduler", 171 | type=str, 172 | default="get_constant_schedule", 173 | choices=['get_linear_schedule_with_warmup', 'get_constant_schedule_with_warmup', 'get_constant_schedule', 174 | 'get_cosine_schedule_with_warmup', 'get_adafactor_schedule', 'no_schedule'], 175 | help="For scheduler.", 176 | ) 177 | parser.add_argument( 178 | "--learning_rate", 179 | default=5e-5, 180 | type=float, 181 | help="The initial learning rate for Adam.", 182 | ) 183 | parser.add_argument( 184 | "--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer." 185 | ) 186 | parser.add_argument( 187 | "--warmup_steps", default=8000, type=int, help="Linear warmup over warmup_steps." 188 | ) 189 | parser.add_argument( 190 | "--warm_up_ratio", default=0.1, type=float, help="Linear warmup over warmup_steps(warm_up_ratio*t_total)." 191 | ) 192 | parser.add_argument( 193 | "--max_grad_norm", default=1.0, type=float, help="Max gradient norm." 194 | ) 195 | parser.add_argument( 196 | "--weight_decay", default=0.0, type=float, help="Weight decay if we apply some." 197 | ) 198 | 199 | # 模型训练的epoch数目 200 | parser.add_argument( 201 | '--num_train_epochs', 202 | default=3, 203 | type=int, 204 | ) 205 | # 模型训练的最大步数 206 | parser.add_argument( 207 | "--max_steps", 208 | default=-1, 209 | type=int, 210 | help="If > 0: set total number of training steps to perform. Override num_train_epochs.", 211 | ) 212 | # 设置是否进行迅雷 213 | parser.add_argument( 214 | "--no_train", action="store_true", help="Only evaluate the checkpoint and not train" 215 | ) 216 | 217 | # 模型的梯度加速 218 | parser.add_argument( 219 | "--gradient_accumulation_steps", 220 | type=int, 221 | default=1, 222 | help="Number of updates steps to accumulate before performing a backward/update pass.", 223 | ) 224 | # Dataloder的num_workers 225 | parser.add_argument( 226 | "--num_workers", 227 | default=4, 228 | type=int, 229 | help="num_workers for Dataloder", 230 | ) 231 | parser.add_argument( 232 | "--local_rank", 233 | type=int, 234 | default=-1, 235 | help="For distributed training: local_rank", 236 | ) 237 | parser.add_argument( 238 | "--not_find_unused_parameters", action="store_true", help="If True set find_unused_parameters=False in DDP constructor" 239 | ) 240 | 241 | parser.add_argument( 242 | "--save_total_limit", 243 | type=int, 244 | default=3, 245 | help="Limit the total amount of checkpoints, delete the older checkpoints in the output_dir, does not delete by default", 246 | ) 247 | 248 | # 混合精度训练 249 | parser.add_argument("--autocast", action='store_true', 250 | help="If true using autocast to automatically mix accuracy to accelerate training(开启自动混合精度加速训练)") 251 | parser.add_argument( 252 | "--fp16", 253 | action="store_true", 254 | help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit", 255 | ) 256 | parser.add_argument( 257 | "--fp16_opt_level", 258 | type=str, 259 | default="O1", 260 | help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." 261 | "See details at https://nvidia.github.io/apex/amp.html", 262 | ) -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 Research Center of Body Data Science from South China University of Technology. All rights reserved. 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | 17 | from .prompt_dataset import PromptDataSetClass -------------------------------------------------------------------------------- /utils/prompt_dataset.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 Research Center of Body Data Science from South China University of Technology. All rights reserved. 3 | 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | 17 | # File: cMedQA_dataset.py 18 | # Description: The dataset loading class of cMedQA 19 | # Repository: https://github.com/scutcyr 20 | # Mail: [eeyirongchen@mail.scut.edu.cn](mailto:eeyirongchen@mail.scut.edu.cn) 21 | # Date: 2023/03/14 22 | 23 | 24 | import torch 25 | from torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler 26 | 27 | 28 | 29 | class PromptDataSetClass(Dataset): 30 | """ 31 | 创建一个自定义的数据集,用于训练,必须包括两个字段:输入(如source_text)、输出(如target_text) 32 | Creating a custom dataset for reading the dataset and 33 | loading it into the dataloader to pass it to the 34 | neural network for finetuning the model 35 | 36 | """ 37 | 38 | def __init__( 39 | self, dataframe, tokenizer, source_len, target_len, source_text, target_text, return_dict=False 40 | ): 41 | """ 42 | Initializes a Dataset class 43 | 44 | Args: 45 | dataframe (pandas.DataFrame): Input dataframe 46 | tokenizer (transformers.tokenizer): Transformers tokenizer 47 | source_len (int): Max length of source text 48 | target_len (int): Max length of target text 49 | source_text (str): column name of source text 50 | target_text (str): column name of target text 51 | """ 52 | self.tokenizer = tokenizer 53 | self.data = dataframe 54 | self.source_len = source_len 55 | self.summ_len = target_len 56 | self.target_text = self.data[target_text] 57 | self.source_text = self.data[source_text] 58 | self.return_dict = return_dict 59 | 60 | def __len__(self): 61 | """returns the length of dataframe""" 62 | 63 | return len(self.target_text) 64 | 65 | def __getitem__(self, index): 66 | """return the input ids, attention masks and target ids""" 67 | 68 | source_text = str(self.source_text[index]) 69 | target_text = str(self.target_text[index]) 70 | 71 | # cleaning data so as to ensure data is in string type 72 | source_text = " ".join(source_text.split()) 73 | target_text = " ".join(target_text.split()) 74 | 75 | source = self.tokenizer.batch_encode_plus( 76 | [source_text], 77 | max_length=self.source_len, 78 | pad_to_max_length=True, 79 | truncation=True, 80 | padding="max_length", 81 | return_tensors="pt", 82 | ) 83 | target = self.tokenizer.batch_encode_plus( 84 | [target_text], 85 | max_length=self.summ_len, 86 | pad_to_max_length=True, 87 | truncation=True, 88 | padding="max_length", 89 | return_tensors="pt", 90 | ) 91 | 92 | source_ids = source["input_ids"].squeeze() 93 | source_mask = source["attention_mask"].squeeze() 94 | target_ids = target["input_ids"].squeeze() 95 | target_mask = target["attention_mask"].squeeze() 96 | 97 | if self.return_dict: 98 | return { 99 | "source_ids": source_ids.to(dtype=torch.long), 100 | "source_mask": source_mask.to(dtype=torch.long), 101 | "target_ids": target_ids.to(dtype=torch.long), 102 | "target_ids_y": target_ids.to(dtype=torch.long), 103 | } 104 | else: 105 | return source_ids.to(dtype=torch.long), source_mask.to(dtype=torch.long), target_ids.to(dtype=torch.long), target_ids.to(dtype=torch.long) 106 | 107 | 108 | --------------------------------------------------------------------------------