[{"data":1,"prerenderedAt":729},["ShallowReactive",2],{"content-query-UAv93pIjof":3},{"_path":4,"_dir":5,"_draft":6,"_partial":6,"_locale":7,"title":8,"description":9,"date":10,"cover":11,"type":12,"category":13,"body":14,"_type":723,"_id":724,"_source":725,"_file":726,"_stem":727,"_extension":728},"/technology-blogs/zh/3615","zh",false,"","大模型中文成语释义与解析挑战-基于MindSpore分布式推理的llama3-8B实践项目","作者：鲍迪       来源：昇思学习打卡营第五期·NLP特辑","2025-02-17","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/02/21/195b869efbce48ada5880f19e56a5941.png","technology-blogs","开发者分享",{"type":15,"children":16,"toc":713},"root",[17,25,35,40,48,53,58,63,68,76,81,86,91,96,101,106,114,122,127,134,141,146,153,158,167,172,177,182,187,192,197,202,210,215,220,225,230,235,240,248,262,267,280,285,296,301,312,317,360,370,383,393,401,409,417,450,455,460,465,498,506,514,519,527,535,540,545,550,555,560,564,575,582,590,595,600,605,610,615,620,628,636,644,649,657,662,670,675,683,691,703],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"大模型中文成语释义与解析挑战-基于mindspore分布式推理的llama3-8b实践项目",[23],{"type":24,"value":8},"text",{"type":18,"tag":26,"props":27,"children":28},"p",{},[29],{"type":18,"tag":30,"props":31,"children":32},"strong",{},[33],{"type":24,"value":34},"作者：鲍迪 来源：昇思学习打卡营第五期·NLP特辑",{"type":18,"tag":26,"props":36,"children":37},{},[38],{"type":24,"value":39},"《昇思学习打卡营第五期·NLP特辑》的直播和打卡已全部完成。由打卡营优秀学员们输出的学习笔记同样值得我们研读和学习。本期技术文章由打卡营学员鲍迪输出并投稿。如果您也在本期打卡营中获益良多，欢迎私聊我们投稿。",{"type":18,"tag":26,"props":41,"children":42},{},[43],{"type":18,"tag":30,"props":44,"children":45},{},[46],{"type":24,"value":47},"成语释义与解析挑战",{"type":18,"tag":26,"props":49,"children":50},{},[51],{"type":24,"value":52},"中文成语，汉语的瑰宝，承载着千年的文化传统和智慧积淀。它们通常由四字组成，形式简洁却内涵丰富，寥寥数语便能传递深刻的思想和情感。成语的理解和应用，不仅要求掌握其字面意义，更要洞悉其背后的文化和历史渊源。在人工智能领域，构建能够准确理解并恰当运用成语的模型，对于推动中文自然语言处理技术的发展具有重要意义。",{"type":18,"tag":26,"props":54,"children":55},{},[56],{"type":24,"value":57},"这个赛题旨在挑战和提升模型对中文成语的深入理解能力。大家需要构建模型，通过理解成语在具体语境中的使用，从给定的候选成语中选择最合适的选项，填补文本中的空白。这一任务不仅考察模型对成语基本义项的掌握，更考验其对成语深层次含义及使用场景的精准把握。",{"type":18,"tag":26,"props":59,"children":60},{},[61],{"type":24,"value":62},"数据集由2972条中文通俗介绍的句子组成，每条句子对应一个成语单词。对于每个句子需要提交最有可能的五个成语单词，五个成语中只要有一个是正确的即可。调用开源大模型利用其对中文语义的理解，生成语义所描述的成语。",{"type":18,"tag":26,"props":64,"children":65},{},[66],{"type":24,"value":67},"数据集前10条文本：",{"type":18,"tag":26,"props":69,"children":70},{},[71],{"type":18,"tag":72,"props":73,"children":75},"img",{"alt":7,"src":74},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/02/21/55ce23eca7454c85bee633aea1626133.png",[],{"type":18,"tag":26,"props":77,"children":78},{},[79],{"type":24,"value":80},"使用自然语言指令驱使大模型对2972条这样的文义语句进行总结，每条语义可以总结为5个成语，其中有一个正确即可。这样的语义理解任务对于开源大模型的中文能力要求是相当高的，同时这样的半开放命题也是一个非常好的大模型技术学习机会。基于我们的调优手段，可以产生以下的调优思路：",{"type":18,"tag":26,"props":82,"children":83},{},[84],{"type":24,"value":85},"1、选择中文表现优秀的大模型",{"type":18,"tag":26,"props":87,"children":88},{},[89],{"type":24,"value":90},"2、对于选取优质的开源大模型进行成语语义文本的微调以提高生成表现",{"type":18,"tag":26,"props":92,"children":93},{},[94],{"type":24,"value":95},"3、对于Prompt进行优化以获取更好的回答",{"type":18,"tag":26,"props":97,"children":98},{},[99],{"type":24,"value":100},"4、对于Decoding策略进行优化，通过model.generate()参数的调整获取更好的回答",{"type":18,"tag":26,"props":102,"children":103},{},[104],{"type":24,"value":105},"本文选取了能力优秀的Llama3-8B-Instruct模型作为大模型，使用Mindspore框架基于华为云Modelarts环境的NPU进行高效推理。",{"type":18,"tag":26,"props":107,"children":108},{},[109],{"type":18,"tag":30,"props":110,"children":111},{},[112],{"type":24,"value":113},"Llama3-8B-Instruct",{"type":18,"tag":26,"props":115,"children":116},{},[117],{"type":18,"tag":30,"props":118,"children":119},{},[120],{"type":24,"value":121},"Llama 3",{"type":18,"tag":26,"props":123,"children":124},{},[125],{"type":24,"value":126},"2024年4月18日，Meta 重磅推出了Meta Llama 3，Llama 3是Meta最先进开源大型语言模型的下一代，包括具有80亿和700亿参数的预训练和指令微调的语言模型，能够支持广泛的应用场景。",{"type":18,"tag":26,"props":128,"children":129},{},[130],{"type":18,"tag":72,"props":131,"children":133},{"alt":7,"src":132},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/02/21/d5ce3723dc8b48dead1421ab45117894.png",[],{"type":18,"tag":26,"props":135,"children":136},{},[137],{"type":18,"tag":72,"props":138,"children":140},{"alt":7,"src":139},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/02/21/f6c77f4cb295405dba57a4cd668b28e6.png",[],{"type":18,"tag":26,"props":142,"children":143},{},[144],{"type":24,"value":145},"新的80亿和700亿参数的Llama 3模型在Llama 2的基础上取得了显著进展，为这类大规模语言模型（LLM）设立了新的行业标杆。通过预训练和后训练阶段的改进，这些模型在当前可用的80亿和700亿参数规模中表现最佳。这些改进还带来了推理能力、代码生成以及指令遵循方面的大幅提升，使得Llama 3模型变得更加易于操控和高效。因此，可以说，通过一系列优化措施，Llama 3在多个关键性能指标上实现了对前代产品的超越，展示了其在自然语言处理领域的强大竞争力。",{"type":18,"tag":26,"props":147,"children":148},{},[149],{"type":18,"tag":30,"props":150,"children":151},{},[152],{"type":24,"value":113},{"type":18,"tag":26,"props":154,"children":155},{},[156],{"type":24,"value":157},"Meta-Llama-3-8B-Instruct是Meta公司开发的大型语言模型(LLM)系列中的一员。它是一个经过指令微调的80亿参数规模的模型,专门针对对话场景进行了优化。该模型是Meta Llama 3模型家族中的一个重要成员,旨在提供强大的自然语言处理能力,同时兼顾安全性和有用性。",{"type":18,"tag":159,"props":160,"children":162},"h3",{"id":161},"模型特点",[163],{"type":18,"tag":30,"props":164,"children":165},{},[166],{"type":24,"value":161},{"type":18,"tag":26,"props":168,"children":169},{},[170],{"type":24,"value":171},"Meta-Llama-3-8B-Instruct模型具有以下几个主要特点:",{"type":18,"tag":26,"props":173,"children":174},{},[175],{"type":24,"value":176},"1、参数规模: 拥有80亿参数,属于中等规模的语言模型。",{"type":18,"tag":26,"props":178,"children":179},{},[180],{"type":24,"value":181},"2、上下文长度: 支持8k token的上下文窗口,可以处理较长的输入文本。",{"type":18,"tag":26,"props":183,"children":184},{},[185],{"type":24,"value":186},"3、训练数据: 使用了15T以上的公开在线数据进行预训练。",{"type":18,"tag":26,"props":188,"children":189},{},[190],{"type":24,"value":191},"4、知识截止: 模型的知识截止到2023年3月。",{"type":18,"tag":26,"props":193,"children":194},{},[195],{"type":24,"value":196},"5、架构优化: 采用了优化的Transformer架构,并使用了分组查询注意力(GQA)机制来提高推理效率。",{"type":18,"tag":26,"props":198,"children":199},{},[200],{"type":24,"value":201},"6、指令微调: 经过了监督微调(SFT)和基于人类反馈的强化学习(RLHF)的训练,以提高模型的有用性和安全性。",{"type":18,"tag":159,"props":203,"children":205},{"id":204},"使用场景",[206],{"type":18,"tag":30,"props":207,"children":208},{},[209],{"type":24,"value":204},{"type":18,"tag":26,"props":211,"children":212},{},[213],{"type":24,"value":214},"Meta-Llama-3-8B-Instruct模型主要针对以下场景设计:",{"type":18,"tag":26,"props":216,"children":217},{},[218],{"type":24,"value":219},"1、商业应用: 可用于开发各种商业化的自然语言处理应用。",{"type":18,"tag":26,"props":221,"children":222},{},[223],{"type":24,"value":224},"2、研究用途: 适合进行自然语言处理相关的学术研究。",{"type":18,"tag":26,"props":226,"children":227},{},[228],{"type":24,"value":229},"3、对话系统: 特别擅长处理类似人工助手的聊天任务。",{"type":18,"tag":26,"props":231,"children":232},{},[233],{"type":24,"value":234},"4、英语处理: 主要针对英语语言进行了优化。",{"type":18,"tag":26,"props":236,"children":237},{},[238],{"type":24,"value":239},"需要注意的是,该模型不应用于违反法律法规的用途,也不建议直接用于英语之外的语言处理任务。",{"type":18,"tag":26,"props":241,"children":242},{},[243],{"type":18,"tag":30,"props":244,"children":245},{},[246],{"type":24,"value":247},"MindSpore NLP适配",{"type":18,"tag":26,"props":249,"children":250},{},[251,253],{"type":24,"value":252},"msrun是动态组网（",{"type":18,"tag":254,"props":255,"children":259},"a",{"href":256,"rel":257},"https://www.mindspore.cn/docs/zh-CN/r2.4.1/model%5C_train/parallel/dynamic%5C_cluster.html%EF%BC%89%E5%90%AF%E5%8A%A8%E6%96%B9%E5%BC%8F%E7%9A%84%E5%B0%81%E8%A3%85%EF%BC%8C%E7%94%A8%E6%88%B7%E5%8F%AF%E4%BD%BF%E7%94%A8msrun%E4%BB%A5%E5%8D%95%E4%B8%AA%E5%91%BD%E4%BB%A4%E8%A1%8C%E6%8C%87%E4%BB%A4%E7%9A%84%E6%96%B9%E5%BC%8F%E5%9C%A8%E5%90%84%E8%8A%82%E7%82%B9%E6%8B%89%E8%B5%B7%E5%A4%9A%E8%BF%9B%E7%A8%8B%E5%88%86%E5%B8%83%E5%BC%8F%E4%BB%BB%E5%8A%A1%EF%BC%8C%E5%B9%B6%E4%B8%94%E6%97%A0%E9%9C%80%E6%89%8B%E5%8A%A8%E8%AE%BE%E7%BD%AE%E5%8A%A8%E6%80%81%E7%BB%84%E7%BD%91%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F%EF%BC%88https://www.mindspore.cn/docs/zh-CN/r2.4.1/model%5C_train/parallel/dynamic%5C_cluster.html%EF%BC%89%E3%80%82msrun%E5%90%8C%E6%97%B6%E6%94%AF%E6%8C%81Ascend%EF%BC%8CGPU%E5%92%8CCPU%E5%90%8E%E7%AB%AF%E3%80%82%E4%B8%8E%E5%8A%A8%E6%80%81%E7%BB%84%E7%BD%91%E5%90%AF%E5%8A%A8%E6%96%B9%E5%BC%8F%E4%B8%80%E6%A0%B7%EF%BC%8Cmsrun%E6%97%A0%E9%9C%80%E4%BE%9D%E8%B5%96%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%93%E4%BB%A5%E5%8F%8A%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E3%80%82",[258],"nofollow",[260],{"type":24,"value":261},"https://www.mindspore.cn/docs/zh-CN/r2.4.1/model\\_train/parallel/dynamic\\_cluster.html）启动方式的封装，用户可使用msrun以单个命令行指令的方式在各节点拉起多进程分布式任务，并且无需手动设置动态组网环境变量（https://www.mindspore.cn/docs/zh-CN/r2.4.1/model\\_train/parallel/dynamic\\_cluster.html）。msrun同时支持Ascend，GPU和CPU后端。与动态组网启动方式一样，msrun无需依赖第三方库以及配置文件。",{"type":18,"tag":26,"props":263,"children":264},{},[265],{"type":24,"value":266},"MindSpore NLP是基于MindSpore的一个自然语言处理（NLP）开源库，其中包含了许多自然语言处理的常用方法，提供了一个易用的NLP平台，旨在帮助研究人员和开发者更高效地构建和训练模型。",{"type":18,"tag":268,"props":269,"children":270},"ul",{},[271],{"type":18,"tag":272,"props":273,"children":274},"li",{},[275],{"type":18,"tag":30,"props":276,"children":277},{},[278],{"type":24,"value":279},"丰富完备的数据预处理模块",{"type":18,"tag":26,"props":281,"children":282},{},[283],{"type":24,"value":284},"提供丰富的NLP数据处理模块，可灵活高效地完成数据预处理，包括Multi30k、SQuAD、CoNLL等经典数据集。",{"type":18,"tag":268,"props":286,"children":287},{},[288],{"type":18,"tag":272,"props":289,"children":290},{},[291],{"type":18,"tag":30,"props":292,"children":293},{},[294],{"type":24,"value":295},"用户友好的NLP模型工具集",{"type":18,"tag":26,"props":297,"children":298},{},[299],{"type":24,"value":300},"提供多种可配置神经网络组件，易于用户自定义模型，可大幅提升NLP任务建模的效率。",{"type":18,"tag":268,"props":302,"children":303},{},[304],{"type":18,"tag":272,"props":305,"children":306},{},[307],{"type":18,"tag":30,"props":308,"children":309},{},[310],{"type":24,"value":311},"灵活易用的训练与推理引擎",{"type":18,"tag":26,"props":313,"children":314},{},[315],{"type":24,"value":316},"简化了MindSpore中复杂的训练过程，提供了灵活易用的 Trainer 和 Evaluator ，可以轻松地训练和评估模型",{"type":18,"tag":268,"props":318,"children":319},{},[320,325,330,335,340,345,350,355],{"type":18,"tag":272,"props":321,"children":322},{},[323],{"type":24,"value":324},"**完整的平台支持：**全面支持 Ascend 910 series、Ascend 310B (Orange Pi)、GPU和CPU。（注意：目前 Orange Pi 上唯一可用的 AI 开发套件。",{"type":18,"tag":272,"props":326,"children":327},{},[328],{"type":24,"value":329},"**分布式并行推理：**对超过 10B 参数的模型提供多设备、多进程并行推理支持。",{"type":18,"tag":272,"props":331,"children":332},{},[333],{"type":24,"value":334},"**量化算法支持：**SmoothQuant 可用于 Orange Pi;GPU 支持类似 bitsandbytes 的 int8 量化。",{"type":18,"tag":272,"props":336,"children":337},{},[338],{"type":24,"value":339},"**Sentence Transformer 支持：**实现高效的 RAG（检索增强生成）开发。",{"type":18,"tag":272,"props":341,"children":342},{},[343],{"type":24,"value":344},"**动态图性能优化：**在 Ascend 硬件上实现动态图的 PyTorch+GPU 级推理速度（在 85 毫秒/令牌下测试 Llama 性能）。",{"type":18,"tag":272,"props":346,"children":347},{},[348],{"type":24,"value":349},"**真正的静态和动态图形统一：**单行切换到图形模式，与 Hugging Face 代码风格完全兼容，既易于使用又能快速提升性能。在Ascend硬件上测试的Llama性能达到了2倍的动态图速度（45ms/token），与其他MindSpore基于静态图的套件一致。mindspore.jit",{"type":18,"tag":272,"props":351,"children":352},{},[353],{"type":24,"value":354},"**广泛的 LLM 应用程序更新：**包括 Text information extraction、Chatbots、Speech recognition、ChatPDF、Music generation、Code generation、Voice clone 等。随着模型支持的增加，更多令人兴奋的应用程序等待开发！",{"type":18,"tag":272,"props":356,"children":357},{},[358],{"type":24,"value":359},"**MindSpore NLP对于Llama-3-8B-Instruct模型进行了适配，**能够通过MindSporeNLP组件很方便地使用简短代码调用模型：",{"type":18,"tag":361,"props":362,"children":364},"pre",{"code":363},"from mindnlp.transformers import AutoModel\n\nmodel = AutoModel.from_pretrained('LLM-Research/Meta-Llama-3-8B-Instruct')\n",[365],{"type":18,"tag":366,"props":367,"children":368},"code",{"__ignoreMap":7},[369],{"type":24,"value":363},{"type":18,"tag":268,"props":371,"children":372},{},[373],{"type":18,"tag":272,"props":374,"children":375},{},[376,381],{"type":18,"tag":30,"props":377,"children":378},{},[379],{"type":24,"value":380},"代码仓",{"type":24,"value":382},"中提供了基于Mindspore和mindnlp.transformers的Llama3脚本和分布式推理脚本",{"type":18,"tag":26,"props":384,"children":385},{},[386],{"type":18,"tag":254,"props":387,"children":390},{"href":388,"rel":389},"https://github.com/mindspore-lab/mindnlp/tree/master/llm/inference/llama3%EF%BC%8C%E4%BD%BF%E7%94%A8%E8%80%85%E8%83%BD%E5%A4%9F%E9%80%9A%E8%BF%87msrun%E5%92%8Cmpirun%E5%BE%88%E6%96%B9%E4%BE%BF%E5%9C%B0%E6%9E%84%E5%BB%BA%E5%A4%9A%E4%B8%AA%E8%8A%82%E7%82%B9%E8%BF%9B%E8%A1%8C%E6%A8%A1%E5%9E%8B%E6%8E%A8%E7%90%86%E3%80%82",[258],[391],{"type":24,"value":392},"https://github.com/mindspore-lab/mindnlp/tree/master/llm/inference/llama3，使用者能够通过msrun和mpirun很方便地构建多个节点进行模型推理。",{"type":18,"tag":26,"props":394,"children":395},{},[396],{"type":18,"tag":30,"props":397,"children":398},{},[399],{"type":24,"value":400},"Baseline解读",{"type":18,"tag":26,"props":402,"children":403},{},[404],{"type":18,"tag":30,"props":405,"children":406},{},[407],{"type":24,"value":408},"步骤1：更新或安装所需环境",{"type":18,"tag":361,"props":410,"children":412},{"code":411},"!pip install --upgrade modelscope requests urllib3 tqdm pandas mindspore mindnlp\n!apt update > /dev/null; apt install aria2 git-lfs axel -y > /dev/null\n",[413],{"type":18,"tag":366,"props":414,"children":415},{"__ignoreMap":7},[416],{"type":24,"value":411},{"type":18,"tag":268,"props":418,"children":419},{},[420,425,430,435,440,445],{"type":18,"tag":272,"props":421,"children":422},{},[423],{"type":24,"value":424},"pip install --upgrade: 这个命令用于升级已安装的Python包到最新版本。--upgrade选项告诉pip检查并安装最新版本的指定包。",{"type":18,"tag":272,"props":426,"children":427},{},[428],{"type":24,"value":429},"modelscope: ModelScope 是一个由阿里巴巴达摩院开源的模型即服务（MaaS）平台，旨在简化机器学习模型的使用流程，提供多种预训练模型，涵盖计算机视觉、自然语言处理、语音识别等多个领域。它集成了众多开源AI模型，涵盖了多个领域，开发者可以轻松找到满足自己需求的模型。ModelScope，开发者只需一行代码即可调用AI模型，极大地简化了模型调用过程。用户可以通过SDK或者WEB端的方式上传数据集，通过ModelScope或者公开Host托管。这是国内最大的大模型托管社区，类比为国内版hugging face.在这次代码中用来导入和运行大模型。",{"type":18,"tag":272,"props":431,"children":432},{},[433],{"type":24,"value":434},"requests: Python的requests包是一个非常流行的HTTP请求库，广泛用于网络爬虫、API交互等场景。它简化了HTTP请求的复杂性，提供了简洁而强大的API，使得开发者可以轻松地发送HTTP请求并处理响应。",{"type":18,"tag":272,"props":436,"children":437},{},[438],{"type":24,"value":439},"urllib3: urllib3 是一个功能强大且易于使用的 Python HTTP 客户端库，广泛应用于 Python 生态系统中。它提供了许多 Python 标准库 urllib 所不具备的重要特性，如线程安全、连接池管理、客户端 SSL/TLS 验证、文件分部编码上传、自动重试、支持压缩编码、支持 HTTP 和 SOCKS 代理等",{"type":18,"tag":272,"props":441,"children":442},{},[443],{"type":24,"value":444},"tqdm: tqdm是一个快速、可扩展的Python进度条库，广泛用于在Python长循环中添加进度提示信息。它可以帮助用户监测程序运行的进度，估计运行时长，并且在调试时也非常有用。tqdm的主要功能是通过封装任意的迭代器来显示进度条，用户只需在循环中使用tqdm(iterator)即可。这次代码中是用来做进度条的。",{"type":18,"tag":272,"props":446,"children":447},{},[448],{"type":24,"value":449},"pandas: Pandas 是一个强大的 Python 数据分析工具包，广泛应用于数据科学和数据分析领域。它提供了高效、灵活且易于使用的数据结构，旨在简化数据处理和分析任务。",{"type":18,"tag":26,"props":451,"children":452},{},[453],{"type":24,"value":454},"在这次代码中发挥了以下作用",{"type":18,"tag":26,"props":456,"children":457},{},[458],{"type":24,"value":459},"**数据导入/导出：**支持从多种文件格式（如 CSV、Excel、SQL、JSON 等）导入和导出数据。",{"type":18,"tag":26,"props":461,"children":462},{},[463],{"type":24,"value":464},"**数据清洗：**提供丰富的函数和方法来处理缺失数据、重复数据和异常值。",{"type":18,"tag":268,"props":466,"children":467},{},[468,473,478,483,488,493],{"type":18,"tag":272,"props":469,"children":470},{},[471],{"type":24,"value":472},"apt update: apt update 是一个用于更新软件包列表的命令，它在 Debian 和 Ubuntu 系统中广泛使用。这个命令的主要功能是从远程软件仓库获取最新的软件包元数据，并更新本地的软件包数据库。通过执行 apt update，系统可以确保在安装或升级软件包时，使用的是最新的可用版本。",{"type":18,"tag":272,"props":474,"children":475},{},[476],{"type":24,"value":477},"/dev/null: 这个操作符将命令的输出重定向到/dev/null，即丢弃输出。这样可以避免在终端中显示更新过程中的详细信息。",{"type":18,"tag":272,"props":479,"children":480},{},[481],{"type":24,"value":482},"apt install aria2 git-lfs axel -y: 这个命令用于安装指定的软件包。-y选项表示自动确认安装，不需要用户输入确认信息。",{"type":18,"tag":272,"props":484,"children":485},{},[486],{"type":24,"value":487},"aria2: Aria2 是一个轻量级的多协议、多源命令行下载工具，支持 HTTP/HTTPS、FTP、SFTP、BitTorrent 和 Metalink 协议。它可以通过内置的 JSON-RPC 和 XML-RPC 接口进行操作，非常适合用于批量下载和管理下载任务。",{"type":18,"tag":272,"props":489,"children":490},{},[491],{"type":24,"value":492},"git-lfs: Git LFS（Large File Storage）是一个Git扩展，专门用于处理大型文件，如音频、视频、图像或任何其他二进制大文件。它通过将这些大文件存储在外部系统而不是Git仓库本身来优化性能，从而显著减小了Git仓库的大小，同时也保留了对大文件的版本控制能力。",{"type":18,"tag":272,"props":494,"children":495},{},[496],{"type":24,"value":497},"axel: Python包之axel是一个用于加速文件下载的工具，它通过同时下载文件的不同部分并合并它们来提高下载速度。这个包是Axel命令行工具的Python实现，旨在帮助用户通过多线程下载来加速文件传输。",{"type":18,"tag":26,"props":499,"children":500},{},[501],{"type":18,"tag":30,"props":502,"children":503},{},[504],{"type":24,"value":505},"步骤2：下载数据集",{"type":18,"tag":361,"props":507,"children":509},{"code":508},"!axel -n 12 -a https://ai-contest-static.xfyun.cn/2024/%E5%A4%A7%E6%A8%A1%E5%9E%8B%E8%83%BD%E5%8A%9B%E8%AF%84%E6%B5%8B%EF%BC%9A%E4%B8%AD%E6%96%87%E6%88%90%E8%AF%AD%E9%87%8A%E4%B9%89%E4%B8%8E%E8%A7%A3%E6%9E%90%E6%8C%91%E6%88%98%E8%B5%9B/test_input.csv\n",[510],{"type":18,"tag":366,"props":511,"children":512},{"__ignoreMap":7},[513],{"type":24,"value":508},{"type":18,"tag":26,"props":515,"children":516},{},[517],{"type":24,"value":518},"下载数据集文件“test_input.csv”也可以从代码仓获取再手动上传。",{"type":18,"tag":26,"props":520,"children":521},{},[522],{"type":18,"tag":30,"props":523,"children":524},{},[525],{"type":24,"value":526},"步骤3：构建模型",{"type":18,"tag":361,"props":528,"children":530},{"code":529},"import mindspore\nfrom mindnlp.transformers import AutoTokenizer, AutoModelForCausalLM\n\nmodel_id = \"LLM-Research/Meta-Llama-3-8B-Instruct\"\n\ntokenizer = AutoTokenizer.from_pretrained(model_id, mirror='modelscope')\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    ms_dtype=mindspore.float16,\n    mirror='modelscope'\n)\n\nmessages = [\n    {\"role\": \"system\", \"content\": \"You are a pirate chatbot who always responds in pirate speak!\"},\n    {\"role\": \"user\", \"content\": \"Who are you?\"},\n]\n\ninput_ids = tokenizer.apply_chat_template(\n    messages,\n    add_generation_prompt=True,\n    return_tensors=\"ms\"\n)\n\nterminators = [\n    tokenizer.eos_token_id,\n    tokenizer.convert_tokens_to_ids(\"\u003C|eot_id|>\")\n]\n\noutputs = model.generate(\n    input_ids,\n    max_new_tokens=50,\n    eos_token_id=terminators,\n    # do_sample=False,\n    do_sample=True,\n    temperature=0.6,\n    top_p=0.9,\n)\nresponse = outputs[0][input_ids.shape[-1]:]\nprint(tokenizer.decode(response, skip_special_tokens=True))\n",[531],{"type":18,"tag":366,"props":532,"children":533},{"__ignoreMap":7},[534],{"type":24,"value":529},{"type":18,"tag":26,"props":536,"children":537},{},[538],{"type":24,"value":539},"导入mindnlp.transformers基于Modelarts提供的NPU环境进行高效推理:",{"type":18,"tag":26,"props":541,"children":542},{},[543],{"type":24,"value":544},"1、使用AutoTokenizer导入模型Id和魔搭镜像，使用AutoModelForCausalLM规定模型Id、镜像和数据类型。",{"type":18,"tag":26,"props":546,"children":547},{},[548],{"type":24,"value":549},"2、在messages类中规定系统提示词，并封装为输入提供给模型。",{"type":18,"tag":26,"props":551,"children":552},{},[553],{"type":24,"value":554},"3、经过input_ids、terminators、outputs的传递，打印解码后的response。",{"type":18,"tag":26,"props":556,"children":557},{},[558],{"type":24,"value":559},"4、得到一个针对\"Who are you?\"的回答，确认模型构建成功。",{"type":18,"tag":561,"props":562,"children":563},"h2",{"id":7},[],{"type":18,"tag":26,"props":565,"children":566},{},[567],{"type":18,"tag":30,"props":568,"children":569},{},[570],{"type":18,"tag":30,"props":571,"children":572},{},[573],{"type":24,"value":574},"步骤4：读取数据集",{"type":18,"tag":26,"props":576,"children":577},{},[578],{"type":18,"tag":72,"props":579,"children":581},{"alt":7,"src":580},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/02/21/774de518c1414e79a42c2596a7fd5c0d.png",[],{"type":18,"tag":361,"props":583,"children":585},{"code":584},"from tqdm import tqdm\nimport os\n\n\ni = 1\n# 假设 test 是一个 DataFrame\n# 遍历测试数据集的第一项的值，目的是生成与给定句子最相关的五个成语\nfor test_prompt in tqdm(test[0].values, total=len(test[0].values), desc=\"处理进度\"):\n    i = i + 1\n    # 构造提示信息，要求模型输出与句子最相关的五个成语\n    prompt = f\"列举与下面句子最符合的五个成语。只需要输出五个成语，不需要有其他的输出，写在一行中：{test_prompt}\"\n\n    # 初始化一个长度为5的列表，填充默认成语“同舟共济”\n    words = ['同舟共济'] * 5\n\n    # 构建聊天消息格式，用于提示模型进行生成\n    messages = [\n    {\"role\": \"system\", \"content\": \"You are a helpful chinese teacher.\"},\n    {\"role\": \"user\", \"content\": f\"{prompt}\"},\n    ]\n    # 应用聊天模板对消息进行处理，准备模型输入\n    input_ids = tokenizer.apply_chat_template(\n           messages,\n           add_generation_prompt=True,\n           return_tensors=\"ms\"\n    )\n    # 对输入文本进行编码，准备模型输入数据\n    terminators = [\n    tokenizer.eos_token_id,\n    tokenizer.convert_tokens_to_ids(\"\u003C|eot_id|>\")\n    ]\n   \n    # 生成回答，限制最大生成长度\n    outputs = model.generate(\n    input_ids,\n    max_new_tokens=100,\n    eos_token_id=terminators,\n    num_beams=5,\n    no_repeat_ngram_size=2,\n    num_return_sequences=5,\n    do_sample=False,\n    #length_penalty=1.0,\n    )\n    # 提取模型输出，去除输入部分\n    response = outputs[0][input_ids.shape[-1]:]\n   \n    # 解码模型输出，去除特殊标记\n    response = tokenizer.decode(response, skip_special_tokens=True)\n   \n    # 清理回答文本，确保格式统一\n    response = response.replace('\\n', ' ').replace('、', ' ')\n    # 提取回答中的成语，确保每个成语长度为4且非空\n    words = [x for x in response.split() if len(x) == 4 and x.strip() != '']\n   \n   \n\n    # 如果生成的成语列表长度不满足要求（即20个字符），则使用默认成语列表\n   #if len(' '.join(words).strip()) != 24:\n       # words = ['同舟共济'] * 5\n    while True:\n        text = ' '.join(words).strip()\n        if len(text) \u003C 24:\n            words.append('同舟共济')\n        else:\n            break\n\n    # 将最终的成语列表写入提交文件\n    with open('submit.csv', 'a+', encoding='utf-8') as up:\n        up.write(' '.join(words) + '\\n')\n\n   \n    # 查看阶段性结果\n    if i % 50 == 0:\n        tqdm.write(f\"大模型第{i}次返回的结果是：\\n   {response}\\n\")\n        tqdm.write(f\"submit.cvs第{i}行输出结果：\\n   {words}\\n\")\n   \n    # 为了尽快拿到结果，我们暂时仅获得500个结果（如果有时间的话，可以删除这两行）\n    if i == 2973:\n        break\n\nprint('submit.csv 已生成')\n",[586],{"type":18,"tag":366,"props":587,"children":588},{"__ignoreMap":7},[589],{"type":24,"value":584},{"type":18,"tag":26,"props":591,"children":592},{},[593],{"type":24,"value":594},"1、使用test_prompt在每一个循环中从test列表中获取一个成语语义描述；",{"type":18,"tag":26,"props":596,"children":597},{},[598],{"type":24,"value":599},"2、从test_prompt中获取成语表述，以更新每个循环提交给模型的prompt；",{"type":18,"tag":26,"props":601,"children":602},{},[603],{"type":24,"value":604},"3、利用构建成功的模型获得输出response；",{"type":18,"tag":26,"props":606,"children":607},{},[608],{"type":24,"value":609},"4、解码并清理response，除去标点符号等，提取成语填充进words的一行中；",{"type":18,"tag":26,"props":611,"children":612},{},[613],{"type":24,"value":614},"5、判断words的一行中成语是否够5个，不足的就用‘同舟共济’补足；",{"type":18,"tag":26,"props":616,"children":617},{},[618],{"type":24,"value":619},"6、讲这一行5个成语写入'submit.csv'中，并开启下一个循环，直到循环结束。",{"type":18,"tag":26,"props":621,"children":622},{},[623],{"type":18,"tag":30,"props":624,"children":625},{},[626],{"type":24,"value":627},"单卡推理脚本",{"type":18,"tag":361,"props":629,"children":631},{"code":630},"# llama3-8b-instruct.py\n\n# 安装依赖 Terminal 中执行\n# pip install --upgrade modelscope requests urllib3 tqdm pandas mindspore mindnlp\n# pip uninstall mindformers\n# Modelarts中可以不执行此句\n#!apt update > /dev/null; apt install aria2 git-lfs axel -y > /dev/null\n\nimport mindspore\nfrom mindnlp.transformers import AutoTokenizer, AutoModelForCausalLM\n\nmodel_id = \"LLM-Research/Meta-Llama-3-8B-Instruct\"\n\ntokenizer = AutoTokenizer.from_pretrained(model_id, mirror='modelscope')\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    ms_dtype=mindspore.float16,\n    mirror='modelscope'\n)\n\nmessages = [\n    {\"role\": \"system\", \"content\": \"You are a pirate chatbot who always responds in pirate speak!\"},\n    {\"role\": \"user\", \"content\": \"Who are you?\"},\n]\n\ninput_ids = tokenizer.apply_chat_template(\n    messages,\n    add_generation_prompt=True,\n    return_tensors=\"ms\"\n)\n\nterminators = [\n    tokenizer.eos_token_id,\n    tokenizer.convert_tokens_to_ids(\"\u003C|eot_id|>\")\n]\n\noutputs = model.generate(\n    input_ids,\n    max_new_tokens=50,\n    eos_token_id=terminators,\n    # do_sample=False,\n    do_sample=True,\n    temperature=0.6,\n    top_p=0.9,\n)\nresponse = outputs[0][input_ids.shape[-1]:]\nprint(tokenizer.decode(response, skip_special_tokens=True))\n\nimport pandas as pd\ntest = pd.read_csv('./test_input.csv', header=None)\n\nfrom tqdm import tqdm\nimport os\n\n\ni = 1\n# 假设 test 是一个 DataFrame\n# 遍历测试数据集的第一项的值，目的是生成与给定句子最相关的五个成语\nfor test_prompt in tqdm(test[0].values, total=len(test[0].values), desc=\"处理进度\"):\n    i = i + 1\n    # 构造提示信息，要求模型输出与句子最相关的五个成语\n    prompt = f\"列举与下面句子最符合的五个成语。只需要输出五个成语，不需要有其他的输出，写在一行中：{test_prompt}\"\n\n    # 初始化一个长度为5的列表，填充默认成语“同舟共济”\n    words = ['同舟共济'] * 5\n\n    # 构建聊天消息格式，用于提示模型进行生成\n    messages = [\n    {\"role\": \"system\", \"content\": \"You are a helpful chinese teacher.\"},\n    {\"role\": \"user\", \"content\": f\"{prompt}\"},\n    ]\n    # 应用聊天模板对消息进行处理，准备模型输入\n    input_ids = tokenizer.apply_chat_template(\n           messages,\n           add_generation_prompt=True,\n           return_tensors=\"ms\"\n    )\n    # 对输入文本进行编码，准备模型输入数据\n    terminators = [\n    tokenizer.eos_token_id,\n    tokenizer.convert_tokens_to_ids(\"\u003C|eot_id|>\")\n    ]\n   \n    # 生成回答，限制最大生成长度\n    outputs = model.generate(\n    input_ids,\n    max_new_tokens=100,\n    eos_token_id=terminators,\n    no_repeat_ngram_size=2,\n    num_beams=5,\n    num_return_sequences=5,\n    do_sample=False,\n    remove_invalid_values=True,\n    #temperature=0.6,\n    #top_p=0.9,\n    #top_k=50,\n    #length_penalty=1.0,\n    )\n    # 提取模型输出，去除输入部分\n    response = outputs[0][input_ids.shape[-1]:]\n   \n    # 解码模型输出，去除特殊标记\n    response = tokenizer.decode(response, skip_special_tokens=True)\n   \n    # 清理回答文本，确保格式统一\n    response = response.replace('\\n', ' ').replace('、', ' ')\n    # 提取回答中的成语，确保每个成语长度为4且非空\n    words = [x for x in response.split() if len(x) == 4 and x.strip() != '']\n   \n   \n\n    # 如果生成的成语列表长度不满足要求（即20个字符），则使用默认成语列表\n   #if len(' '.join(words).strip()) != 24:\n       # words = ['同舟共济'] * 5\n    while True:\n        text = ' '.join(words).strip()\n        if len(text) \u003C 24:\n            words.append('同舟共济')\n        else:\n            break\n\n    # 将最终的成语列表写入提交文件\n    with open('submit.csv', 'a+', encoding='utf-8') as up:\n        up.write(' '.join(words) + '\\n')\n\n   \n    # 查看阶段性结果\n    if i % 50 == 0:\n        tqdm.write(f\"大模型第{i}次返回的结果是：\\n   {response}\\n\")\n        tqdm.write(f\"submit.cvs第{i}行输出结果：\\n   {words}\\n\")\n   \n    # 完整的循环数为2973，如果想要测试，可以设置为10\n    if i == 2973:\n        break\n\nprint('submit.csv 已生成')\n",[632],{"type":18,"tag":366,"props":633,"children":634},{"__ignoreMap":7},[635],{"type":24,"value":630},{"type":18,"tag":26,"props":637,"children":638},{},[639],{"type":18,"tag":30,"props":640,"children":641},{},[642],{"type":24,"value":643},"分布式推理脚本",{"type":18,"tag":26,"props":645,"children":646},{},[647],{"type":24,"value":648},"使用动态组网，自行定义节点数量和主端口，拉起分布式任务。",{"type":18,"tag":361,"props":650,"children":652},{"code":651},"msrun --worker_num=2 --local_worker_num=2 --master_port=8118 --join=True llama3-8b-instruct-distributed.py\n",[653],{"type":18,"tag":366,"props":654,"children":655},{"__ignoreMap":7},[656],{"type":24,"value":651},{"type":18,"tag":26,"props":658,"children":659},{},[660],{"type":24,"value":661},"或者使用MPI组网。",{"type":18,"tag":361,"props":663,"children":665},{"code":664},"mpirun -n 2 python llama3-8b-instruct-distributed.py\n",[666],{"type":18,"tag":366,"props":667,"children":668},{"__ignoreMap":7},[669],{"type":24,"value":664},{"type":18,"tag":26,"props":671,"children":672},{},[673],{"type":24,"value":674},"导入mindspore.communication库的Init类，并使用init()初始化计算实例，让代码在多个节点中运行。",{"type":18,"tag":361,"props":676,"children":678},{"code":677},"# llama3-8b-instruct-distributed.py\n\n# 安装依赖 Terminal 中执行\n# pip install --upgrade modelscope requests urllib3 tqdm pandas mindspore mindnlp\n# pip uninstall mindformers\n# Modelarts中可以不执行此句\n#!apt update > /dev/null; apt install aria2 git-lfs axel -y > /dev/null\n# msrun --worker_num=2 --local_worker_num=2 --master_port=8118 --join=True llama3-8b-instruct-distributed.py\n\nimport mindspore\nfrom mindspore.communication import init\nfrom mindnlp.transformers import AutoTokenizer, AutoModelForCausalLM\n\nmodel_id = \"LLM-Research/Meta-Llama-3-8B-Instruct\"\n\ninit()\ntokenizer = AutoTokenizer.from_pretrained(model_id, mirror='modelscope')\nmodel = AutoModelForCausalLM.from_pretrained(\n    model_id,\n    ms_dtype=mindspore.float16,\n    mirror='modelscope'\n)\n\nmessages = [\n    {\"role\": \"system\", \"content\": \"You are a pirate chatbot who always responds in pirate speak!\"},\n    {\"role\": \"user\", \"content\": \"Who are you?\"},\n]\n\ninput_ids = tokenizer.apply_chat_template(\n    messages,\n    add_generation_prompt=True,\n    return_tensors=\"ms\"\n)\n\nterminators = [\n    tokenizer.eos_token_id,\n    tokenizer.convert_tokens_to_ids(\"\u003C|eot_id|>\")\n]\n\noutputs = model.generate(\n    input_ids,\n    max_new_tokens=50,\n    eos_token_id=terminators,\n    # do_sample=False,\n    do_sample=True,\n    temperature=0.6,\n    top_p=0.9,\n)\nresponse = outputs[0][input_ids.shape[-1]:]\nprint(tokenizer.decode(response, skip_special_tokens=True))\n\nimport pandas as pd\ntest = pd.read_csv('./test_input.csv', header=None)\n\nfrom tqdm import tqdm\nimport os\n\n\ni = 1\n# 假设 test 是一个 DataFrame\n# 遍历测试数据集的第一项的值，目的是生成与给定句子最相关的五个成语\nfor test_prompt in tqdm(test[0].values, total=len(test[0].values), desc=\"处理进度\"):\n    i = i + 1\n    # 构造提示信息，要求模型输出与句子最相关的五个成语\n    prompt = f\"列举与下面句子最符合的五个成语。只需要输出五个成语，不需要有其他的输出，写在一行中：{test_prompt}\"\n\n    # 初始化一个长度为5的列表，填充默认成语“同舟共济”\n    words = ['同舟共济'] * 5\n\n    # 构建聊天消息格式，用于提示模型进行生成\n    messages = [\n    {\"role\": \"system\", \"content\": \"You are a helpful chinese teacher.\"},\n    {\"role\": \"user\", \"content\": f\"{prompt}\"},\n    ]\n    # 应用聊天模板对消息进行处理，准备模型输入\n    input_ids = tokenizer.apply_chat_template(\n           messages,\n           add_generation_prompt=True,\n           return_tensors=\"ms\"\n    )\n    # 对输入文本进行编码，准备模型输入数据\n    terminators = [\n    tokenizer.eos_token_id,\n    tokenizer.convert_tokens_to_ids(\"\u003C|eot_id|>\")\n    ]\n   \n    # 生成回答，限制最大生成长度\n    outputs = model.generate(\n    input_ids,\n    max_new_tokens=100,\n    eos_token_id=terminators,\n    num_beams=5,\n    no_repeat_ngram_size=2,\n    num_return_sequences=5,\n    do_sample=False,\n    #length_penalty=1.0,\n    )\n    # 提取模型输出，去除输入部分\n    response = outputs[0][input_ids.shape[-1]:]\n   \n    # 解码模型输出，去除特殊标记\n    response = tokenizer.decode(response, skip_special_tokens=True)\n   \n    # 清理回答文本，确保格式统一\n    response = response.replace('\\n', ' ').replace('、', ' ')\n    # 提取回答中的成语，确保每个成语长度为4且非空\n    words = [x for x in response.split() if len(x) == 4 and x.strip() != '']\n   \n   \n\n    # 如果生成的成语列表长度不满足要求（即20个字符），则使用默认成语列表\n   #if len(' '.join(words).strip()) != 24:\n       # words = ['同舟共济'] * 5\n    while True:\n        text = ' '.join(words).strip()\n        if len(text) \u003C 24:\n            words.append('同舟共济')\n        else:\n            break\n\n    # 将最终的成语列表写入提交文件\n    with open('submit.csv', 'a+', encoding='utf-8') as up:\n        up.write(' '.join(words) + '\\n')\n\n   \n    # 查看阶段性结果\n    if i % 50 == 0:\n        tqdm.write(f\"大模型第{i}次返回的结果是：\\n   {response}\\n\")\n        tqdm.write(f\"submit.cvs第{i}行输出结果：\\n   {words}\\n\")\n   \n    # 完整的循环数为2973，如果想要测试，可以设置为10\n    if i == 2973:\n        break\n\nprint('submit.csv 已生成')                            |\n",[679],{"type":18,"tag":366,"props":680,"children":681},{"__ignoreMap":7},[682],{"type":24,"value":677},{"type":18,"tag":159,"props":684,"children":686},{"id":685},"参考文章",[687],{"type":18,"tag":30,"props":688,"children":689},{},[690],{"type":24,"value":685},{"type":18,"tag":26,"props":692,"children":693},{},[694,696],{"type":24,"value":695},"[1] ",{"type":18,"tag":254,"props":697,"children":700},{"href":698,"rel":699},"https://blog.csdn.net/qq%5C_41185868/article/details/137981416",[258],[701],{"type":24,"value":702},"https://blog.csdn.net/qq\\_41185868/article/details/137981416",{"type":18,"tag":26,"props":704,"children":705},{},[706,707],{"type":24,"value":695},{"type":18,"tag":254,"props":708,"children":711},{"href":709,"rel":710},"https://www.dongaigc.com/p/meta-llama/Meta-Llama-3-8B-Instruct",[258],[712],{"type":24,"value":709},{"title":7,"searchDepth":714,"depth":714,"links":715},4,[716,718,719],{"id":161,"depth":717,"text":161},3,{"id":204,"depth":717,"text":204},{"id":7,"depth":720,"text":7,"children":721},2,[722],{"id":685,"depth":717,"text":685},"markdown","content:technology-blogs:zh:3615.md","content","technology-blogs/zh/3615.md","technology-blogs/zh/3615","md",1776506132326]