中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁(yè) > news >正文

食品包裝設(shè)計(jì)價(jià)格seo崗位工資

食品包裝設(shè)計(jì)價(jià)格,seo崗位工資,wordpress 側(cè)邊欄浮動(dòng),上海網(wǎng)站建設(shè)制作百橙前言 在大模型的生成過(guò)程中,部分原生的大語(yǔ)言模型未經(jīng)過(guò)特殊的對(duì)齊訓(xùn)練,往往會(huì)“胡說(shuō)八道”的生成一些敏感詞語(yǔ)等用戶不想生成的詞語(yǔ),最簡(jiǎn)單粗暴的方式就是在大模型生成的文本之后,添加敏感詞庫(kù)等規(guī)則手段進(jìn)行敏感詞過(guò)濾&#xf…

前言

在大模型的生成過(guò)程中,部分原生的大語(yǔ)言模型未經(jīng)過(guò)特殊的對(duì)齊訓(xùn)練,往往會(huì)“胡說(shuō)八道”的生成一些敏感詞語(yǔ)等用戶不想生成的詞語(yǔ),最簡(jiǎn)單粗暴的方式就是在大模型生成的文本之后,添加敏感詞庫(kù)等規(guī)則手段進(jìn)行敏感詞過(guò)濾,但是在生成過(guò)程中,生成敏感詞仍然耗費(fèi)了時(shí)間和算力成本。

本文以chatglm2-6B為例,通過(guò)自定義LogitsProcessor,實(shí)踐大模型在生成過(guò)程中控制一些詞語(yǔ)的生成。

LogitsProcessor

從下面代碼可以看到,LogitsProcessor的作用就是在生成過(guò)程中修改score,改變模型輸出的概率分布的工具。

class LogitsProcessor:"""Abstract base class for all logit processors that can be applied during generation."""@add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:raise NotImplementedError(f"{self.__class__} is an abstract class. Only classes inheriting this class can be called.")class LogitsProcessorList(list):"""This class can be used to create a list of [`LogitsProcessor`] or [`LogitsWarper`] to subsequently process a`scores` input tensor. This class inherits from list and adds a specific *__call__* method to apply each[`LogitsProcessor`] or [`LogitsWarper`] to the inputs."""def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.FloatTensor:r"""Args:input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):Prediction scores of a language modeling head. These can be logits for each vocabulary when not usingbeam search or log softmax for each vocabulary token when using beam searchkwargs (`Dict[str, Any]`, *optional*):Additional kwargs that are specific to a logits processor.Return:`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`:The processed prediction scores."""for processor in self:function_args = inspect.signature(processor.__call__).parametersif len(function_args) > 2:if not all(arg in kwargs for arg in list(function_args.keys())[2:]):raise ValueError(f"Make sure that all the required parameters: {list(function_args.keys())} for "f"{processor.__class__} are passed to the logits processor.")scores = processor(input_ids, scores, **kwargs)else:scores = processor(input_ids, scores)return scores

自定義LogitsProcessor實(shí)踐

回到正題,如何自定義LogitsProcessor控制大模型生成的過(guò)程呢?下面直接上實(shí)踐代碼:

class new_logits_processor(LogitsProcessor):def __init__(self, forbid_token_id_list: List[int] = None):self.forbid_token_id_list = forbid_token_id_listdef __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:for id_ in self.forbid_token_id_list:scores[:, id_] = -float('inf')return scores

forbid_token_id_list是不讓模型生成詞語(yǔ)的id映射列表,對(duì)于這些抑制生成的詞語(yǔ),在自定義logits_processor時(shí)將其概率推向負(fù)無(wú)窮大即可。

chatglm2-6B詳細(xì)實(shí)踐代碼:

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, TextStreamer
from transformers.generation.logits_process import LogitsProcessor, LogitsProcessorList
from typing import List
import torchclass new_logits_processor(LogitsProcessor):def __init__(self, forbid_token_id_list: List[int] = None):self.forbid_token_id_list = forbid_token_id_listdef __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:for id_ in self.forbid_token_id_list:scores[:, id_] = -float('inf')return scoresmodel_path = "THUDM/chatglm2-6b"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForSeq2SeqLM.from_pretrained(model_path, trust_remote_code=True).to('mps')def add_forbid_words():'''添加需要抑制的詞語(yǔ),這里簡(jiǎn)單添加了數(shù)字和幾個(gè)詞語(yǔ)進(jìn)行對(duì)比:return:list'''forbid_words = []for i in range(10):forbid_words.append(tokenizer.convert_tokens_to_ids(str(i)))forbid_words.append(tokenizer.convert_tokens_to_ids("首先"))forbid_words.append(tokenizer.convert_tokens_to_ids("積極"))forbid_words.append(tokenizer.convert_tokens_to_ids("回答"))forbid_words.append(tokenizer.convert_tokens_to_ids("勇敢"))forbid_words.append(tokenizer.convert_tokens_to_ids("勇氣"))return forbid_wordslogits_processor = LogitsProcessorList()
logits_processor.append(new_logits_processor(add_forbid_words()))streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)input = "列舉出10個(gè)積極的詞語(yǔ):"outputs = model.generate(tokenizer(input, return_tensors='pt').input_ids.to("mps"),max_new_tokens=1024,logits_processor=logits_processor,  # 不開(kāi)啟注釋即可streamer=streamer
)
decode_text = tokenizer.batch_decode(outputs, streamer=streamer)[0]
print(decode_text)

抑制前輸出:

1. 勇敢
2. 快樂(lè)
3. 成功
4. 努力
5. 積極
6. 樂(lè)觀
7. 自信
8. 開(kāi)朗
9. 團(tuán)結(jié)
10. 奮斗

抑制后輸出:

- 積極主動(dòng)
- 樂(lè)觀向上
- 自信
- 自律
- 誠(chéng)實(shí)守信
- 樂(lè)于助人
- 勇于嘗試
- 堅(jiān)韌不拔
- 樂(lè)觀開(kāi)朗
- 團(tuán)結(jié)一心

小結(jié)

本文通過(guò)自定義LogitsProcessor,簡(jiǎn)單的實(shí)踐了大語(yǔ)言模型在生成過(guò)程中屏蔽生成用戶自定義詞語(yǔ)的trick。在現(xiàn)實(shí)場(chǎng)景中,根據(jù)特定場(chǎng)景探索如何靈活的利用LogitsProcessor進(jìn)行有針對(duì)性的控制生成模型的生成過(guò)程非常重要。

參考文獻(xiàn)

【1】https://github.com/huggingface/transformers/blob/v4.31.0/src/transformers/generation/logits_process.py

http://www.risenshineclean.com/news/22828.html

相關(guān)文章:

  • 做網(wǎng)站用windows和 linux廣州網(wǎng)絡(luò)推廣公司有哪些
  • 企業(yè)網(wǎng)站建設(shè)論文糕點(diǎn)烘焙專業(yè)培訓(xùn)學(xué)校
  • 網(wǎng)站域名免費(fèi)申請(qǐng)網(wǎng)站排名優(yōu)化培訓(xùn)哪家好
  • 做 愛(ài) 網(wǎng)站小視頻下載查詢網(wǎng)官網(wǎng)
  • 中石化第五建設(shè)有限公司官方網(wǎng)站濰坊關(guān)鍵詞優(yōu)化平臺(tái)
  • wordpress商家展示主題企業(yè)網(wǎng)站的優(yōu)化建議
  • 社區(qū)工作者優(yōu)化設(shè)計(jì)方法
  • 保定市住房和城鄉(xiāng)建設(shè)局網(wǎng)站競(jìng)價(jià)廣告點(diǎn)擊軟件
  • 武漢黃浦醫(yī)院網(wǎng)站建設(shè)關(guān)鍵詞優(yōu)化排名平臺(tái)
  • 獨(dú)立做網(wǎng)站需要學(xué)什么條件關(guān)鍵詞優(yōu)化怎么寫(xiě)
  • 做代購(gòu)注冊(cè)什么網(wǎng)站搜索引擎優(yōu)化解釋
  • 臺(tái)州網(wǎng)站開(kāi)發(fā)太原網(wǎng)站優(yōu)化公司
  • 學(xué)會(huì)了vue 能搭建一個(gè)網(wǎng)站平臺(tái)比較靠譜的電商培訓(xùn)機(jī)構(gòu)
  • jsp開(kāi)發(fā)網(wǎng)站百度指數(shù)人群畫(huà)像哪里查詢
  • 網(wǎng)站備案的是域名還是空間電子商務(wù)網(wǎng)站建設(shè)與維護(hù)
  • 搭建網(wǎng)站難嗎電商培訓(xùn)學(xué)校
  • 玉溪做網(wǎng)站的公司seo的優(yōu)化步驟
  • 奪寶網(wǎng)站怎樣做優(yōu)化泰安做百度推廣的公司
  • 網(wǎng)站開(kāi)發(fā)有什么點(diǎn)子軟文生成器
  • 公司主頁(yè)網(wǎng)站怎么做免費(fèi)推廣軟件 推廣幫手
  • 服務(wù)器方面如何規(guī)劃建設(shè)網(wǎng)站外貿(mào)網(wǎng)站有哪些平臺(tái)
  • 政府門(mén)戶網(wǎng)站建設(shè)的基本意義有哪些網(wǎng)絡(luò)營(yíng)銷的概念和特點(diǎn)是什么
  • 網(wǎng)站建設(shè)項(xiàng)目合同如何做好網(wǎng)絡(luò)推廣
  • 網(wǎng)站建設(shè)網(wǎng)站維護(hù)的具體內(nèi)容是什么seo推廣員是做什么的
  • 實(shí)際網(wǎng)站開(kāi)發(fā)怎樣分工2023百度秒收錄技術(shù)
  • 北京環(huán)球影城每日客流量統(tǒng)計(jì)排名優(yōu)化公司口碑哪家好
  • 駐馬店廣告制作公司抖音seo教程
  • 自助建站系統(tǒng)個(gè)人網(wǎng)站怎樣開(kāi)自己的網(wǎng)站
  • 產(chǎn)品網(wǎng)站用什么軟件做百度一下網(wǎng)頁(yè)首頁(yè)
  • 注冊(cè)城鄉(xiāng)規(guī)劃師報(bào)考條件提高seo排名