大模型原理:文本生成过程、优化生成文本 作者:马育民 • 2026-01-28 10:23 • 阅读:10003 # 文本生成过程 下图展示了使用GPT模型的三步文本生成过程: 1. 首先,分词器将输入文本转换为一系列词元ID(参见第2章); 2. 然后,模型接收这些词元ID并生成相应的logits,这些logits是表示词汇表中每个词元的概率分布的向量(参见第4章); 3. 最后,这些logits被转换回词元ID,分词器会将其解码为人类可读的文本,这样就完成了从文本输入到文本输出的循环。  上图中,生成文本的过程涉及两个操作: - **文本编码为大语言模型能够处理的`词元ID`**,这些 `词元ID` 经过大语言模型处理后会变成 `logits向量` 2. 然后 **`logits向量` 被转换回 `词元ID`**,最终被反词元化变成文本表示 # 优化生成文本 增加两个函数:`text_to_token_ids()` 和 `token_ids_to_text()`,用于文本和词元表示之间的转换 ### 新增 text_to_token_ids() 对 [大模型原理:生成文本原理、演示](https://www.malaoshi.top/show_1GW2esSDq8xF.html "大模型原理:生成文本原理、演示")文中下面代码的简单封装: ``` encoded = tokenizer.encode(start_context) ``` 函数实现: ``` def text_to_token_ids(text, tokenizer): """ 将文本编码为词元 :param text: :param tokenizer: :return: """ encoded = tokenizer.encode(text, allowed_special={'<|endoftext|>'}) encoded_tensor = torch.tensor(encoded).unsqueeze(0) # add batch dimension return encoded_tensor ``` ### 新增 token_ids_to_text() 对 [大模型原理:生成文本原理、演示](https://www.malaoshi.top/show_1GW2esSDq8xF.html "大模型原理:生成文本原理、演示") 文中下面代码的简单封装: ``` decoded_text = tokenizer.decode(out.squeeze(0).tolist()) ``` 函数实现: ``` def token_ids_to_text(token_ids, tokenizer): """ 将词元解码为文本 :param token_ids: :param tokenizer: :return: """ flat = token_ids.squeeze(0) # remove batch dimension return tokenizer.decode(flat.tolist()) ``` # 测试 ### 准备 从 [大模型原理:全部代码](https://www.malaoshi.top/show_1GW2f5VTAjjY.html "大模型原理:全部代码") 复制以下类或函数: - MultiHeadAttention - GELU - FeedForward - LayerNorm - TransformerBlock - GPTModel - generate_text_simple ### 执行 ``` torch.manual_seed(123) model = GPTModel(GPT_CONFIG_124M) model.eval() # 启用eval()模式 start_context = "Every effort moves you" tokenizer = tiktoken.get_encoding("gpt2") token_ids = generate_text_simple( model=model, idx=text_to_token_ids(start_context, tokenizer), max_new_tokens=10, context_size=GPT_CONFIG_124M["context_length"] ) print("生成文本:\n", token_ids_to_text(token_ids, tokenizer)) ``` 执行结果: ``` 生成文本: Every effort moves you rentingetic wasnم refres RexMeCHicular stren ``` 由于 **没经过训练**,模型还 **无法生成 连贯的文本** 原文出处:http://malaoshi.top/show_1GW2fqXxcIYW.html