[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-apoorvumang--prompt-lookup-decoding":3,"tool-apoorvumang--prompt-lookup-decoding":61},[4,18,26,36,44,52],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",141543,2,"2026-04-06T11:32:54",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107888,"2026-04-06T11:32:50",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":10,"last_commit_at":50,"category_tags":51,"status":17},4487,"LLMs-from-scratch","rasbt\u002FLLMs-from-scratch","LLMs-from-scratch 是一个基于 PyTorch 的开源教育项目，旨在引导用户从零开始一步步构建一个类似 ChatGPT 的大型语言模型（LLM）。它不仅是同名技术著作的官方代码库，更提供了一套完整的实践方案，涵盖模型开发、预训练及微调的全过程。\n\n该项目主要解决了大模型领域“黑盒化”的学习痛点。许多开发者虽能调用现成模型，却难以深入理解其内部架构与训练机制。通过亲手编写每一行核心代码，用户能够透彻掌握 Transformer 架构、注意力机制等关键原理，从而真正理解大模型是如何“思考”的。此外，项目还包含了加载大型预训练权重进行微调的代码，帮助用户将理论知识延伸至实际应用。\n\nLLMs-from-scratch 特别适合希望深入底层原理的 AI 开发者、研究人员以及计算机专业的学生。对于不满足于仅使用 API，而是渴望探究模型构建细节的技术人员而言，这是极佳的学习资源。其独特的技术亮点在于“循序渐进”的教学设计：将复杂的系统工程拆解为清晰的步骤，配合详细的图表与示例，让构建一个虽小但功能完备的大模型变得触手可及。无论你是想夯实理论基础，还是为未来研发更大规模的模型做准备",90106,"2026-04-06T11:19:32",[35,15,13,14],{"id":53,"name":54,"github_repo":55,"description_zh":56,"stars":57,"difficulty_score":10,"last_commit_at":58,"category_tags":59,"status":17},4292,"Deep-Live-Cam","hacksider\u002FDeep-Live-Cam","Deep-Live-Cam 是一款专注于实时换脸与视频生成的开源工具，用户仅需一张静态照片，即可通过“一键操作”实现摄像头画面的即时变脸或制作深度伪造视频。它有效解决了传统换脸技术流程繁琐、对硬件配置要求极高以及难以实时预览的痛点，让高质量的数字内容创作变得触手可及。\n\n这款工具不仅适合开发者和技术研究人员探索算法边界，更因其极简的操作逻辑（仅需三步：选脸、选摄像头、启动），广泛适用于普通用户、内容创作者、设计师及直播主播。无论是为了动画角色定制、服装展示模特替换，还是制作趣味短视频和直播互动，Deep-Live-Cam 都能提供流畅的支持。\n\n其核心技术亮点在于强大的实时处理能力，支持口型遮罩（Mouth Mask）以保留使用者原始的嘴部动作，确保表情自然精准；同时具备“人脸映射”功能，可同时对画面中的多个主体应用不同面孔。此外，项目内置了严格的内容安全过滤机制，自动拦截涉及裸露、暴力等不当素材，并倡导用户在获得授权及明确标注的前提下合规使用，体现了技术发展与伦理责任的平衡。",88924,"2026-04-06T03:28:53",[14,15,13,60],"视频",{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":66,"readme_en":67,"readme_zh":68,"quickstart_zh":69,"use_case_zh":70,"hero_image_url":71,"owner_login":72,"owner_name":73,"owner_avatar_url":74,"owner_bio":75,"owner_company":76,"owner_location":77,"owner_email":78,"owner_twitter":79,"owner_website":80,"owner_url":81,"languages":82,"stars":91,"forks":92,"last_commit_at":93,"license":65,"difficulty_score":32,"env_os":94,"env_gpu":95,"env_ram":96,"env_deps":97,"category_tags":102,"github_topics":65,"view_count":32,"oss_zip_url":65,"oss_zip_packed_at":65,"status":17,"created_at":103,"updated_at":104,"faqs":105,"releases":133},4385,"apoorvumang\u002Fprompt-lookup-decoding","prompt-lookup-decoding",null,"prompt-lookup-decoding 是一种专为大语言模型设计的加速推理技术。它主要解决了在摘要生成、文档问答、多轮对话及代码编辑等“基于输入生成”的任务中，传统自回归解码速度较慢的问题。在这些场景下，模型输出的内容往往大量复用输入提示词中的短语或实体，而该技术正是利用这一特性来提升效率。\n\n其核心亮点在于巧妙改进了现有的“推测性解码”机制：不再依赖额外的草稿模型来预测后续内容，而是直接在输入提示词中进行简单的字符串（N-gram）匹配。通过查找当前生成内容与历史输入的重复模式，它能一次性预判并生成多个候选令牌。这种方法无需修改模型架构或引入外部数据库，兼容贪婪搜索和采样等多种生成策略，能在完全不影响输出质量的前提下，实现 2 到 4 倍的推理加速。\n\n目前，该技术已被集成至 Hugging Face Transformers 库和 vLLM 框架中，开发者只需添加少量参数即可启用。因此，它非常适合需要优化大模型推理延迟的 AI 开发者、研究人员以及致力于提升应用响应速度的工程团队使用。","# Prompt Lookup Decoding\n\n**UPDATE 2**: This method is now available in [vLLM as well](https:\u002F\u002Fdocs.vllm.ai\u002Fen\u002Fstable\u002Fmodels\u002Fspec_decode.html#speculating-by-matching-n-grams-in-the-prompt) by setting `speculative_model=\"[ngram]\"` 🥳\n\n**UPDATE**: This has been [added to the transformers](https:\u002F\u002Ftwitter.com\u002Fjoao_gante\u002Fstatus\u002F1747322413006643259) library. Please see [this for a code example](https:\u002F\u002Fpastebin.com\u002Fbms6XtR4), or simply add `prompt_lookup_num_tokens=10` to your `model.generate(...)` call.\n\nMinimal implementation: See [demo notebook](.\u002Fdemo-pld.ipynb) or [colab](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1ovjH1sg3lXWdm5Rx5EEukB9H_PFJVpJ4?usp=sharing)\n\n**TLDR**: We modify speculative decoding where we replace the draft model with simple string matching in the prompt to generate candidate token sequences. This results in significant speedups (2x-4x) in input-grounded tasks, with no effect on output quality. This method can be used with any decoder model without model changes or external datastore, and with both greedy and sampling techniques.\n\n\nhttps:\u002F\u002Fgithub.com\u002Fapoorvumang\u002Fprompt-lookup-decoding\u002Fassets\u002F1957903\u002Fe908de89-ce5c-4156-8ef1-21f169dc1c8f\n\nColoured token indicate that multiple tokens were generated in a single step.\n\n\n## Method\n\n**Intuition**: In several LLM use cases where you're doing _input grounded generation_ (summarization, document QA, multi-turn chat, code editing), there is high n-gram overlap between LLM input (prompt) and LLM output. This could be entity names, phrases, or code chunks that the LLM directly copies from the input while generating the output. Prompt lookup exploits this pattern to speed up autoregressive decoding in LLMs.\n\nHere's an animation explaining with an example (for information on how speculative decoding itself works\u002Fgives speedup, please see this excellent [huggingface blog](https:\u002F\u002Fhuggingface.co\u002Fblog\u002Fassisted-generation)):\n\nhttps:\u002F\u002Fgithub.com\u002Fapoorvumang\u002Fprompt-lookup-decoding\u002Fassets\u002F1957903\u002F10c3728b-2d50-4205-a758-478e51425793\n\nThis is the \"prompt lookup\" function:\n\n```\ndef find_candidate_pred_tokens(input_ids, max_ngram_size=3, num_pred_tokens=10):\n    input_length = input_ids.size(1)\n\n    for ngram_size in range(max_ngram_size, 0, -1):\n        # Extract the last n tokens as our search ngram\n        ngram = input_ids[0, -ngram_size:].tolist()\n\n        # Create sliding windows of size ngram_size\n        windows = input_ids.unfold(dimension=1, size=ngram_size, step=1)\n\n        # Convert ngram to a tensor for comparison\n        ngram_tensor = torch.tensor(ngram, device=input_ids.device).unsqueeze(0)\n\n        # Find where the windows match the ngram\n        matches = (windows == ngram_tensor).all(dim=2)\n\n        # Get the indices of matches\n        match_indices = matches.nonzero(as_tuple=True)[1]\n\n        # Iterate through match indices to find a valid continuation\n        for idx in match_indices:\n            start_idx = idx + ngram_size\n            end_idx = start_idx + num_pred_tokens\n            # Ensure we don't go beyond the length of input_ids and avoid self-match\n            if end_idx \u003C= input_length and start_idx \u003C input_length - ngram_size:\n                return input_ids[0, start_idx:end_idx]\n\n    # If no match is found, return an empty tensor\n    return torch.tensor([], dtype=torch.long, device=input_ids.device)\n\n```\n\n\nImplementation-wise, we modify [speculative decoding](https:\u002F\u002Farxiv.org\u002Fpdf\u002F2302.01318.pdf) (aka assisted generation in hf transformers) by swapping out the “draft model” with this function.\n\nInput to this function is the same as to the draft model - all the tokens till the current generation step (`input_ids`). It then tries to match last few tokens to somewhere earlier in the prompt. If found, it returns the next-k token continuation as `candidate_input_ids` or candidate sequence. The 2 parameters are `max_ngram_size`, which is the maximum ngram to use when looking for matches in the prompt. `num_pred_tokens` is the candidate sequence length to return after match is found.\n\n\n## Experimental setup\n\n- **GPU**: Single A100 40GB\n- **Model**: Mistral-7B-Instruct-v0.1\n- **Decoding Type**: Greedy decoding\n- **Hyperparams**: Matching max n-gram size = 3, Continuation length = 10\n\n## Datasets\n\nWe experiment on 3 datasets, and compare with simple greedy decoding as a baseline. We focus on \"input-grounded\" tasks where we expect high overlap between input and output - summarization, context-based QA and multi-turn chat.\n\n- **Summarization**: CNN\u002FDailymail 100 examples\n- **Context-QA**: 100 examples from [HAGRID](https:\u002F\u002Fgithub.com\u002Fproject-miracl\u002Fhagrid). We concatenate all the evidences to form the context and then do QA\n- **Multi-turn chat**: [MT-bench](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002FHuggingFaceH4\u002Fmt_bench_prompts), all 80 examples. This isn't exactly input-grounded generation but gives an idea of performance on regular chat\n\n## Results\n\n### Summarization and Context-QA\nOn both summarization and context-QA, we get a relatively consistent 2.4x speedup (on average). The error bar is stddev, which shows there is quite a bit of variation depending on the example. Throughput of PLD was always more than that of greedy (or within margin of error) - I never saw it giving worse throughput than greedy on any example.\n\n\u003Cimg width=\"639\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fapoorvumang_prompt-lookup-decoding_readme_b96f996339a3.png\">\n\n### Multi-turn chat\nOn MT-Bench, we see a similar gain on turn 1, but a much smaller gain on turn 0. This is expected - in the first turn, the algorithm can only match n-grams with its own output, since the prompt is pretty small. However this matching with self output gives measurable gains. Again, the error bars are stddev and I didn't see PLD giving worse throughput on any example.\n\n\u003Cimg width=\"535\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fapoorvumang_prompt-lookup-decoding_readme_2c2bda68bdda.png\">\n\nMT-Bench also has prompt categories. Some observations:\n- roleplay has the worst gain. This is probably because there isn't many ngrams to copy, since each generation is sort of unique.\n- coding has very high gain in 2nd turn, because there is lots of code copying\n- in first turn, extraction has highest gain. This agrees with our hypothesis - in extraction there is definitely n-gram copying, and PLD should help\n\n\u003Cimg width=\"709\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fapoorvumang_prompt-lookup-decoding_readme_2e3f7cccf7f3.png\">\n\n## TODOs\u002FThoughts\u002FFuture work\n- There's probably better ways to do string matching than the current one, and there are several obvious things to improve eg. what to do when there are multiple matches? Whats the ideal length of continuation?\n- We haven't yet tried sampling, although there's no reason it shouldn't work.\n    - Here, one additional thing to test would be whether prompt lookup while sampling can affect hallucination rates, since this artifically increases probability of sampling exact sequences from input (this was suggest by my colleague Shwetha S)\n- Testing actual FLOPs impact and tradeoffs is needed\n- Also need to figure out best hyperparams - 3 and 10 were chosen on very little testing\n- It would be an interesting challenge to design the \"best lookup function\" for decoding, could even be a competition?\n\n## How to cite\n```\n@misc{saxena2023prompt,\n    title = {Prompt Lookup Decoding},\n    author = {Apoorv Saxena},\n    year = {2023},\n    month = {November},\n    url = {https:\u002F\u002Fgithub.com\u002Fapoorvumang\u002Fprompt-lookup-decoding\u002F}\n}\n```\n","# 提示查找解码\n\n**更新 2**：此方法现已在 [vLLM 中也可用](https:\u002F\u002Fdocs.vllm.ai\u002Fen\u002Fstable\u002Fmodels\u002Fspec_decode.html#speculating-by-matching-n-grams-in-the-prompt)，只需设置 `speculative_model=\"[ngram]\"` 即可 🥳\n\n**更新**：此功能已[添加到 transformers 库](https:\u002F\u002Ftwitter.com\u002Fjoao_gante\u002Fstatus\u002F1747322413006643259)。请参阅[此处的代码示例](https:\u002F\u002Fpastebin.com\u002Fbms6XtR4)，或直接在 `model.generate(...)` 调用中添加 `prompt_lookup_num_tokens=10`。\n\n最小实现：请参阅[演示笔记本](.\u002Fdemo-pld.ipynb)或[Colab](https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1ovjH1sg3lXWdm5Rx5EEukB9H_PFJVpJ4?usp=sharing)。\n\n**简而言之**：我们对推测解码进行了修改，将草案模型替换为在提示中进行简单的字符串匹配，以生成候选标记序列。这在输入相关的任务中带来了显著的速度提升（2–4倍），且不会影响输出质量。该方法可与任何解码器模型配合使用，无需更改模型或依赖外部数据存储，并且适用于贪婪和采样两种解码策略。\n\n\nhttps:\u002F\u002Fgithub.com\u002Fapoorvumang\u002Fprompt-lookup-decoding\u002Fassets\u002F1957903\u002Fe908de89-ce5c-4156-8ef1-21f169dc1c8f\n\n彩色标记表示在单步中生成了多个标记。\n\n\n## 方法\n\n**直觉**：在许多需要“基于输入生成”的大语言模型应用场景中（如摘要生成、文档问答、多轮对话、代码编辑），模型输入（提示）与输出之间存在较高的 n 元组重叠。这些可能是实体名称、短语或代码片段，模型在生成输出时会直接从输入中复制它们。提示查找利用这一模式来加速大语言模型的自回归解码。\n\n以下是一个示例动画，用于解释其原理（有关推测解码的工作原理及其提速效果，请参阅这篇优秀的[Hugging Face 博客文章](https:\u002F\u002Fhuggingface.co\u002Fblog\u002Fassisted-generation)）：\n\nhttps:\u002F\u002Fgithub.com\u002Fapoorvumang\u002Fprompt-lookup-decoding\u002Fassets\u002F1957903\u002F10c3728b-2d50-4205-a758-478e51425793\n\n以下是“提示查找”函数：\n\n```\ndef find_candidate_pred_tokens(input_ids, max_ngram_size=3, num_pred_tokens=10):\n    input_length = input_ids.size(1)\n\n    for ngram_size in range(max_ngram_size, 0, -1):\n        # 提取最后 n 个标记作为我们的搜索 n 元组\n        ngram = input_ids[0, -ngram_size:].tolist()\n\n        # 创建大小为 ngram_size 的滑动窗口\n        windows = input_ids.unfold(dimension=1, size=ngram_size, step=1)\n\n        # 将 ngram 转换为张量以便比较\n        ngram_tensor = torch.tensor(ngram, device=input_ids.device).unsqueeze(0)\n\n        # 查找窗口与 ngram 匹配的位置\n        matches = (windows == ngram_tensor).all(dim=2)\n\n        # 获取匹配的索引\n        match_indices = matches.nonzero(as_tuple=True)[1]\n\n        # 遍历匹配索引以找到有效的延续\n        for idx in match_indices:\n            start_idx = idx + ngram_size\n            end_idx = start_idx + num_pred_tokens\n            # 确保不超过 input_ids 的长度，并避免自我匹配\n            if end_idx \u003C= input_length && start_idx \u003C input_length - ngram_size:\n                return input_ids[0, start_idx:end_idx]\n\n    # 如果未找到匹配，则返回空张量\n    return torch.tensor([], dtype=torch.long, device=input_ids.device)\n\n```\n\n\n从实现角度来看，我们将[推测解码](https:\u002F\u002Farxiv.org\u002Fpdf\u002F2302.01318.pdf)（也称为 Hugging Face Transformers 中的辅助生成）中的“草案模型”替换为此函数。\n\n该函数的输入与草案模型相同——即截至当前生成步骤的所有标记 (`input_ids`)。随后，它会尝试将最后几个标记与提示中较早的部分进行匹配。如果找到匹配，则返回接下来的 k 个标记作为 `candidate_input_ids` 或候选序列。两个参数分别为 `max_ngram_size`，即在提示中寻找匹配时使用的最大 n 元组大小；以及 `num_pred_tokens`，即找到匹配后要返回的候选序列长度。\n\n\n## 实验设置\n\n- **GPU**：单块 A100 40GB\n- **模型**：Mistral-7B-Instruct-v0.1\n- **解码类型**：贪婪解码\n- **超参数**：最大匹配 n 元组大小 = 3，延续长度 = 10\n\n## 数据集\n\n我们在 3 个数据集上进行了实验，并以简单的贪婪解码作为基准进行对比。我们重点关注“基于输入”的任务，这类任务通常预期输入与输出之间有较高的重叠——例如摘要生成、基于上下文的问答以及多轮对话。\n\n- **摘要生成**：CNN\u002FDailymail 100 个示例\n- **基于上下文的问答**：来自 [HAGRID](https:\u002F\u002Fgithub.com\u002Fproject-miracl\u002Fhagrid) 的 100 个示例。我们将所有证据拼接成上下文后再进行问答。\n- **多轮对话**：[MT-bench](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002FHuggingFaceH4\u002Fmt_bench_prompts)，共 80 个示例。虽然这并不完全是基于输入的生成任务，但可以大致了解其在常规聊天场景下的性能。\n\n## 结果\n\n### 摘要生成与基于上下文的问答\n在摘要生成和基于上下文的问答任务中，我们均获得了相对稳定的 2.4 倍速度提升（平均值）。误差线代表标准差，表明不同示例之间的差异较大。PLD 的吞吐量始终高于或与贪婪解码持平——在任何示例中我都未观察到 PLD 的吞吐量低于贪婪解码的情况。\n\n\u003Cimg width=\"639\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fapoorvumang_prompt-lookup-decoding_readme_b96f996339a3.png\">\n\n### 多轮对话\n在 MT-Bench 上，我们在第一轮中看到了类似的收益，但在第零轮中收益则小得多。这是意料之中——因为在第一轮中，算法只能将其自身的输出与 n 元组进行匹配，因为提示内容非常有限。不过，这种与自身输出的匹配仍然带来了可观的收益。同样，误差线代表标准差，我并未在任何示例中观察到 PLD 的吞吐量低于贪婪解码的情况。\n\n\u003Cimg width=\"535\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fapoorvumang_prompt-lookup-decoding_readme_2c2bda68bdda.png\">\n\nMT-Bench 还按提示类别进行了划分。一些观察结果如下：\n- 角色扮演类别的收益最差。这可能是因为可复制的 n 元组较少，每次生成的内容都较为独特。\n- 编程类别的第二轮收益非常高，因为其中包含大量代码复制。\n- 在第一轮中，信息抽取类别的收益最高。这与我们的假设一致——在信息抽取任务中确实存在 n 元组复制现象，因此 PLD 应该能够起到帮助作用。\n\n\u003Cimg width=\"709\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fapoorvumang_prompt-lookup-decoding_readme_2e3f7cccf7f3.png\">\n\n## 待办事项\u002F思考\u002F未来工作\n- 字符串匹配的方法可能还有更好的实现方式，目前的实现仍有明显可改进之处，例如：当存在多个匹配时该如何处理？理想的续写长度应该是多少？\n- 我们尚未尝试采样方法，尽管从理论上讲它应该可以正常工作。\n    - 在这里，还有一项需要测试的内容是：在采样过程中进行提示词查找是否会影响幻觉率，因为这会人为地增加从输入中采样到精确序列的概率（这一建议来自我的同事 Shwetha S）。\n- 需要测试实际的 FLOPs 影响及权衡。\n- 还需要确定最佳超参数——目前使用的 3 和 10 是基于非常有限的实验选择的。\n- 设计用于解码的“最优查找函数”将是一项有趣的挑战，甚至可以组织一场竞赛？\n\n## 如何引用\n```\n@misc{saxena2023prompt,\n    title = {提示词查找解码},\n    author = {Apoorv Saxena},\n    year = {2023},\n    month = {十一月},\n    url = {https:\u002F\u002Fgithub.com\u002Fapoorvumang\u002Fprompt-lookup-decoding\u002F}\n}\n```","# Prompt Lookup Decoding 快速上手指南\n\nPrompt Lookup Decoding (PLD) 是一种优化的推测解码（Speculative Decoding）技术。它通过在输入提示词（Prompt）中进行简单的字符串匹配来生成候选 token 序列，从而替代传统的草稿模型（Draft Model）。该方法特别适用于摘要、文档问答、多轮对话和代码编辑等“基于输入的生成”任务，可实现 2-4 倍的推理加速，且不影响输出质量。\n\n目前该技术已集成至 Hugging Face `transformers` 库及 `vLLM` 框架中。\n\n## 环境准备\n\n*   **系统要求**：Linux \u002F macOS \u002F Windows\n*   **硬件要求**：支持 CUDA 的 NVIDIA GPU（推荐 A100 或同等算力显卡以获得最佳加速效果）\n*   **前置依赖**：\n    *   Python >= 3.8\n    *   PyTorch\n    *   Hugging Face `transformers` (建议安装最新版本以支持原生参数)\n\n## 安装步骤\n\n请确保已安装基础的 PyTorch 环境。若需使用最新功能，建议升级 `transformers` 库。\n\n**使用 pip 安装\u002F升级：**\n\n```bash\npip install --upgrade transformers torch accelerate\n```\n\n> **国内加速建议**：如果下载速度较慢，可使用清华或阿里镜像源：\n> ```bash\n> pip install --upgrade transformers torch accelerate -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n> ```\n\n## 基本使用\n\n### 方法一：使用 Hugging Face Transformers (推荐)\n\n自更新后，`transformers` 库已原生支持该功能。只需在调用 `model.generate()` 时添加 `prompt_lookup_num_tokens` 参数即可。\n\n**代码示例：**\n\n```python\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\n# 1. 加载模型和分词器\nmodel_name = \"mistralai\u002FMistral-7B-Instruct-v0.1\"\ntokenizer = AutoTokenizer.from_pretrained(model_name)\nmodel = AutoModelForCausalLM.from_pretrained(model_name, device_map=\"auto\")\n\n# 2. 准备输入文本 (基于输入的任务效果最佳，如摘要、问答)\nprompt = \"Summarize the following text: Artificial intelligence is a wonderful field...\"\ninputs = tokenizer(prompt, return_tensors=\"pt\").to(model.device)\n\n# 3. 生成文本\n# 关键参数：prompt_lookup_num_tokens\n# 设置该参数即启用 Prompt Lookup Decoding\n# num_pred_tokens (此处为 10) 表示匹配成功后预生成的候选 token 数量\noutputs = model.generate(\n    **inputs,\n    max_new_tokens=100,\n    prompt_lookup_num_tokens=10,  # 启用 PLD\n    do_sample=False               # 当前主要支持贪婪解码 (Greedy)\n)\n\n# 4. 解码输出\nresult = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(result)\n```\n\n### 方法二：使用 vLLM\n\n如果你使用 `vLLM` 进行部署，可以通过设置 `speculative_model` 为 `[ngram]` 来启用此功能。\n\n**启动命令示例：**\n\n```bash\npython -m vllm.entrypoints.api_server \\\n    --model mistralai\u002FMistral-7B-Instruct-v0.1 \\\n    --speculative_model \"[ngram]\" \\\n    --num_speculative_tokens 10\n```\n\n### 核心参数说明\n\n*   `prompt_lookup_num_tokens` (Transformers) \u002F `--num_speculative_tokens` (vLLM):\n    *   含义：当在 Prompt 中找到匹配的 n-gram 后，向后预取的 token 数量。\n    *   默认实验值：`10`。可根据具体任务调整，过大会增加验证开销，过小则加速效果不明显。\n*   `max_ngram_size` (仅在使用自定义实现时需关注):\n    *   含义：用于匹配的最大 n-gram 长度。\n    *   默认实验值：`3`。\n\n### 适用场景建议\n\n*   **最佳场景**：摘要生成、基于文档的问答 (RAG)、多轮对话（尤其是第二轮及以后）、代码补全\u002F编辑。这些场景中输出内容与输入内容有很高的 n-gram 重叠。\n*   **效果一般场景**：创意写作、角色扮演（Roleplay），因为此类任务输出与输入的重叠度较低。","某法律科技团队正在开发一款智能合同审查助手，需要让大模型基于用户上传的长篇法律文档，快速生成包含大量原文引用的合规分析报告。\n\n### 没有 prompt-lookup-decoding 时\n- **生成速度缓慢**：模型在逐字输出时，即使是对文档中已有的长段落进行“复制”，也必须按传统自回归方式一个 token 一个 token 地计算，耗时极长。\n- **算力成本高昂**：由于推理延迟高，为了维持用户体验，团队不得不部署更多 GPU 实例来并发处理请求，导致云端账单激增。\n- **响应体验割裂**：用户在等待报告生成时，看到文字是逐个蹦出的，尤其在处理数万字的合同时，首字延迟和整体生成时间让人难以忍受。\n- **资源利用率低**：大量的计算资源被浪费在重复预测那些明明已经存在于输入提示词（Prompt）中的固定短语和条款上。\n\n### 使用 prompt-lookup-decoding 后\n- **推理速度倍增**：工具通过在提示词中直接匹配 n-gram 序列，一次性“跳跃”生成多个后续 token，在合同审查这类强依赖原文的任务中实现了 2-4 倍的加速。\n- **显著降低成本**：同样的硬件配置下吞吐量大幅提升，团队减少了近半数的 GPU 节点需求，直接降低了运营开支。\n- **流畅交互体验**：用户能观察到文字成段落地快速浮现（如演示中彩色标记所示），大幅缩短了等待焦虑，使长文档处理变得即时可用。\n- **零质量损耗**：加速过程仅改变了解码策略，未修改模型权重，生成的法律条款准确性与原文一致性完全保持不变。\n\nprompt-lookup-decoding 通过巧妙利用输入与输出间的高重叠特性，在不牺牲任何生成质量的前提下，为文档摘要、问答及代码编辑等场景带来了革命性的推理提速。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fapoorvumang_prompt-lookup-decoding_b96f9963.png","apoorvumang","Apoorv Saxena","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fapoorvumang_d0f478cf.jpg","MTS, Inception Labs. Prev Adobe Research","Inception","Bangalore","apoorv@inceptionlabs.ai","apoorv_umang","apoorvumang.github.io","https:\u002F\u002Fgithub.com\u002Fapoorvumang",[83,87],{"name":84,"color":85,"percentage":86},"Jupyter Notebook","#DA5B0B",52.3,{"name":88,"color":89,"percentage":90},"Python","#3572A5",47.7,602,27,"2026-03-27T00:22:44","","实验环境使用单张 NVIDIA A100 40GB；理论上支持任何可运行解码器模型的 GPU，具体显存取决于所选模型大小","未说明",{"notes":98,"python":96,"dependencies":99},"该工具主要作为算法逻辑集成到 Hugging Face transformers 库或 vLLM 中使用，无需独立安装特定包。实验基于 Mistral-7B 模型进行，实际硬件需求随模型规模变化。适用于输入与输出有高重叠度的任务（如摘要、问答、代码编辑）。",[100,101],"torch","transformers",[35,14],"2026-03-27T02:49:30.150509","2026-04-06T20:03:42.385198",[106,111,116,120,125,129],{"id":107,"question_zh":108,"answer_zh":109,"source_url":110},19936,"使用 Prompt Lookup Decoding (PLD) 时，为什么在 temperature=0 (argmax) 模式下生成的结果与不使用 PLD 时不一致？","这通常是由于最新版本的 transformers 库中存在 bug 导致的。解决方案是将 transformers 版本降级到 4.37 或更早版本。例如，运行命令：pip install transformers==4.37。降级后，PLD 生成的结果应与预期一致。","https:\u002F\u002Fgithub.com\u002Fapoorvumang\u002Fprompt-lookup-decoding\u002Fissues\u002F5",{"id":112,"question_zh":113,"answer_zh":114,"source_url":115},19937,"遇到 AttributeError: 'MistralForCausalLM' object has no attribute '_extend_attention_mask' 错误怎么办？","该错误通常与 transformers 库的版本兼容性有关。虽然具体修复步骤需视环境而定，但参考同类问题（如 Issue #5），建议尝试调整 transformers 版本（如降级至 4.37 或升级至最新修复版）。此外，检查是否使用了正确的 CandidateGenerator 实现或官方 transformers 的 prompt_lookup_num_tokens 选项可能有助于规避此问题。","https:\u002F\u002Fgithub.com\u002Fapoorvumang\u002Fprompt-lookup-decoding\u002Fissues\u002F7",{"id":117,"question_zh":118,"answer_zh":119,"source_url":115},19938,"在不同 GPU（如 L4, T4, RTX3060）上使用 PLD 的性能表现如何？哪种实现方式加速效果最好？","根据用户测试数据，使用 transformers 原生支持的 prompt_lookup_num_tokens 选项通常在各种 GPU 上提供最佳的加速比（Speed up）。例如在 L4 上加速约 2.3 倍，在 T4 上加速约 2.2 倍。相比之下，自定义的 CandidateGenerator 实现与原代码差异不大，且在 T4 上表现不稳定。建议优先使用 transformers 内置的 generate 方法并设置 prompt_lookup_num_tokens 参数。",{"id":121,"question_zh":122,"answer_zh":123,"source_url":124},19939,"Prompt Lookup Decoding 与 LLMA (Large Language Model Acceleration) 有什么区别？","根据项目维护者的回复，Prompt Lookup Decoding 的核心思想与 LLMA 论文中提出的想法基本一致。因此，两者在原理上没有显著区别。项目方计划在后续工作中引用 LLMA 的相关工作，但目前未进行详细的对比实验，因为概念高度相似。","https:\u002F\u002Fgithub.com\u002Fapoorvumang\u002Fprompt-lookup-decoding\u002Fissues\u002F4",{"id":126,"question_zh":127,"answer_zh":128,"source_url":115},19940,"在 Google Colab T4 GPU 上运行 PLD 时行为异常，如何解决？","有用户反馈在 Colab T4 GPU 上，自定义实现的 PLD（包括原始代码和基于 CandidateGenerator 的修订版）表现奇怪，但使用 transformers 原生的 prompt_lookup_num_tokens 选项时行为正常。建议在 T4 环境下优先使用 transformers 内置的实现方式，避免使用自定义的生成逻辑以获得稳定性。",{"id":130,"question_zh":131,"answer_zh":132,"source_url":115},19941,"如何验证 PLD 实现的正确性并进行性能对比？","可以通过对比三种方式来验证：1) 原始自定义代码；2) 使用 CandidateGenerator 类的修订代码；3) transformers 库自带的 prompt_lookup_num_tokens 功能。用户提供的测试笔记本（candidate_generator_upload.ipynb 和 transformers_pld_upload.ipynb）可作为参考。测试表明，transformers 原生实现不仅速度最快，而且跨 GPU 兼容性最好。",[]]