欢迎来到 Jiahong 的技术博客
包含操作系统、机器学习、深度学习、强化学习、NLP 和 LLM 等 计算机/AI 领域的学习笔记与实践总结
📊 共计 604 篇技术文章 | 🏷️ 46 个分类领域
人工智能 & 机器学习
广告 & 推荐
编程语言
系统 & 运维
数学
开发工具
其他
💡 提示:点击任意卡片即可查看该分类下的所有文章
📧 联系方式:JoeZJiahong@Foxmail.com | 🔗 GitHub: @JoeZJH
凡事预则立,不预则废
包含操作系统、机器学习、深度学习、强化学习、NLP 和 LLM 等 计算机/AI 领域的学习笔记与实践总结
📊 共计 604 篇技术文章 | 🏷️ 46 个分类领域
💡 提示:点击任意卡片即可查看该分类下的所有文章
📧 联系方式:JoeZJiahong@Foxmail.com | 🔗 GitHub: @JoeZJH
注:本文包含 AI 辅助创作
Paper Summary



temperature = 1.0,top-p = 0.95,上下文长度为 256k tokens

1 | You are Kimi, today’s date: DATE. |
max_steps_per_episode = 100 temperature = 0,WebArena 的 temperature = 0.1作者为所有计算机使用任务使用统一的系统提示:
1 | You are a GUI agent. You are given an instruction, a screenshot of the screen and your previous interactions with the computer. |
1 | { |
1 | You are Kimi, a professional and meticulous expert in information collection and organization. |





注:本文包含 AI 辅助创作
Paper Summary
pass@k

pass@k 性能以衡量基础推理能力,但这仅作为参考,而非主要优化目标





注:本文包含 AI 辅助创作
Paper Summary









注:本文包含 AI 辅助创作
Paper Summary





Figure 2:Expansion rate \(n=2\) 的 HC 示意图

Figure 8: Transformer HC 形式

Algorithm 2:Pseudocode of hyper-connections in a PyTorch-like style.
1 | # h: hyper hidden matrix (BxLxNxD) |
Algorithm3:Pseudocode of transformer with hyper-connections in a PyTorch-like style.
1 | # h: hyper hidden matrix (BxLxNxD) |
关键词:chat_template, chat_chat_template, chat template
tokenizer_config.json 文件中的 chat_template 字段AutoTokenizer.apply_chat_template,这是Hugging Face Transformers 库中 tokenizer 的一个核心方法apply_chat_template 函数的用法1 | def apply_chat_template( |
"role" 和 "content" 键Union[list[dict[str, str]], list[list[dict[str, str]]]]1 | # 单轮对话 |
bool,默认值是 TrueTrue;False1 | # 输出文本格式 |
bool,**默认值: FalseTrue 时,会在对话末尾添加表示助手开始回复的特殊标记1 | # 不添加生成提示 |
bool,默认值是 Falseadd_generation_prompt 同时使用1 | # 预填充助手回复 |
Optional[str],默认值为 None1 | custom_template = """ |
工具列表,用于函数调用场景
参数类型: Optional[list[Union[dict, Callable]]],默认值为 None
每个工具应该是 JSON Schema 格式,包含名称、描述和参数类型
简单参考示例:
1 | tools = [ |
get_weather(**call_info["arguments"])call_info["arguments"] 是一个必须包含 "location" 的字典Optional[list[dict[str, str]]],默认值为 None"title" 和 "text" 键1 | documents = [ |
return_tensors 参数仅在 tokenize=True 时生效Optional[Union[str, TensorType]]None,此时返回 原生 Python 数据结构'pt' (PyTorch), 'tf' (TensorFlow), 'np' (NumPy), 'jax' (JAX)tokenize=False,则无论如何返回值都是原生 Python 数据结构tokenize=True,则根据 return_tensors 判断返回类型None,此时返回 原生 Python 数据结构1 | # PyTorch tensors |
tokenize=True 时有效bool,默认值为 Falseapply_chat_template 函数的 return_dict 参数设为 True 时,函数会返回一个字典格式的结果 ,而非默认的张量(或字符串)return_dict=False):若 tokenize=True,直接返回 input_ids 张量(若开启 padding,会返回形状为 [batch_size, seq_len] 的张量)return_dict=True:返回字典,键值对应模型输入的核心要素,结构清晰,无需手动区分张量类型input_ids、attention_mask 等模型输入所需的关键组件,便于直接拆解和使用return_assistant_tokens_mask=True 时,会多返回一个 assistant_masks 字段output 是一个字典,包含以下关键键(根据参数配置可能增减):"input_ids":对话文本对应的token ID张量(模型输入核心)"attention_mask":注意力掩码张量(标记哪些token是有效文本,哪些是padding,避免模型关注padding)参数类型: bool,默认值为 False
当 return_assistant_tokens_mask=True 时,会多返回一个 assistant_masks 字段
是否返回助手生成 token 的掩码,助手生成的 token 对应掩码为 1,用户和系统 token 对应掩码为 0
tokenize=True 且 return_dict=True 时生效,否则返回错误: 1 | ValueError: `return_dict=True` is incompatible with `tokenize=False`, because there is no dict of tokenizer outputs to return. |
仅支持包含 {% generation %} ... {% endgeneration %} 关键字的聊天模板
assistant 的内容assistant 的整个内容(包括应该学习的所有内容,如 tools 调用等内容都包括进来) {% generationa %} ... {% endgenerationa %} 则会出现下面的问题: 1 | jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'generationa'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'. |
亲测:return_assistant_tokens_mask=True 但对 chat_template 有一定的要求(要求包含 {% generation %} 用于标记 assistant 位置),当前大部分 chat_template 都不支持,此时会全屏蔽(返回 assistant_masks 字段全是 0)
1 | return_assistant_tokens_mask==True but chat template does not contain `{% raw %} {% generation %} {% endraw %}` keyword. |
常用用途:用于训练或分析,标识哪些 token 是由助手生成的
简单参考示例:
1 | output = tokenizer.apply_chat_template( |
output 多多包涵一个 assistant_masks 的 list 类型字段,里面为 1 的地方都是 assistant 的 Tokenassistant 信息前面加入的 <USER> Token 通常会被包含Union[bool, str, PaddingStrategy],默认值为 Falsetokenize=True 时生效tokenize=False 时不会 paddingTrue 或 'longest': 填充到批次中最长序列'max_length': 填充到指定最大长度,最大长度由 max_length 参数指定False(默认值) 或 'do_not_pad': 不填充1 | # 填充到最长序列 |
padding_side 属性指定左填充 or 右填充Tokenizer.apply_chat_template 方法本身并不直接提供选择左 padding(Left Padding) 或右 padding (Right Padding) 的参数padding_side 参数)决定的,而不是由 apply_chat_template 方法单独控制tokenizer.padding_side 属性进行配置padding_side 可选值为 "right"(默认值) 或 "left"apply_chat_template 方法主要用于将对话历史格式化为模型期望的输入格式,它会调用 tokenizer 的编码逻辑,而编码过程会遵循 tokenizer 已设置的 padding_side 配置1 | from transformers import AutoTokenizer |
bool,默认值为 Falsetruncation_side 属性指定左截断 or 右截断padding_side 参数类似truncation_side 是 Tokenizer 类的一个属性,其可选值为:"left":从序列的左侧(开头)截断"right"(默认值):从序列的右侧(结尾)截断(默认值)padding 或 truncation 配合使用Optional[int],默认值为 None1 | from transformers import AutoTokenizer, AutoModelForCausalLM |
1 | # 批量对话 |
RAG 使用模板的示例
1 | # 准备文档 |
注:一般的模板不支持 documents,目前包括 Llama 系列,Qwen 系列等均不支持
支持 documents 的模型示例:huggingface.co/CohereLabs/c4ai-command-r-v01/blob/main/tokenizer_config.json
chat_template 模版不支持 documents 时,方法包括:
documents 拼进 system 或第一条 user 消息,再在 vLLM 等框架启动时通过 --chat-template 指定,apply_chat_template 函数也支持该参数;messages=[{"role":"user","content":"..."}] 传入即可最佳实践:先通过 Prompt Engineering 找到合适的模版,然后通过固定的模版文件将该形式固定下来,模型微调和线上 serving 均使用这个模版,这样可以避免因为模型微调和线上 serving 不一致带来的问题,也方便团队内外的合作
add_generation_prompt 的使用: 在推理时,确保设置 add_generation_prompt=True 以获得正确的助手回复tokenizer.get_chat_template() 查看具体格式truncation=True 并设置合适的 max_lengthpadding 参数以提高效率,否则可能返回不同长度的编码结果tools 参数,需要检查模型文档batch size 或 max_lengthconversation 格式正确,每个消息都有 role 和 content 键code_interpreter(代码解释器)和 function(函数/工具)是两种不同类型的工具function(函数/工具)function(函数/工具)是预先定义的、具有特定功能的程序函数或API接口,用于让模型调用外部能力 ,模型通过生成符合格式的调用指令(如JSON),触发这些函数执行,并获取返回结果
get_weather(city="北京")函数获取实时天气function 调用方式:模型需严格按照预设格式(如{"name": "函数名", "parameters": {"参数名": "值"}})生成调用指令,确保函数能被正确解析和执行,例如:
1 | {"name": "translate", "parameters": {"text": "Hello", "target_lang": "zh"}} |
function 灵活性低:功能固定,只能执行预定义的操作;但安全性高:严格限制在预设函数范围内,风险可控
function适用场景包括
code_interpreter(代码解释器)code_interpreter(代码解释器)是一个能够动态执行代码(通常是Python)的沙箱环境,允许模型直接生成并运行代码来解决问题,模型生成代码后,解释器会运行代码并返回输出结果(包括文本、图表等)
1+2+...+100的和,并通过代码解释器执行得到结果code_interpreter 灵活性高:支持任意代码逻辑,可解决复杂、动态的问题;但安全性低:需运行用户/模型生成的代码,存在恶意代码风险(通常通过沙箱隔离缓解)
code_interpreter 中,模型直接生成代码片段(通常包裹在特定标记中,如1
2
3
4```python
import numpy as np
result = np.sum(range(1, 101))
print(result)
code_interpreter 适用场景包括
使用 code_interpreter 时,只需要在 tools 里面加一项 { "type": "code_interpreter" },,这样 chat_template 会自动识别到该字段并输出一些使用信息,告诉模型如何给出代码,并告知模型这个代码可以被执行
code_interpreter 包装成一个类似 function 的格式,再统一输出,最终效果就是让模型知道可以调用 code_interpreter 执行代码("code" 参数内容就是代码)function 和 code_interpreter 整体对比function处理外部交互,code_interpreter处理复杂计算,共同扩展大模型的能力边界| 维度 | function(函数) |
code_interpreter(代码解释器) |
|---|---|---|
| 核心能力 | 调用预定义功能接口 | 动态执行代码逻辑 |
| 适用场景 | 外部服务调用、结构化任务 | 复杂计算、数据处理、脚本生成 |
| 调用格式 | 严格 JSON 格式指令 | 代码片段(如 Python) |
| 灵活性 | 低(固定功能) | 高(支持任意逻辑) |
| 安全性 | 高 | 需沙箱隔离,风险较高 |
大部分开源模型的 chat-template 都是压缩为一行的,可读性较差
可以使用下面的代码重新存储 tokenizer 信息
1 | tokenizer.save_pretrained(output_model_name) |
这样会同步生成得到的 chat-template.jinja 文件,整体格式是更可读的
注:也可以使用大模型来帮忙格式化
continue 语句的使用transformers 中,调用 tokenizer.apply_chat_template 时 不支持 chat-template 中有 continue 语句transformers 版本后可以解决问题: 1 | jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'continue'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'. |
Qwen2-72B-Instruct 的 chat-template 非常简单
特别需要说明:当不增加 System Prompt 时, Qwen2-72B-Instruct 会默认将 "You are a helpful assistant." 作为 System Prompt
Qwen2-72B-Instruct/tokenizer_config.json 原始定义:
1 | { |
"You are Qwen, created by Alibaba Cloud. You are a helpful assistant." 1 | { |
Qwen2-72B chat-template 使用示例:
1 | model_name = "/Users/xxx/llm/model/Qwen2-72B-Instruct" |
注:本文包含 AI 辅助创作
underscores the power and beauty of reinforcement learning: rather than explicitly teaching the model on how to solve a problem, we simply provide it with the right incentives, and it autonomously develops advanced problem-solving strategies.
such as cost, error rates, hunger, pro- ductivity, health metrics, climate metrics, profit, sales, exam results, success, visits, yields, stocks, likes, income, pleasure/pain, economic indicators, accuracy, power, distance, speed, efficiency, or energy consump- tion
the era of human data has focused predominantly on RL methods that are designed for short episodes of ungrounded, human interaction, and are not suitable for long streams of grounded, autonomous interaction.
注:本文包含 AI 辅助创作
Paper Summary


在本节中,基于第 3 节对链式思维中熵模式的观察,论文进一步研究了这些模式在 RLVR 训练过程中的演化
RLVR 主要保留基础模型的现有熵模式(RLVR primarily preserves the existing entropy patterns of the base models)
RLVR 主要调整高熵 Token 的熵值,而低熵 Token 的熵值相对稳定,变化较小(RLVR predominantly alters the entropy of high-entropy tokens, whereas the entropy of low-entropy tokens remains comparatively stable with minimal variations.)
“User:\n[question]\nPlease reason step by step, and put your final answer within \boxed{}.\n\nAssistant:\n”
with “<|endoftext|>“ serving as the EOS token, where “[question]” should be replaced by the specific question.
<|im_end|>,这里使用 <|endoftext|> 真的不会有问题吗?


注:本文包含 AI 辅助创作
Paper Summary
verified=True and is_passed=True),优先考虑高保真度的推理而非数据量
Furthermore, we observe that on-policy training exhibits high variance, failing to guarantee monotonic improvement or stable convergence.