GPT 結束語設計 以nanogpt為例

GPT 結束語設計 以nanogpt為例

目錄

GPT 結束語設計 以nanogpt為例

1、簡述

2、分詞設計

3、結束語斷點


1、簡述

在手搓gpt的時候,可能會遇到一些性能問題,即關于是否需要全部輸出或者怎么節約資源。

在輸出語句被max_new_tokens 限制,如果出現一些輸出句子比較長,就會被限制,但如果是設計時候沒有設計結束語,就會出現全部輸出的問題。

如果只需要一部分的語句,或者是某一些特定的場景設計,例如:

1、gpt自動化操作

2、輸出美觀

3、一些較小的業務場景,特定處理的業務

以上的業務場景都是設計的時候為特定模型,即小大模型,通常不需要較大的參數,所以在設計時候如果考慮到輕量化和小型化,參數1M至100M之間的小大模型。

基于成本和開發快速考慮,可以使用nanogpt用于訓練和開發,然后再進一步的微調迭代,所需要的性能和效果基本可以滿足部分要求,迭代速度較快,適合單人或小團隊開發特定場景。


2、分詞設計

以下是關于之前做過的一個開發場景:音樂生成按鍵的場景

分詞中加入了end的作為特定的結束語,如果后續擴展可以通過end前后設計一些音樂風格的標識符,這樣通過風格的標識來達到風格的統一。


# 自定義詞典
word_dict = set(['\n', ' ', '+', '.', '0', '1', '2', '3', '4'
? ? ? ? ?'6', '7', '8', '9', ':', "'a'", "'b'", "'c'", "'d'",
? ? ? ? ?"'e'", "'f'", "'g'", "'h'","'j'", "'n'","'m'","'q'","'w'","'r'","'t'","'y'","'u'",
? ? ? ? "'s'", "'v'", "'x'", "'z'",'<96>','<97>','<98>','<99>','<100>',
? ? ? ? '<101>','<102>','<103>','<104>','<105>','end'])

seg_list = max_forward_matching(data, word_dict, max(len(word) for word in word_dict))
words = list(seg_list)
# 創建一個默認字典來存儲詞匯到ID的映射
word_to_id = defaultdict(lambda: len(word_to_id))
# 創建一個列表來存儲ID到詞匯的映射(可選)
id_to_word = []
# 構建詞匯到ID的映射
for word in words:
? ? word_id = word_to_id[word]
? ? # ID到詞匯的映射,可以這樣做:
? ? if word_id == len(word_to_id): ?# 只有當新的ID被分配時才添加到id_to_word中
? ? ? ? id_to_word.append(word)

import os
import pickle
import requests
import numpy as np
from collections import defaultdict
# download the tiny shakespeare dataset
input_file_path = os.path.join(os.path.dirname(__file__), 'music.txt')
if not os.path.exists(input_file_path):data_url = 'https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt'with open(input_file_path, 'w') as f:f.write(requests.get(data_url).text)with open(input_file_path, 'r',encoding="utf-8") as f:data = f.read()
print(f"length of dataset in characters: {len(data):,}")# get all the unique characters that occur in this text
def max_forward_matching(text, word_dict, max_len):result = []index = 0while index < len(text):found = Falsefor size in range(max_len, 0, -1):  # 從最大長度開始嘗試匹配piece = text[index:index + size]if piece in word_dict:result.append(piece)index += sizefound = Truebreakif not found:  # 如果沒有找到匹配的詞,則按字符輸出result.append(text[index])index += 1return result#自建一套
# 自定義詞典
word_dict = set(['\n', ' ', '+', '.', '0', '1', '2', '3', '4''6', '7', '8', '9', ':', "'a'", "'b'", "'c'", "'d'","'e'", "'f'", "'g'", "'h'","'j'", "'n'","'m'","'q'","'w'","'r'","'t'","'y'","'u'","'s'", "'v'", "'x'", "'z'",'<96>','<97>','<98>','<99>','<100>','<101>','<102>','<103>','<104>','<105>','end'])seg_list = max_forward_matching(data, word_dict, max(len(word) for word in word_dict))
words = list(seg_list)
# 創建一個默認字典來存儲詞匯到ID的映射
word_to_id = defaultdict(lambda: len(word_to_id))
# 創建一個列表來存儲ID到詞匯的映射(可選)
id_to_word = []
# 構建詞匯到ID的映射
for word in words:word_id = word_to_id[word]# ID到詞匯的映射,可以這樣做:if word_id == len(word_to_id):  # 只有當新的ID被分配時才添加到id_to_word中id_to_word.append(word)chars = list(word_to_id)
print(chars)
vocab_size = len(chars)print("all the unique characters:", ''.join(chars))
print(f"vocab size: {vocab_size:,}")
#Myzzb That is need about jieba to cut text
print(chars)
# create a mapping from characters to integers
stoi = { ch:i for i,ch in enumerate(chars) }
print(stoi)
itos = { i:ch for i,ch in enumerate(chars) }
print(itos)def encode(s):seg_list = max_forward_matching(data, word_dict, max(len(word) for word in word_dict))words = list(seg_list)# 創建一個默認字典來存儲詞匯到ID的映射word_to_id = defaultdict(lambda: len(word_to_id))# 創建一個列表來存儲ID到詞匯的映射id_to_word = []# 構建詞匯到ID的映射for word in words:word_id = word_to_id[word]# 如果你也需要ID到詞匯的映射,可以這樣做:if word_id == len(word_to_id):  # 只有當新的ID被分配時才添加到id_to_word中id_to_word.append(word)return [word_to_id[word] for word in words] # encoder: take a string, output a list of integers
def decode(l):seg_list = max_forward_matching(data, word_dict, max(len(word) for word in word_dict))words = list(seg_list)# 創建一個默認字典來存儲詞匯到ID的映射word_to_id = defaultdict(lambda: len(word_to_id))# 創建一個列表來存儲ID到詞匯的映射(可選)id_to_word = []# 構建詞匯到ID的映射for word in words:word_id = word_to_id[word]# 如果你也需要ID到詞匯的映射,可以這樣做:if word_id == len(word_to_id):  # 只有當新的ID被分配時才添加到id_to_word中id_to_word.append(word)return ''.join([word_to_id[word] for word in words]) # decoder: take a list of integers, output a string
# create the train and test splits
n = len(data)
train_data = data[:int(n*0.95)]#這里因為沒寫字典排序,所以訓練集和測試集懶得分開
val_data = data[int(n*0.95):]
# print(val_data)
# encode both to integers
train_ids = encode(train_data)
print(train_ids)
val_ids = encode(val_data)
print(val_ids)
# print(val_ids)
print(f"train has {len(train_ids):,} tokens")
print(f"val has {len(val_ids):,} tokens")# export to bin files
train_ids = np.array(train_ids, dtype=np.uint16)
val_ids = np.array(val_ids, dtype=np.uint16)
train_ids.tofile(os.path.join(os.path.dirname(__file__), 'train.bin'))
val_ids.tofile(os.path.join(os.path.dirname(__file__), 'val.bin'))# save the meta information as well, to help us encode/decode later
meta = {'vocab_size': vocab_size,'itos': itos,'stoi': stoi,
}
with open(os.path.join(os.path.dirname(__file__), 'meta.pkl'), 'wb') as f:pickle.dump(meta, f)

3、結束語斷點

通過在推理過程中檢測新生成的編碼是否和結束語一致,以上在設計的過程中通過字典分詞,然后再分配的編碼,是可以通過代碼獲取對應的結束語的編碼。

通過在分詞的時候進行對部分結束語進行輸出,例子:

print(encode("\n"))
print(encode("\t"))

源碼添加上,即可知道結束語的編碼是多少:

"""
Prepare the Shakespeare dataset for character-level language modeling.
So instead of encoding with GPT-2 BPE tokens, we just map characters to ints.
Will save train.bin, val.bin containing the ids, and meta.pkl containing the
encoder and decoder and some other related info.
"""
import os
import pickle
import requests
import numpy as np# download the tiny shakespeare dataset
input_file_path = os.path.join(os.path.dirname(__file__), 'say.txt')
if not os.path.exists(input_file_path):data_url = 'https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt'with open(input_file_path, 'w') as f:f.write(requests.get(data_url).text)with open(input_file_path, 'r',encoding="utf-8", errors='replace') as f:data = f.read()
print(f"length of dataset in characters: {len(data):,}")# get all the unique characters that occur in this text
chars = sorted(list(set(data)))
vocab_size = len(chars)
print("all the unique characters:", ''.join(chars))
print(f"vocab size: {vocab_size:,}")# create a mapping from characters to integers
stoi = { ch:i for i,ch in enumerate(chars) }
itos = { i:ch for i,ch in enumerate(chars) }def encode(s):return [stoi[c] for c in s] # encoder: take a string, output a list of integers
def decode(l):return ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a stringprint(encode("\n"))
print(encode("\t"))# create the train and test splits
n = len(data)
train_data = data[:int(n*0.9)]
val_data = data[int(n*0.9):]# encode both to integers
train_ids = encode(train_data)
val_ids = encode(val_data)
print(f"train has {len(train_ids):,} tokens")
print(f"val has {len(val_ids):,} tokens")# export to bin files
train_ids = np.array(train_ids, dtype=np.uint16)
val_ids = np.array(val_ids, dtype=np.uint16)
train_ids.tofile(os.path.join(os.path.dirname(__file__), 'train.bin'))
val_ids.tofile(os.path.join(os.path.dirname(__file__), 'val.bin'))# save the meta information as well, to help us encode/decode later
meta = {'vocab_size': vocab_size,'itos': itos,'stoi': stoi,
}
with open(os.path.join(os.path.dirname(__file__), 'meta.pkl'), 'wb') as f:pickle.dump(meta, f)# length of dataset in characters:  1115394
# all the unique characters:
#  !$&',-.3:;?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
# vocab size: 65
# train has 1003854 tokens
# val has 111540 tokens

只需要簡單添加一句代碼即可:

# 檢查是否生成了結束語 可以獲取大部分結束語的編碼用于判斷 也可以自擬結束語 將其處理為唯一的標識符避免干擾
if 1 in idx_next[0].tolist():break

@torch.no_grad()def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):"""Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and completethe sequence max_new_tokens times, feeding the predictions back into the model each time.Most likely you'll want to make sure to be in model.eval() mode of operation for this."""for _ in range(max_new_tokens):# if the sequence context is growing too long we must crop it at block_sizeidx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]# forward the model to get the logits for the index in the sequencelogits, _ = self(idx_cond)# pluck the logits at the final step and scale by desired temperaturelogits = logits[:, -1, :] / temperature# optionally crop the logits to only the top k optionsif top_k is not None:v, _ = torch.topk(logits, min(top_k, logits.size(-1)))logits[logits < v[:, [-1]]] = -float('Inf')# apply softmax to convert logits to (normalized) probabilitiesprobs = F.softmax(logits, dim=-1)# sample from the distributionidx_next = torch.multinomial(probs, num_samples=1)# 檢查是否生成了結束語 可以獲取大部分結束語的編碼用于判斷 也可以自擬結束語 將其處理為唯一的標識符避免干擾if 1 in idx_next[0].tolist():break# append sampled index to the running sequence and continueidx = torch.cat((idx, idx_next), dim=1)return idx

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/66889.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/66889.shtml
英文地址,請注明出處:http://en.pswp.cn/web/66889.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

《探秘:人工智能如何為鴻蒙Next元宇宙網絡傳輸與延遲問題破局》

在元宇宙的宏大愿景中&#xff0c;流暢的網絡傳輸和低延遲是保障用戶沉浸式體驗的關鍵。鴻蒙Next結合人工智能技術&#xff0c;為解決這些問題提供了一系列創新思路和方法。 智能網絡監測與預測 人工智能可以實時監測鴻蒙Next元宇宙中的網絡狀況&#xff0c;包括帶寬、延遲、…

深入MapReduce——計算模型設計

引入 通過引入篇&#xff0c;我們可以總結&#xff0c;MapReduce針對海量數據計算核心痛點的解法如下&#xff1a; 統一編程模型&#xff0c;降低用戶使用門檻分而治之&#xff0c;利用了并行處理提高計算效率移動計算&#xff0c;減少硬件瓶頸的限制 優秀的設計&#xff0c…

macOS安裝Gradle環境

文章目錄 說明安裝JDK安裝Gradle 說明 gradle8.5最高支持jdk21&#xff0c;如果使用jdk22建議使用gradle8.8以上版本 安裝JDK mac系統安裝最新&#xff08;截止2024.9.13&#xff09;Oracle JDK操作記錄 安裝Gradle 下載Gradle&#xff0c;解壓將其存放到資源java/env目錄…

五國十五校聯合巨獻!仿人機器人運動與操控:控制、規劃與學習的最新突破與挑戰

作者&#xff1a; Zhaoyuan Gu, Junheng Li, Wenlan Shen, Wenhao Yu, Zhaoming Xie, Stephen McCrory, Xianyi Cheng, Abdulaziz Shamsah, Robert Griffin, C. Karen Liu, Abderrahmane Kheddar, Xue Bin Peng, Yuke Zhu, Guanya Shi, Quan Nguyen, Gordon Cheng, Huijun Gao,…

CVPR 2024 無人機/遙感/衛星圖像方向總匯(航空圖像和交叉視角定位)

1、UAV、Remote Sensing、Satellite Image(無人機/遙感/衛星圖像) Unleashing Unlabeled Data: A Paradigm for Cross-View Geo-Localization ?codeRethinking Transformers Pre-training for Multi-Spectral Satellite Imagery ?codeAerial Lifting: Neural Urban Semantic …

【BQ3568HM開發板】如何在OpenHarmony上通過校園網的上網認證

引言 前面已經對BQ3568HM開發板進行了初步測試&#xff0c;后面我要實現MQTT的工作&#xff0c;但是遇到一個問題&#xff0c;就是開發板無法通過校園網的認證操作。未認證的話會&#xff0c;學校使用的深瀾軟件系統會屏蔽所有除了認證用的流量。好在我們學校使用的認證系統和…

(Java版本)基于JAVA的網絡通訊系統設計與實現-畢業設計

源碼 論文 下載地址&#xff1a; ????c??????c基于JAVA的網絡通訊系統設計與實現(源碼系統論文&#xff09;https://download.csdn.net/download/weixin_39682092/90299782https://download.csdn.net/download/weixin_39682092/90299782 第1章 緒論 1.1 課題選擇的…

kafka學習筆記4-TLS加密 —— 筑夢之路

1. 準備證書文件 mkdir /opt/kafka/pkicd !$# 生成CA證書 openssl req -x509 -nodes -days 3650 -newkey rsa:4096 -keyout ca.key -out ca.crt -subj "/CNKafka-CA"# 生成私鑰 openssl genrsa -out kafka.key 4096# 生成證書簽名請求 (CSR) openssl req -new -key …

Node.js NativeAddon 構建工具:node-gyp 安裝與配置完全指南

Node.js NativeAddon 構建工具&#xff1a;node-gyp 安裝與配置完全指南 node-gyp Node.js native addon build tool [這里是圖片001] 項目地址: https://gitcode.com/gh_mirrors/no/node-gyp 項目基礎介紹及主要編程語言 Node.js NativeAddon 構建工具&#xff08;node-gyp…

SpringCloud微服務Gateway網關簡單集成Sentinel

Sentinel是阿里巴巴開源的一款面向分布式服務架構的輕量級流量控制、熔斷降級組件。Sentinel以流量為切入點&#xff0c;從流量控制、熔斷降級、系統負載保護等多個維度來幫助保護服務的穩定性。 官方文檔&#xff1a;https://sentinelguard.io/zh-cn/docs/introduction.html …

vscode環境中用倉頡語言開發時調出覆蓋率的方法

在vscode中倉頡語言想得到在idea中利用junit和jacoco的覆蓋率&#xff0c;需要如下幾個步驟&#xff1a; 1.在vscode中搭建倉頡語言開發環境&#xff1b; 2.在源代碼中右鍵運行[cangjie]coverage. 思路1&#xff1a;編寫了測試代碼的情況&#xff08;包管理工具&#xff09; …

pikachu靶場-敏感信息泄露概述

敏感信息泄露概述 由于后臺人員的疏忽或者不當的設計&#xff0c;導致不應該被前端用戶看到的數據被輕易的訪問到。 比如&#xff1a; ---通過訪問url下的目錄&#xff0c;可以直接列出目錄下的文件列表; ---輸入錯誤的url參數后報錯信息里面包含操作系統、中間件、開發語言的版…

安卓動態設置Unity圖形API

命令行方式 Unity圖像api設置為自動,安卓動態設置Vulkan、OpenGLES Unity設置 安卓設置 創建自定義活動并將其設置為應用程序入口點。 在自定義活動中,覆蓋字符串UnityPlayerActivity。updateunitycommandlineararguments (String cmdLine)方法。 在該方法中,將cmdLine…

CICD集合(五):Jenkins+Git+Allure實戰(自動化測試)

CICD集合(五):Jenkins+Git+Allure實戰(自動化測試) 前提: 已安裝好Jenkins安裝好git,maven,allure報告插件配置好Git,Maven,allure參考:CICD集合(一至四) https://blog.csdn.net/fen_fen/article/details/131476093 https://blog.csdn.net/fen_fen/article/details/1213…

時間類型數據處理:基于Python的datetime庫和pandas庫

一、datetime庫常用方法 日期的數據類型主要有兩種&#xff1a;一是包含時間的datetime類型&#xff0c;二是不包含時間的date類型。這里的時間指具體的時、分、秒、甚至毫秒。 1、自定義日期、時間、獲取本地時間、獲取本地日期、獲取年份、月份、月號、小時、分鐘、秒、星期…

低代碼可視化-轉盤小游戲可視化-代碼生成器

轉盤小程序是一種互動工具&#xff0c;它通過模擬真實的轉盤抽獎或決策體驗&#xff0c;為用戶提供了一種有趣且公平的選擇方式。以下是對轉盤小程序的詳細介紹&#xff1a; 轉盤小程序的應用場景 日常決策&#xff1a;轉盤小程序可以幫助用戶解決日常生活中的選擇困難問題&a…

MongoDB文檔查詢

一、實驗目的 1. 理解MongoDB文檔數據庫的基本概念和特性。 2. 掌握在MongoDB中創建集合和插入文檔數據的方法。 3. 學習使用MongoDB進行文檔查詢操作&#xff0c;包括查詢、過濾和排序等。 二、實驗環境準備 1. JAVA環境準備&#xff1a;確保Java Development Kit (J…

速通Docker === 使用最佳實踐總結

目錄 主要使用步驟 1. 命令 2. 網絡 3. 存儲 卷存儲&#xff08;Volumes&#xff09; 目錄掛載&#xff08;Bind Mounts&#xff09; 比較 4. 環境變量 5. 端口 示例&#xff1a;啟動 MySQL 容器 解釋&#xff1a; 總結 Docker 是一個開源的應用容器引擎&#xff0…

Postgresql源碼(140)理解PG的編譯流程(make、Makefile、Makefile.global.in)

PG16 PG中使用的makefile看起來代碼比較多&#xff0c;但是實際邏輯比較簡單&#xff0c;這里做一些抽象總結。 總結 Makefile.global.in的$(recurse)宏自動生成了target&#xff0c;可以方便的進入內存目錄進行編譯。 all: all-common-recurse all-common-recurse: submak…

c語言中的數組(上)

數組的概念 數組是?組相同類型元素的集合&#xff1b; 數組中存放的是1個或者多個數據&#xff0c;但是數組元素個數不能為0。 數組中存放的多個數據&#xff0c;類型是相同的。 數組分為?維數組和多維數組&#xff0c;多維數組?般?較多?的是?維數組。 數組創建 在C語言…