 與 observe() 的信息載體)
NLP人工智能深度學(xué)習(xí)【免費(fèi)下載鏈接】ParlAIA framework for training and evaluating AI models on a variety of openly available dialogue datasets.項(xiàng)目地址https://gitcode.com/gh_mirrors/pa/ParlAI點(diǎn)擊查看免費(fèi)下載Message 是 ParlAI 中信息流轉(zhuǎn)的核心載體——它是 Agent 與環(huán)境或其他 Agent之間傳遞的 Pythondict子類承載對(duì)話文本、監(jiān)督標(biāo)簽、候選答案、獎(jiǎng)勵(lì)、圖像等所有數(shù)據(jù)。本文以 docs/source/core/messages.md 為骨架結(jié)合parlai/core/message.py及教師Teacher、世界World、Torch Agent 的源碼實(shí)現(xiàn)系統(tǒng)講解 Message 的標(biāo)準(zhǔn)字段、可變性保護(hù)機(jī)制、擴(kuò)展字段約定與底層原理幫助你正確編寫任務(wù) Teacher、理解訓(xùn)練/評(píng)估數(shù)據(jù)流并為模型做多任務(wù)遷移做好準(zhǔn)備。一、Message 是什么Observation 與 Act 的統(tǒng)一載體在 ParlAI 中Agent 與環(huán)境之間的一切交互都以消息Message的形式進(jìn)行。官方文檔將其定義為The primary medium for information flow (messages between agents and the environment) in ParlAI is a Message, a subclass of a pythondictcontaining the actions of an agent (observable by other agents or the environment).即Message 是信息流動(dòng)的主要媒介是一個(gè)dict的子類其中包含某個(gè) Agent 的動(dòng)作action該動(dòng)作可被其他 Agent 或環(huán)境觀察到。ParlAI 中通常把這類消息稱為observation觀察或act動(dòng)作。一個(gè) Message 應(yīng)由 Agent 的act()函數(shù)創(chuàng)建它會(huì)被作為唯一參數(shù)傳遞給另一個(gè) Agent 的observe()函數(shù)。在源碼 parlai/core/agents.py 中Agent基類對(duì)這兩個(gè)方法給出了約定def observe(self, observation): Receive an observation from another agent or the environment. self.observation observation return observation def act(self): Produce an action from the agent. raise NotImplementedError(Must implement act function in your agent)世界的執(zhí)行循環(huán)則負(fù)責(zé)把這二者串起來。以 parlai/core/worlds.py 中的DialogPartnerWorld為例acts[0] agents[0].act() agents[1].observe(validate(acts[0])) acts[1] agents[1].act() agents[0].observe(validate(acts[1]))可以看到Agent 0 的act()產(chǎn)出被validate校驗(yàn)后作為 Agent 1 的observe()輸入反之亦然——這就是 Message 在對(duì)話雙方之間“來回傳遞”的完整閉環(huán)。在MultiAgentDialogWorldparlai/core/worlds.py中每個(gè) Agent 收到的則是自其上次act()以來所有其他 Agent 的動(dòng)作。需要特別說明的是創(chuàng)建自己的任務(wù)時(shí)大多數(shù)字段是可選的。但存在一批標(biāo)準(zhǔn)字段在發(fā)送相應(yīng)類型的數(shù)據(jù)時(shí)應(yīng)當(dāng)使用它們。這樣做的直接收益是在一個(gè)數(shù)據(jù)集上訓(xùn)練好的模型可以很容易地遷移到另一個(gè)任務(wù)甚至進(jìn)行多任務(wù)聯(lián)合訓(xùn)練。二、Message 的可變性保護(hù)force_set與 RuntimeErrorMessage對(duì)象的核心功能是確保 Agent 不會(huì)無意中修改 observation 和 act 中的字段。在 parlai/core/message.py 中Message重寫了dict的__setitem__class Message(dict): def __setitem__(self, key, val): if key in self: raise RuntimeError( Message already contains key {}. If this was intentional, please use the function force_set(key, value)..format(key) ) super().__setitem__(key, val) def force_set(self, key, val): super().__setitem__(key, val)也就是說對(duì)已存在的鍵再次賦值如message[text] new會(huì)拋出RuntimeError若確有需要覆蓋字段必須顯式調(diào)用message.force_set(key, new_value)Message.copy()返回的是同類型的Message對(duì)象type(self)(self)因此復(fù)制品依然保留同樣的寫保護(hù)語義。這一機(jī)制在框架內(nèi)部被廣泛使用。例如教師通過action.force_set(id, self.getID())寫入發(fā)送者 IDparlai/core/teachers.pyTorch Agent 在向量化時(shí)用obs.force_set(text_vec, ...)、obs.force_set(label_original_length, ...)寫入派生字段parlai/core/torch_agent.py——這些都是“字段已存在但需要更新”的典型場景。測試 tests/test_messages.py 直接驗(yàn)證了這一契約message Message() message[text] lol try: message[text] rofl # 期望拋出 RuntimeError except RuntimeError as e: err e assert err is not None, Message allowed override message_copy message.copy() assert type(message_copy) Message, Message did not copy properly另外Message還提供了兩個(gè)與批量訓(xùn)練/服務(wù)化相關(guān)的工具方法parlai/core/message.pypadding_example()構(gòu)造一個(gè)用于 batch padding 的消息含batch_padding: True與episode_done: Trueis_padding()判斷消息是否為 padding 示例json_safe_payload()剝離如metrics等不安全字段后轉(zhuǎn)成普通dict供聊天服務(wù)chat-services、外部庫或 Mephisto 交付使用。三、標(biāo)準(zhǔn)字段逐一詳解1.text最標(biāo)準(zhǔn)的字段text是 observation dict 中最標(biāo)準(zhǔn)的字段包含從一個(gè) Agent 發(fā)送給其他 Agent 的字符串文本。{ text: Hi! How are you?, }在 parlai/core/agents.py 的Agent.respond()便捷方法中可以看到它的核心地位respond()接收一個(gè)字符串或 Message強(qiáng)制要求消息中必須包含text字段否則拋RuntimeError隨后克隆 Agent、調(diào)用observe()act()并返回response[text]。batch_respond()對(duì)批量消息也做了同樣的text字段校驗(yàn)。2.id發(fā)送者的自標(biāo)識(shí)id字段存放發(fā)送者的自我標(biāo)識(shí)字符串。例如任務(wù)會(huì)用它來標(biāo)記任務(wù)名使用--task squad時(shí)發(fā)出的消息id即為squad。在FixedDialogTeacher.process_action()中教師會(huì)統(tǒng)一用action.force_set(id, self.getID())寫入該字段parlai/core/teachers.pygetID()默認(rèn)來自opt.get(task, teacher)parlai/core/teachers.py因此消息的id與任務(wù)名天然對(duì)應(yīng)。3.labels監(jiān)督學(xué)習(xí)的目標(biāo)當(dāng)進(jìn)行監(jiān)督學(xué)習(xí)時(shí)labels字段存放合適的標(biāo)簽。對(duì)許多任務(wù)而言它只有一個(gè)回答但部分?jǐn)?shù)據(jù)集支持多個(gè)正確答案因此該字段應(yīng)是一個(gè)可迭代對(duì)象如 list、tuple而非字符串。{ text: What movies are about ginger rogers?, labels: [Top Hat, Kitty Foyle, The Barkleys of Broadway], }在 Torch Agent 的向量化流程_set_label_vec()parlai/core/torch_agent.py中可以看到若labels存在則優(yōu)先取labels否則取eval_labels當(dāng)標(biāo)簽多于一個(gè)時(shí)會(huì)隨機(jī)挑選一個(gè)用于訓(xùn)練label lbls[0] if len(lbls) 1 else self.random.choice(lbls)。4.eval_labels驗(yàn)證/測試階段的標(biāo)簽在驗(yàn)證validation和測試testing階段labels字段會(huì)被移動(dòng)到eval_labels以防止模型無意中在評(píng)估數(shù)據(jù)上訓(xùn)練。其轉(zhuǎn)換邏輯位于 parlai/core/teachers.pyself.lastY action.get(labels, action.get(eval_labels, None)) if not DatatypeHelper.is_training(self.datatype) and labels in action: # move labels to eval field so not used for training # but this way the model can use the labels for perplexity or loss action action.copy() labels action.pop(labels) if not self.opt.get(hide_labels, False): action[eval_labels] labels保留eval_labels的意義在于模型依然可以利用它計(jì)算模型側(cè)指標(biāo)如困惑度perplexity。Torch Agent 的_set_label_vec()同樣識(shí)別eval_labels并將其向量化為eval_labels_vec供 loss 計(jì)算使用。此外hide_labels選項(xiàng)見 parlai/core/params.py 附近可進(jìn)一步將評(píng)估標(biāo)簽完全隱藏。5.label_candidates排序/打分任務(wù)的候選答案對(duì)于支持排序ranking的任務(wù)label_candidates是一個(gè)可迭代對(duì)象存放數(shù)據(jù)集建議 Agent 可以選擇的候選答案。例如 mnist-qa 任務(wù)提供如下候選見 docs/source/core/messages.mddef label_candidates(self): return [str(x) for x in range(10)] [zero, one, two, three, four, five, six, seven, eight, nine]在實(shí)際代碼中DialogTeacher的act()會(huì)調(diào)用self.label_candidates()來填充該字段parlai/core/teachers.py基于 tab 分隔文本的FbDeprecatedDialogTeacher也支持通過label_candidates:a|b|c語法解析候選并會(huì)校驗(yàn)labels[0]是否出現(xiàn)在候選列表中parlai/core/teachers.py。6.text_candidates模型排序后的候選回復(fù)text_candidates是label_candidates的對(duì)偶字段收到對(duì)方給出的候選標(biāo)簽后模型可以選擇返回一個(gè)可迭代對(duì)象其中按模型認(rèn)為與對(duì)話的相關(guān)性從高到低排序的回復(fù)列表。{ text: Which number is in the image?, label_candidates: [0, 1, 2, ..., nine], text_candidates: [4, four, 0, one, ...], # 模型給出的排序 }這樣教師就可以對(duì)模型的整體排序進(jìn)行打分進(jìn)而計(jì)算hits10、MRR等指標(biāo)。7.episode_done標(biāo)記一次對(duì)話的結(jié)束episode_done標(biāo)志用于標(biāo)記一個(gè) episode會(huì)話/回合組的結(jié)束。ParlAI 中的對(duì)話不一定只有一個(gè)來回許多數(shù)據(jù)集包含多輪交互。單輪示例WikiMovies見 docs/source/core/messages.md{ id: wikimovies, text: what movies are about ginger rogers?, labels: [Top Hat, Kitty Foyle, The Barkleys of Broadway], episode_done: True, }多輪示例bAbI task1k:15同一個(gè) episode 內(nèi)連續(xù)多輪問答前幾輪episode_doneFalse直到最后一個(gè)問題才置為True{ id: babi:task1k:15, text: Cats are afraid of sheep. Sheep are afraid of mice. Wolves are afraid of sheep. Gertrude is a cat. Winona is a cat. Emily is a sheep. Jessica is a cat. Mice are afraid of cats. What is winona afraid of?, labels: [sheep], label_candidates: [wolf, mouse, cat, sheep], episode_done: False, } { id: babi:task1k:15, text: What is jessica afraid of?, labels: [sheep], label_candidates: [wolf, mouse, cat, sheep], episode_done: False, } { id: babi:task1k:15, text: What is gertrude afraid of?, labels: [sheep], label_candidates: [wolf, mouse, cat, sheep], episode_done: False, } { id: babi:task1k:15, text: What is emily afraid of?, labels: [mouse], label_candidates: [wolf, mouse, cat, sheep], episode_done: True, }從實(shí)現(xiàn)看World.episode_done()parlai/core/worlds.py正是依據(jù)消息中的episode_done標(biāo)志來判斷對(duì)話是否結(jié)束從而決定是否進(jìn)行下一輪。8.reward強(qiáng)化學(xué)習(xí)任務(wù)的獎(jiǎng)勵(lì)reward字段供強(qiáng)化學(xué)習(xí)RL任務(wù)在 observation dict 中發(fā)送獎(jiǎng)勵(lì)信號(hào)。{ text: You chose option A., reward: 1.0, }值得注意的是Message中定義了UNSAFE_FIELDS {metrics}parlai/core/message.pyjson_safe_payload()會(huì)剔除這類字段后再交付給外部客戶端——這確保了諸如獎(jiǎng)勵(lì)、指標(biāo)這類可能敏感的字段不會(huì)意外泄露到聊天服務(wù)等下游。9.image多模態(tài)數(shù)據(jù)VQA / Visual Dialogobservation dict 也可以包含圖像。例如 VQA_v2 數(shù)據(jù)集的每個(gè)問題都關(guān)聯(lián)一張圖片。image字段中圖像數(shù)據(jù)的格式取決于--image-mode參數(shù)的設(shè)置默認(rèn)情況下圖像以原始 RGB 像素返回image_mode為raw也可以先用預(yù)訓(xùn)練圖像模型處理只把模型特征放入image字段如resnet/resnext變體甚至可以轉(zhuǎn)換為文本表示以便快速調(diào)試如ascii模式。在 parlai/core/image_featurizers.py 中可以看到模式的解析邏輯self.image_mode opt.get(image_mode, no_image_model) if self.image_mode not in [no_image_model, raw, ascii]: if image_mode not in opt or image_size not in opt: raise RuntimeError(...) if resnet in self.image_mode: ... elif resnext in self.image_mode: ... else: raise RuntimeError(Image mode {} not supported.format(self.image_mode))官方文檔給出的 ascii 調(diào)試示例parlai display_data --task mnist_qa --image-mode ascii其輸出即為一個(gè)完整的含image字段的 observationASCII 字符畫{ text: Which number is in the image?, labels: [4, four], label_candidates: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, zero, one, two, three, four, five, six, seven, eight, nine], episode_done: True, image: ... , }對(duì)應(yīng)的 ASCII 轉(zhuǎn)換邏輯可在_img_to_ascii()parlai/core/image_featurizers.py中找到而raw模式則直接返回 RGB 值parlai/core/image_featurizers.py。四、擴(kuò)展字段Extended Fields任務(wù)自定義元數(shù)據(jù)除了上述標(biāo)準(zhǔn)字段許多數(shù)據(jù)集還會(huì)使用自定義字段來攜帶額外元數(shù)據(jù)。以squad:index任務(wù)為例它在消息中加入了answer_starts記錄答案在文本中的起始字符下標(biāo){ id: squad, text: Architecturally, the school has a Catholic character. Atop the Main Buildings gold dome is a golden statue of the Virgin Mary. ... To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?, labels: [Saint Bernadette Soubirous], episode_done: True, answer_starts: [515], }你可以為任務(wù)添加額外字段以提供任務(wù)特定的元數(shù)據(jù)。但官方文檔明確給出三點(diǎn)警告在特定字段上訓(xùn)練的模型不容易遷移到其他任務(wù)現(xiàn)有模型不會(huì)利用該字段在不同任務(wù)上做多任務(wù)訓(xùn)練會(huì)變得更難實(shí)現(xiàn)。為此ParlAI 默認(rèn)的 SQuAD 任務(wù)并不包含answer_starts而是提供了一個(gè)具備自行查找標(biāo)簽索引能力的模型DrQA。這樣該 Agent 也可以被訓(xùn)練到其他“答案在引言文本中”的任務(wù)上如部分 bAbI 任務(wù)——而這些任務(wù)并不提供answer_starts。這一設(shè)計(jì)思路體現(xiàn)了 ParlAI 的核心哲學(xué)用統(tǒng)一、通用的字段換取模型的跨任務(wù)可遷移性。五、Message 的典型使用路徑從 Teacher 到 Torch Agent綜合以上內(nèi)容一條典型的監(jiān)督學(xué)習(xí)數(shù)據(jù)流如下可用 docs/source/core/teachers.md 與 docs/source/core/torch_agent.md 進(jìn)一步深入Teacher 側(cè)FixedDialogTeacher.act()從數(shù)據(jù)中取出下一條記錄構(gòu)造Message若舊代碼返回普通 dict會(huì)執(zhí)行action Message(action)兜底轉(zhuǎn)換見 parlai/core/teachers.py隨后process_action()用force_set寫入id并在非訓(xùn)練階段把labels改名為eval_labelsparlai/core/teachers.py。World 側(cè)World把 Teacher 的 Message 經(jīng)validate()校驗(yàn)后傳給模型 Agent 的observe()模型act()產(chǎn)出的 Message 再傳回教師用于打分。模型側(cè)TorchAgent.observe()把 Message 中的text/labels/eval_labels向量化為text_vec/labels_vec/eval_labels_vec等派生字段并用force_set安全寫入parlai/core/torch_agent.py。正是因?yàn)閮啥硕甲裱惶讟?biāo)準(zhǔn)字段約定一個(gè)模型才能在不同任務(wù)間自由遷移教師只要產(chǎn)出符合規(guī)范的 Message模型側(cè)無需改動(dòng)即可訓(xùn)練。六、小結(jié)與最佳實(shí)踐字段類型用途備注textstr發(fā)送的文本內(nèi)容最標(biāo)準(zhǔn)字段respond()強(qiáng)制要求idstr發(fā)送者自標(biāo)識(shí)通常為任務(wù)名labelsiterable監(jiān)督訓(xùn)練目標(biāo)訓(xùn)練階段使用eval_labelsiterable驗(yàn)證/測試目標(biāo)由labels自動(dòng)遷移而來防泄漏label_candidatesiterable數(shù)據(jù)集建議的候選答案用于排序任務(wù)text_candidatesiterable模型排序后的候選回復(fù)用于計(jì)算hits10、MRRepisode_donebool標(biāo)記 episode 結(jié)束決定World.episode_done()rewardfloatRL 獎(jiǎng)勵(lì)信號(hào)強(qiáng)化學(xué)習(xí)任務(wù)使用image多變圖像數(shù)據(jù)/特征/ASCII由--image-mode決定格式自定義字段任意任務(wù)特定元數(shù)據(jù)慎用影響模型可遷移性總結(jié)幾條核心實(shí)踐建議遵循標(biāo)準(zhǔn)字段盡量只使用text、labels、label_candidates、episode_done等標(biāo)準(zhǔn)字段這是模型跨任務(wù)遷移和多任務(wù)訓(xùn)練的前提。不要直接覆蓋字段Message 的寫保護(hù)是刻意設(shè)計(jì)確需更新時(shí)顯式調(diào)用force_set()否則將觸發(fā)RuntimeError。區(qū)分訓(xùn)練與評(píng)估讓框架自動(dòng)完成labels→eval_labels的遷移不要自己在 Teacher 中混用也不要在評(píng)估數(shù)據(jù)上訓(xùn)練。慎用擴(kuò)展字段自定義元數(shù)據(jù)如answer_starts只應(yīng)在必要時(shí)添加并清楚其帶來的可遷移性代價(jià)優(yōu)先考慮讓模型自行推斷。多模態(tài)任務(wù)正確配置--image-mode調(diào)試用ascii訓(xùn)練用raw或預(yù)訓(xùn)練特征模式具體取值范圍參考 parlai/core/image_featurizers.py。掌握 Message 的字段契約與底層保護(hù)機(jī)制你就掌握了 ParlAI 中 Agent 通信的“通用語言”——無論編寫新任務(wù)、調(diào)試數(shù)據(jù)流還是訓(xùn)練多任務(wù)模型這都將是貫穿始終的基礎(chǔ)能力。贊分享NLP人工智能深度學(xué)習(xí)【免費(fèi)下載鏈接】ParlAIA framework for training and evaluating AI models on a variety of openly available dialogue datasets.項(xiàng)目地址https://gitcode.com/gh_mirrors/pa/ParlAI點(diǎn)擊查看免費(fèi)下載相關(guān)推薦ParlAI Agent 架構(gòu)全解parlai.core.agents 核心類、消息循環(huán)與加載機(jī)制ParlAI Agent 架構(gòu)全解parlai.core.agents 核心類、消息循環(huán)與加載機(jī)制 導(dǎo)讀 本文聚焦 ParlAI 框架中最核心的模塊之一——NLP人工智能深度學(xué)習(xí)Browser Use 的 Message Manager 深度解析Agent 與 LLM 之間對(duì)話秘書的工作機(jī)制Browser Use 的 Message Manager 深度解析Agent 與 LLM 之間對(duì)話秘書的工作機(jī)制 本教程對(duì)應(yīng) docs/Browser Us人工智能AI 應(yīng)用AI Agent一條指令上崗AI 代理的全自動(dòng)交易路徑一條指令上崗AI 代理的全自動(dòng)交易路徑 人類交易員有券商 AppAI 代理卻長期寄人籬下。 AI Trader 是專為 Claude Code、Open后端前端金融科技AI AgentAI 技能上一篇OpCore Simplify3分鐘完成黑蘋果EFI配置的終極解決方案下一篇100-exercises-to-learn-rust 快速上手新手最省心的 Rust 練習(xí)環(huán)境與 IDE 配置指南創(chuàng)作聲明:本文部分內(nèi)容由AI輔助生成(AIGC),僅供參考