[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-CStanKonrad--long_llama":3,"tool-CStanKonrad--long_llama":64},[4,17,27,35,43,56],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":16},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,3,"2026-04-05T11:01:52",[13,14,15],"开发框架","图像","Agent","ready",{"id":18,"name":19,"github_repo":20,"description_zh":21,"stars":22,"difficulty_score":23,"last_commit_at":24,"category_tags":25,"status":16},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 真正成长为懂上",138956,2,"2026-04-05T11:33:21",[13,15,26],"语言模型",{"id":28,"name":29,"github_repo":30,"description_zh":31,"stars":32,"difficulty_score":23,"last_commit_at":33,"category_tags":34,"status":16},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 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107662,"2026-04-03T11:11:01",[13,14,15],{"id":36,"name":37,"github_repo":38,"description_zh":39,"stars":40,"difficulty_score":23,"last_commit_at":41,"category_tags":42,"status":16},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[13,26],{"id":44,"name":45,"github_repo":46,"description_zh":47,"stars":48,"difficulty_score":23,"last_commit_at":49,"category_tags":50,"status":16},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",84991,"2026-04-05T10:45:23",[14,51,52,53,15,54,26,13,55],"数据工具","视频","插件","其他","音频",{"id":57,"name":58,"github_repo":59,"description_zh":60,"stars":61,"difficulty_score":10,"last_commit_at":62,"category_tags":63,"status":16},3128,"ragflow","infiniflow\u002Fragflow","RAGFlow 是一款领先的开源检索增强生成（RAG）引擎，旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体（Agent）能力相结合，不仅支持从各类文档中高效提取知识，还能让模型基于这些知识进行逻辑推理和任务执行。\n\n在大模型应用中，幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构（如表格、图表及混合排版），显著提升了信息检索的准确度，从而有效减少模型“胡编乱造”的现象，确保回答既有据可依又具备时效性。其内置的智能体机制更进一步，使系统不仅能回答问题，还能自主规划步骤解决复杂问题。\n\n这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统，还是致力于探索大模型在垂直领域落地的创新者，都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口，既降低了非算法背景用户的上手门槛，也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目，它正成为连接通用大模型与行业专有知识之间的重要桥梁。",77062,"2026-04-04T04:44:48",[15,14,13,26,54],{"id":65,"github_repo":66,"name":67,"description_en":68,"description_zh":69,"ai_summary_zh":70,"readme_en":71,"readme_zh":72,"quickstart_zh":73,"use_case_zh":74,"hero_image_url":75,"owner_login":76,"owner_name":77,"owner_avatar_url":78,"owner_bio":79,"owner_company":79,"owner_location":79,"owner_email":79,"owner_twitter":79,"owner_website":79,"owner_url":80,"languages":81,"stars":94,"forks":95,"last_commit_at":96,"license":97,"difficulty_score":23,"env_os":98,"env_gpu":99,"env_ram":100,"env_deps":101,"category_tags":108,"github_topics":79,"view_count":10,"oss_zip_url":79,"oss_zip_packed_at":79,"status":16,"created_at":109,"updated_at":110,"faqs":111,"releases":141},2686,"CStanKonrad\u002Flong_llama","long_llama","LongLLaMA is a large language model capable of handling long contexts. It is based on OpenLLaMA and fine-tuned with the Focused Transformer (FoT) method.","LongLLaMA 是一款专为处理超长文本上下文而设计的大型语言模型。它基于 OpenLLaMA 架构，并创新性地采用了“聚焦变换器”（Focused Transformer, FoT）方法进行微调，能够轻松驾驭长达 256k 甚至更多的 token 上下文，有效解决了传统模型在面对长篇文档、复杂代码库或海量对话历史时容易“遗忘”关键信息或无法完整输入的痛点。\n\n该项目的独特之处在于其高效的训练策略：FoT 技术允许模型仅在部分注意力层访问记忆缓存，从而实现在较短输入数据上的训练，却能赋予模型处理百万级 token 上下文的卓越能力。此外，LongLLaMA 提供了包括 3B 基础版、指令微调版以及针对代码优化的 Code 版本在内的多种模型权重，且部分版本采用宽松的 Apache 2.0 协议开源，可直接替换现有 LLaMA 实现中的模型。\n\nLongLLaMA 非常适合 AI 研究人员、大模型开发者以及需要处理长文本分析的企业用户。研究人员可利用其提供的 PyTorch 指令微调和 JAX 持续预训练代码探索上下文扩展机制；开发者则能将其集成到应用中，构建支持长文档摘要、全代码库理","LongLLaMA 是一款专为处理超长文本上下文而设计的大型语言模型。它基于 OpenLLaMA 架构，并创新性地采用了“聚焦变换器”（Focused Transformer, FoT）方法进行微调，能够轻松驾驭长达 256k 甚至更多的 token 上下文，有效解决了传统模型在面对长篇文档、复杂代码库或海量对话历史时容易“遗忘”关键信息或无法完整输入的痛点。\n\n该项目的独特之处在于其高效的训练策略：FoT 技术允许模型仅在部分注意力层访问记忆缓存，从而实现在较短输入数据上的训练，却能赋予模型处理百万级 token 上下文的卓越能力。此外，LongLLaMA 提供了包括 3B 基础版、指令微调版以及针对代码优化的 Code 版本在内的多种模型权重，且部分版本采用宽松的 Apache 2.0 协议开源，可直接替换现有 LLaMA 实现中的模型。\n\nLongLLaMA 非常适合 AI 研究人员、大模型开发者以及需要处理长文本分析的企业用户。研究人员可利用其提供的 PyTorch 指令微调和 JAX 持续预训练代码探索上下文扩展机制；开发者则能将其集成到应用中，构建支持长文档摘要、全代码库理解或长程对话的智能系统。无论是学术探索还是工程落地，LongLLaMA 都为突破长度限制提供了强大且灵活的基础设施。","\n\u003Cp align=\"center\" width=\"100%\">\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FCStanKonrad_long_llama_readme_16b65badca83.png\" alt=\"LongLLaMA\" style=\"width: 50%;  display: block; margin: auto;\">\u003C\u002Fp>\n\n# LongLLaMA: Focused Transformer Training for Context Scaling\n\n\n\n\u003Cdiv align=\"center\">\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Cth style=\"font-size: 120%\"> >_ 🎓 \u003Ca href=\"https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_code_7b_instruct\">LongLLaMA-Code 7B Instruct\u003C\u002Fa> 📑🗨 \u003C\u002Fth>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd align=\"center\">\n    \u003Ca  href=\"https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FCStanKonrad\u002Flong_llama\u002Fblob\u002Fmain\u002Flong_llama_code_instruct_colab.ipynb\">\u003Cimg src=\"https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg\">\u003C\u002Fa> &nbsp \u003Ca href=\"instruction_fine_tuning\u002FLongLLamaCode7BInstruct.md\">Learn more\u003C\u002Fa>\n    \u003C\u002Ftd>\n    \n \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n\u003C\u002Fdiv>\n\n\n\u003Cdiv align=\"center\">\n\n\u003Ctable>\n\n  \u003Ctr>\n  \u003Ctd align=\"center\">\n    \u003Cspan style=\"font-size:200%\">⇧\u003C\u002Fspan>\n  \u003C\u002Ftd>\n \u003C\u002Ftr>\n \n\u003C\u002Ftable>\n\n\u003C\u002Fdiv>\n\n\u003Cdiv align=\"center\">\n\n\u003Ctable>\n\n  \u003Ctr>\n  \u003Ctd align=\"center\">\n    \u003Cspan style=\"font-size:150%\">{\u003C\u002Fspan>\n    \u003C\u002Ftd>\n    \u003Ctd align=\"center\">\n    \u003Cspan style=\"font-size:110%\">\n    \u003Cb>\n    \u003Ca href=\"https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_code_7b\" tyle=\"margin-bottom:30px\">LongLLaMA-Code 7B\u003C\u002Fa>\n    \u003C\u002Fb>\n    \u003C\u002Fspan>\n    \u003C\u002Ftd>\n    \u003Ctd align=\"center\">\n    \u003Cspan style=\"font-size:150%\">}\u003C\u002Fspan>\n    \u003C\u002Ftd>\n\n \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n\u003Chr>\n\n\u003C\u002Fdiv>\n\n\n\u003Cdiv align=\"center\">\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Cth> \u003Ca href=\"https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b_instruct\">LongLLaMA-Instruct-3Bv1.1\u003C\u002Fa> \u003C\u002Fth>\n    \u003Cth> \u003Ca href=\"https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b_v1_1\">LongLLaMA-3Bv1.1\u003C\u002Fa>\u003C\u002Fth>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd align=\"center\">\n    \u003Ca  href=\"https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FCStanKonrad\u002Flong_llama\u002Fblob\u002Fmain\u002Flong_llama_instruct_colab.ipynb\">\u003Cimg src=\"https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg\">\u003C\u002Fa>\n    \u003C\u002Ftd>\n    \u003Ctd align=\"center\">\n    \u003Ca href=\"https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FCStanKonrad\u002Flong_llama\u002Fblob\u002Fmain\u002Flong_llama_colab.ipynb\">\u003Cimg src=\"https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg\">\u003C\u002Fa>\n    \u003C\u002Ftd>\n \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n\u003C\u002Fdiv>\n\n\u003Cdiv align=\"center\">\n\n [TLDR](#TLDR) | [Overview](#Overview) | [Usage](#Usage) | [LongLLaMA performance](#LongLLaMA-performance) | [Authors](#Authors) | [Citation](#Citation) | [License](#License) | [Acknowledgments](#Acknowledgments)\n \n [FoT continued pretraining](fot_continued_pretraining) | [Instruction tuning](instruction_fine_tuning)\n\n\u003C\u002Fdiv>\n\n## TLDR\nThis repository contains the research preview of **LongLLaMA, a large language model capable of handling long contexts of 256k tokens or even more**. \n\nLongLLaMA is built upon the foundation of [OpenLLaMA](https:\u002F\u002Fgithub.com\u002Fopenlm-research\u002Fopen_llama) and fine-tuned using the [Focused Transformer (FoT)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2307.03170) method.\nLongLLaMA Code is built upon the foundation of [Code Llama](https:\u002F\u002Fhuggingface.co\u002Fcodellama\u002FCodeLlama-7b-hf).\nWe release a smaller  3B base variant (not instruction tuned) of the LongLLaMA model on a permissive license (Apache 2.0) and inference code supporting longer contexts on [Hugging Face](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b). Our model weights can serve as the drop-in replacement of LLaMA in existing implementations (for short context up to 2048 tokens). Additionally, we provide evaluation results and comparisons against the original OpenLLaMA models.  \nIn addition to this, we release code for [instruction tuning (PyTorch)](instruction_fine_tuning\u002F) and [FoT continued pretraining (JAX)](fot_continued_pretraining\u002F).\n\n\n## Overview\n\n### Base models\n[Focused Transformer: Contrastive Training for Context Scaling](https:\u002F\u002Farxiv.org\u002Fabs\u002F2307.03170) (FoT) presents a simple method for endowing language models with the ability to handle context consisting possibly of millions of tokens while training on significantly shorter input. FoT permits a subset of attention layers to access a memory cache of (key, value) pairs to extend the context length. The distinctive aspect of FoT is its training procedure, drawing from contrastive learning. Specifically, we deliberately expose the memory attention layers to both relevant and irrelevant keys (like negative samples from unrelated documents). This strategy incentivizes the model to differentiate keys connected with semantically diverse values, thereby enhancing their structure. This, in turn, makes it possible to extrapolate the effective context length much beyond what is seen in training. \n\n\n**LongLLaMA** is an [OpenLLaMA](https:\u002F\u002Fgithub.com\u002Fopenlm-research\u002Fopen_llama) model finetuned with the FoT method,\nwith three layers used for context extension. **Crucially, LongLLaMA is able to extrapolate much beyond the context length seen in training: $8k$. E.g., in the passkey retrieval task, it can handle inputs of length $256k$**.  \n**LongLLaMA Code** is a [Code Llama](https:\u002F\u002Fhuggingface.co\u002Fcodellama\u002FCodeLlama-7b-hf) model finetuned with the FoT method.\n\n\n\u003Cdiv align=\"center\">\n\n|  | [LongLLaMA-3B](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b) | [LongLLaMA-3Bv1.1](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b_v1_1) | [LongLLaMA-Code 7B](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_code_7b) |\n|----------------|----------|----------|-----------|\n| Source model         | [OpenLLaMA-3B](https:\u002F\u002Fhuggingface.co\u002Fopenlm-research\u002Fopen_llama_3b_easylm)      | [OpenLLaMA-3Bv2](https:\u002F\u002Fhuggingface.co\u002Fopenlm-research\u002Fopen_llama_3b_v2_easylm) | [CodeLLaMA-7b-hf](https:\u002F\u002Fhuggingface.co\u002Fcodellama\u002FCodeLlama-7b-hf)       |\n| Source model tokens     | 1T      |  1 T |  2T + 0.5 T       |\n| Fine-tuning tokens  | 10B     | 5B | 35B     | - |\n| Memory layers         |  6, 12, 18        |   6, 12, 18        |  8, 16, 24        |\n\n\u003C\u002Fdiv>\n\n\n### FoT continued pretraining\nIn the [fot_continued_pretraining](fot_continued_pretraining\u002F) subfolder, we provide the code that can be used to tune LLaMA models with FoT.  \nThis code is written in [JAX](https:\u002F\u002Fjax.readthedocs.io\u002Fen\u002Flatest\u002Fnotebooks\u002Fquickstart.html) & [Flax](https:\u002F\u002Fflax.readthedocs.io\u002Fen\u002Flatest\u002Fguides\u002Fflax_basics.html) and based on [EasyLM](https:\u002F\u002Fgithub.com\u002Fyoung-geng\u002FEasyLM).\n\n### Instruction\u002FChat tuning\n\nIn the [instruction_fine_tuning](instruction_fine_tuning\u002F) subfolder, we provide the code that was used to create [LongLLaMA-Instruct-3Bv1.1](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b_instruct), an instruction-tuned version of [LongLLaMA-3Bv1.1](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b_v1_1). We used [OpenOrca](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002FOpen-Orca\u002FOpenOrca) (instructions) and [zetavg\u002FShareGPT-Processed](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fzetavg\u002FShareGPT-Processed) (chat) datasets for tuning.  \nThis code utilizes [PyTorch](https:\u002F\u002Fpytorch.org\u002F) and [Hugging Face trainer](https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Ftransformers\u002Fv4.30.0\u002Fen\u002Fmain_classes\u002Ftrainer).\n\n### Inference code\nIn the [src](src\u002F) subfolder we provide inference code for FoT models.  \nThe code is written in [PyTorch](https:\u002F\u002Fpytorch.org\u002F) and based on [Hugging Face implementation of LLaMA](https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Ftransformers\u002Fmain\u002Fmodel_doc\u002Fllama).  \nThe code should support standard Hugging Face API. For more details see the [Usage](#Usage) section.\n\n\n## Usage\n\nSee also: \n* [Colab with LongLLaMA-Instruct-3Bv1.1](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FCStanKonrad\u002Flong_llama\u002Fblob\u002Fmain\u002Flong_llama_instruct_colab.ipynb).\n* [Colab with an example usage of base LongLLaMA](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FCStanKonrad\u002Flong_llama\u002Fblob\u002Fmain\u002Flong_llama_colab.ipynb).\n### Requirements\n```\npip install --upgrade pip\npip install transformers==4.33.2 sentencepiece accelerate\n```\n\n### Loading model\n```python\nimport torch\nfrom transformers import LlamaTokenizer, AutoModelForCausalLM\n\ntokenizer = LlamaTokenizer.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\")\nmodel = AutoModelForCausalLM.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\", \n                                            torch_dtype=torch.float32, \n                                            trust_remote_code=True)\n```\n\n### Input handling and generation\nLongLLaMA uses the Hugging Face interface, the long input given to the model will be \nsplit into context windows and loaded into the memory cache.\n```python\nprompt = \"My name is Julien and I like to\"\ninput_ids = tokenizer(prompt, return_tensors=\"pt\").input_ids\noutputs = model(input_ids=input_ids)\n```\nDuring the model call, one can provide the parameter `last_context_length` (default $1024$), which specifies the number of tokens left in the last context window. Tuning this parameter can improve generation as the first layers do not have access to memory. See details in [How LongLLaMA handles long inputs](#How-LongLLaMA-handles-long-inputs).\n\n```python\ngeneration_output = model.generate(\n    input_ids=input_ids,\n    max_new_tokens=256,\n    num_beams=1,\n    last_context_length=1792,\n    do_sample=True,\n    temperature=1.0,\n)\nprint(tokenizer.decode(generation_output[0]))\n```\n\n### Additional configuration\nLongLLaMA has several other parameters:\n* `mem_layers` specifies layers endowed with memory (should be either an empty list or a list of all memory layers specified in the description of the checkpoint).\n* `mem_dtype` allows changing the type of memory cache\n* `mem_attention_grouping` can trade off speed for reduced memory usage. \n  When equal to `(4, 2048)`, the memory layers will process at most $4*2048$ queries at once ($4$ heads and $2048$ queries for each head).\n\n```python\nimport torch\nfrom transformers import LlamaTokenizer, AutoModelForCausalLM\n\ntokenizer = LlamaTokenizer.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\")\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"syzymon\u002Flong_llama_3b_v1_1\", torch_dtype=torch.float32, \n    mem_layers=[], \n    mem_dtype='bfloat16',\n    trust_remote_code=True,\n    mem_attention_grouping=(4, 2048),\n)\n```\n\n\n### Drop-in use with LLaMA code\n LongLLaMA checkpoints can also be used as a drop-in replacement for LLaMA checkpoints in [Hugging Face implementation of LLaMA](https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Ftransformers\u002Fmain\u002Fmodel_doc\u002Fllama), but in this case, they will be limited to the original context length of $2048$.\n\n```python\nfrom transformers import LlamaTokenizer, LlamaForCausalLM\nimport torch\n\ntokenizer = LlamaTokenizer.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\")\nmodel = LlamaForCausalLM.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\", torch_dtype=torch.float32)\n```\n\n\n### How LongLLaMA handles long inputs\nInputs over $lctx=2048$ ($lctx=4096$ for LongLLaMA Code) tokens are automatically split into windows $w_1, \\ldots, w_m$. The first $m-2$ windows contain $lctx$ tokens each, $w_{m-1}$ has no more than $lctx$ tokens, and $w_m$ contains the number of tokens specified by `last_context_length`. The model processes the windows one by one extending the memory cache after each. If `use_cache` is `True`, then the last window will not be loaded to the memory cache but to the local (generation) cache.\n\nThe memory cache stores $(key, value)$ pairs for each head of the specified memory layers `mem_layers`. In addition to this, it stores attention masks. \n\nIf `use_cache=True` (which is the case in generation), LongLLaMA will use two caches: the memory cache for the specified layers and the local (generation) cache for all layers. When the local cache exceeds $lctx$ elements, its content is moved to the memory cache for the memory layers.\n\nFor simplicity, context extension is realized with a memory cache and full attention in this repo. Replacing this simple mechanism with a KNN search over an external database is possible with systems like [Faiss](https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Ffaiss). This potentially would enable further context length scaling. We leave this as a future work.\n\n\n## LongLLaMA performance\nWe present some illustrative examples of LongLLaMA results. Refer to our paper [Focused Transformer: Contrastive Training for Context Scaling](https:\u002F\u002Farxiv.org\u002Fabs\u002F2307.03170) for more details.\n\nWe manage to achieve good performance on the passkey retrieval task from [Landmark Attention: Random-Access Infinite Context Length for Transformers](https:\u002F\u002Farxiv.org\u002Fabs\u002F2305.16300). The code for generating the prompt and running the model is located in `examples\u002Fpasskey.py`. \n\n\u003Cp align=\"center\" width=\"100%\">\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FCStanKonrad_long_llama_readme_07d73adcc5f6.png\" alt=\"LongLLaMA\" style=\"width: 70%; min-width: 300px; display: block; margin: auto;\">\n\u003C\u002Fp>\n\nOur LongLLaMA 3B model also shows improvements when using long context on two downstream tasks, TREC question classification and WebQS question answering. \n\u003Cdiv align=\"center\">\n\n\n| Context\u002FDataset | TREC  | WebQS |\n| --- | --- | --- |\n| $2K$ | 67.0 |  21.2 |\n| $4K$ | 71.6 | 21.4 |\n| $6K$ | 72.9 | 22.2 |\n| $8K$ | **73.3** | **22.4** |\n\n\u003C\u002Fdiv>\n\nLongLLaMA retains performance on tasks that do not require long context. \n\nIn particular, LongLLaMA-Code 7B improves reasoning (GSM8K) and knowledge (MMLU) due to code fine-tuning:\n\n\u003Cp align=\"center\" width=\"100%\">\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FCStanKonrad_long_llama_readme_e80026369fb9.png\" alt=\"LongLLaMA\" style=\"width: 70%; min-width: 300px; display: block; margin: auto;\">\n\u003C\u002Fp>\n\nWe provide a comparison with OpenLLaMA\non [lm-evaluation-harness](https:\u002F\u002Fgithub.com\u002FEleutherAI\u002Flm-evaluation-harness) in the zero-shot setting. \n\u003Cdiv align=\"center\">\n\n| Task\u002FMetric | OpenLLaMA-3B | LongLLaMA-3B |\n|----------------|----------|-----------|\n| anli_r1\u002Facc | 0.33 | 0.32 |\n| anli_r2\u002Facc | 0.32 | 0.33 |\n| anli_r3\u002Facc | 0.35 | 0.35 |\n| arc_challenge\u002Facc | 0.34 | 0.34 |\n| arc_challenge\u002Facc_norm | 0.37 | 0.37 |\n| arc_easy\u002Facc | 0.69 | 0.68 |\n| arc_easy\u002Facc_norm | 0.65 | 0.63 |\n| boolq\u002Facc | 0.68 | 0.68 |\n| hellaswag\u002Facc | 0.49 | 0.48 |\n| hellaswag\u002Facc_norm | 0.67 | 0.65 |\n| openbookqa\u002Facc | 0.27 | 0.28 |\n| openbookqa\u002Facc_norm | 0.40 | 0.38 |\n| piqa\u002Facc | 0.75 | 0.73 |\n| piqa\u002Facc_norm | 0.76 | 0.75 |\n| record\u002Fem | 0.88 | 0.87 |\n| record\u002Ff1 | 0.89 | 0.87 |\n| rte\u002Facc | 0.58 | 0.60 |\n| truthfulqa_mc\u002Fmc1 | 0.22 | 0.24 |\n| truthfulqa_mc\u002Fmc2 | 0.35 | 0.38 |\n| wic\u002Facc | 0.48 | 0.50 |\n| winogrande\u002Facc | 0.62 | 0.60 |\n| Avg score | 0.53 | 0.53 |\n\n\u003C\u002Fdiv>\n\nStarting with v1.1 models we have decided to use [EleutherAI](https:\u002F\u002Fgithub.com\u002FEleutherAI) implementation of [lm-evaluation-harness](https:\u002F\u002Fgithub.com\u002FEleutherAI\u002Flm-evaluation-harness) with a slight modification, that adds `\u003Cbos>` token at beginning of input sequence. The results are provided in the table below.\n\n\u003Cdiv align=\"center\">\n\n| description            | LongLLaMA-3B | OpenLLaMA-3Bv2 | LongLLaMA-3Bv1.1 | LongLLaMA-Instruct-3Bv1.1 |\n|:-----------------------|:--------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------|:--------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------|\n| anli_r1\u002Facc            | 0.32                                                                                  | 0.33                                                                               | 0.31                                                                      | 0.33                                                                                         |\n| anli_r2\u002Facc            | 0.33                                                                                  | 0.35                                                                               | 0.33                                                                      | 0.35                                                                                         |\n| anli_r3\u002Facc            | 0.35                                                                                  | 0.38                                                                               | 0.35                                                                      | 0.38                                                                                         |\n| arc_challenge\u002Facc      | 0.34                                                                                  | 0.33                                                                               | 0.32                                                                      | 0.36                                                                                         |\n| arc_challenge\u002Facc_norm | 0.37                                                                                  | 0.36                                                                               | 0.36                                                                      | 0.37                                                                                         |\n| arc_easy\u002Facc           | 0.67                                                                                  | 0.68                                                                               | 0.68                                                                      | 0.7                                                                                          |\n| arc_easy\u002Facc_norm      | 0.63                                                                                  | 0.63                                                                               | 0.63                                                                      | 0.63                                                                                         |\n| boolq\u002Facc              | 0.68                                                                                  | 0.67                                                                               | 0.66                                                                      | 0.77                                                                                         |\n| hellaswag\u002Facc          | 0.48                                                                                  | 0.53                                                                               | 0.52                                                                      | 0.52                                                                                         |\n| hellaswag\u002Facc_norm     | 0.65                                                                                  | 0.7                                                                                | 0.69                                                                      | 0.68                                                                                         |\n| openbookqa\u002Facc         | 0.28                                                                                  | 0.28                                                                               | 0.28                                                                      | 0.28                                                                                         |\n| openbookqa\u002Facc_norm    | 0.38                                                                                  | 0.39                                                                               | 0.37                                                                      | 0.41                                                                                         |\n| piqa\u002Facc               | 0.73                                                                                  | 0.77                                                                               | 0.77                                                                      | 0.78                                                                                         |\n| piqa\u002Facc_norm          | 0.75                                                                                  | 0.78                                                                               | 0.77                                                                      | 0.77                                                                                         |\n| record\u002Fem              | 0.87                                                                                  | 0.87                                                                               | 0.86                                                                      | 0.85                                                                                         |\n| record\u002Ff1              | 0.88                                                                                  | 0.88                                                                               | 0.87                                                                      | 0.86                                                                                         |\n| rte\u002Facc                | 0.6                                                                                   | 0.53                                                                               | 0.62                                                                      | 0.7                                                                                          |\n| truthfulqa_mc\u002Fmc1      | 0.24                                                                                  | 0.22                                                                               | 0.21                                                                      | 0.25                                                                                         |\n| truthfulqa_mc\u002Fmc2      | 0.38                                                                                  | 0.35                                                                               | 0.35                                                                      | 0.4                                                                                          |\n| wic\u002Facc                | 0.5                                                                                   | 0.5                                                                                | 0.5                                                                       | 0.54                                                                                         |\n| winogrande\u002Facc         | 0.6                                                                                   | 0.66                                                                               | 0.63                                                                      | 0.65                                                                                         |\n| Avg score                   | 0.53                                                                                  | 0.53                                                                               | 0.53                                                                      | 0.55                                                                                         |\n\n\u003C\u002Fdiv>\n\n\nWe also provide the results on human-eval. We cut the generated text after either\n*  `\"\\ndef \"`\n*  `\"\\nclass \"`\n*  `\"\\nif __name__\"`\n\n\u003Cdiv align=\"center\">\n\n|  | OpenLLaMA-3Bv2 | LongLLaMA-3Bv1.1 | LongLLaMA-Instruct-3Bv1.1 |\n| - | - | - | - |\n| pass@1| 0.09| 0.12 |  0.12 |\n\n\u003C\u002Fdiv>\n\n## Authors\n- [Szymon Tworkowski](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=1V8AeXYAAAAJ&hl=en)\n- [Konrad Staniszewski](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=CM6PCBYAAAAJ)\n- [Mikołaj Pacek](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=eh6iEbQAAAAJ&hl=en&oi=ao)\n- [Henryk Michalewski](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=YdHW1ycAAAAJ&hl=en)\n- [Yuhuai Wu](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=bOQGfFIAAAAJ&hl=en)\n- [Piotr Miłoś](https:\u002F\u002Fscholar.google.pl\u002Fcitations?user=Se68XecAAAAJ&hl=pl&oi=ao)\n\n\n## Citation\nTo cite this work please use\n```bibtex\n@misc{tworkowski2023focused,\n      title={Focused Transformer: Contrastive Training for Context Scaling}, \n      author={Szymon Tworkowski and Konrad Staniszewski and Mikołaj Pacek and Yuhuai Wu and Henryk Michalewski and Piotr Miłoś},\n      year={2023},\n      eprint={2307.03170},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n```\n\n\n## License\nThe source code and base LongLLaMA 3B models checkpoints are licensed under [Apache License, Version 2.0](http:\u002F\u002Fwww.apache.org\u002Flicenses\u002FLICENSE-2.0).  \nThe instruction\u002Fchat tuned models are for research purposes only.  \nFor the LongLLaMA-Code 7B see [codellama\u002FCodeLlama-7b-hf](https:\u002F\u002Fhuggingface.co\u002Fcodellama\u002FCodeLlama-7b-hf\u002Fblob\u002Fmain\u002FLICENSE) license.  \nLongLLaMA-Code 7B Instruct is LongLLaMA-Code 7B tuned on [TIGER-Lab\u002FMathInstruct](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002FTIGER-Lab\u002FMathInstruct), [OpenOrca](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002FOpen-Orca\u002FOpenOrca) and [ShareGPT-Processed](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fzetavg\u002FShareGPT-Processed) datasets.  \nSome of the examples use external code (see headers of files for copyright notices and licenses).\n\n## Acknowledgments\nWe gratefully acknowledge the TPU Research Cloud program, which was instrumental to our research by providing significant computational resources. We are also grateful to Xinyang Geng and Hao Liu for releasing [OpenLLaMA](https:\u002F\u002Fgithub.com\u002Fopenlm-research\u002Fopen_llama) checkpoints and the [EasyLM](https:\u002F\u002Fgithub.com\u002Fyoung-geng\u002FEasyLM) library.\n\nSpecial thanks to [Keiran Paster](https:\u002F\u002Ftwitter.com\u002Fkeirp1) for providing immensely valuable suggestions about the pre-training data for LongLLaMA-Code.\n\nWe would like to thank [Xiaosong,He](https:\u002F\u002Fgithub.com\u002Fhxs91) for suggestions on how to improve the explanations of cross-batch code.\n","\u003Cp align=\"center\" width=\"100%\">\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FCStanKonrad_long_llama_readme_16b65badca83.png\" alt=\"LongLLaMA\" style=\"width: 50%;  display: block; margin: auto;\">\u003C\u002Fp>\n\n# LongLLaMA：面向上下文扩展的聚焦Transformer训练\n\n\n\n\u003Cdiv align=\"center\">\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Cth style=\"font-size: 120%\"> >_ 🎓 \u003Ca href=\"https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_code_7b_instruct\">LongLLaMA-Code 7B 指令版\u003C\u002Fa> 📑🗨 \u003C\u002Fth>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd align=\"center\">\n    \u003Ca  href=\"https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FCStanKonrad\u002Flong_llama\u002Fblob\u002Fmain\u002Flong_llama_code_instruct_colab.ipynb\">\u003Cimg src=\"https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg\">\u003C\u002Fa> &nbsp \u003Ca href=\"instruction_fine_tuning\u002FLongLLamaCode7BInstruct.md\">了解更多\u003C\u002Fa>\n    \u003C\u002Ftd>\n    \n \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n\u003C\u002Fdiv>\n\n\n\u003Cdiv align=\"center\">\n\n\u003Ctable>\n\n  \u003Ctr>\n  \u003Ctd align=\"center\">\n    \u003Cspan style=\"font-size:200%\">⇧\u003C\u002Fspan>\n  \u003C\u002Ftd>\n \u003C\u002Ftr>\n \n\u003C\u002Ftable>\n\n\u003C\u002Fdiv>\n\n\u003Cdiv align=\"center\">\n\n\u003Ctable>\n\n  \u003Ctr>\n  \u003Ctd align=\"center\">\n    \u003Cspan style=\"font-size:150%\">{\u003C\u002Fspan>\n    \u003C\u002Ftd>\n    \u003Ctd align=\"center\">\n    \u003Cspan style=\"font-size:110%\">\n    \u003Cb>\n    \u003Ca href=\"https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_code_7b\" tyle=\"margin-bottom:30px\">LongLLaMA-Code 7B\u003C\u002Fa>\n    \u003C\u002Fb>\n    \u003C\u002Fspan>\n    \u003C\u002Ftd>\n    \u003Ctd align=\"center\">\n    \u003Cspan style=\"font-size:150%\">}\u003C\u002Fspan>\n    \u003C\u002Ftd>\n\n \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n\u003Chr>\n\n\u003C\u002Fdiv>\n\n\n\u003Cdiv align=\"center\">\n\n\u003Ctable>\n  \u003Ctr>\n    \u003Cth> \u003Ca href=\"https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b_instruct\">LongLLaMA-指令-3Bv1.1\u003C\u002Fa> \u003C\u002Fth>\n    \u003Cth> \u003Ca href=\"https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b_v1_1\">LongLLaMA-3Bv1.1\u003C\u002Fa>\u003C\u002Fth>\n  \u003C\u002Ftr>\n  \u003Ctr>\n    \u003Ctd align=\"center\">\n    \u003Ca  href=\"https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FCStanKonrad\u002Flong_llama\u002Fblob\u002Fmain\u002Flong_llama_instruct_colab.ipynb\">\u003Cimg src=\"https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg\">\u003C\u002Fa>\n    \u003C\u002Ftd>\n    \u003Ctd align=\"center\">\n    \u003Ca href=\"https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FCStanKonrad\u002Flong_llama\u002Fblob\u002Fmain\u002Flong_llama_colab.ipynb\">\u003Cimg src=\"https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg\">\u003C\u002Fa>\n    \u003C\u002Ftd>\n \u003C\u002Ftr>\n\u003C\u002Ftable>\n\n\u003C\u002Fdiv>\n\n\u003Cdiv align=\"center\">\n\n [简述](#TLDR) | [概述](#Overview) | [使用方法](#Usage) | [LongLLaMA性能](#LongLLaMA-performance) | [作者](#Authors) | [引用](#Citation) | [许可证](#License) | [致谢](#Acknowledgments)\n \n [FoT持续预训练](fot_continued_pretraining) | [指令调优](instruction_fine_tuning)\n\n\u003C\u002Fdiv>\n\n## 简述\n本仓库包含 **LongLLaMA 的研究预览版，这是一款能够处理长达 256k 个标记甚至更多上下文的大型语言模型**。\n\nLongLLaMA 基于 [OpenLLaMA](https:\u002F\u002Fgithub.com\u002Fopenlm-research\u002Fopen_llama) 构建，并采用 [聚焦Transformer (FoT)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2307.03170) 方法进行微调。\nLongLLaMA Code 则基于 [Code Llama](https:\u002F\u002Fhuggingface.co\u002Fcodellama\u002FCodeLlama-7b-hf) 构建。\n我们以宽松的许可证（Apache 2.0）发布了一个较小的 3B 基础版本（未进行指令调优）的 LongLLaMA 模型，并在 [Hugging Face](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b) 上提供了支持更长上下文的推理代码。我们的模型权重可以作为现有实现中 LLaMA 的直接替代品（适用于短上下文，最多 2048 个标记）。此外，我们还提供了评估结果以及与原始 OpenLLaMA 模型的对比。\n\n除此之外，我们还发布了用于 [指令调优（PyTorch）](instruction_fine_tuning\u002F) 和 [FoT 持续预训练（JAX）](fot_continued_pretraining\u002F) 的代码。\n\n## 概述\n\n### 基础模型\n[聚焦Transformer：面向上下文扩展的对比学习](https:\u002F\u002Farxiv.org\u002Fabs\u002F2307.03170)（FoT）提出了一种简单的方法，使语言模型能够在训练时使用显著较短的输入，却具备处理可能包含数百万个标记的上下文的能力。FoT 允许一部分注意力层访问由 (key, value) 对组成的内存缓存，从而扩展上下文长度。FoT 的独特之处在于其训练过程，借鉴了对比学习的思想。具体而言，我们会有意将记忆注意力层暴露于相关和不相关的 key 中（类似于来自无关文档的负样本）。这一策略促使模型区分与语义多样化的 value 相关的 key，从而增强其结构。这样一来，就能将有效上下文长度外推到远超训练时所见的范围。\n\n\n**LongLLaMA** 是一款基于 [OpenLLaMA](https:\u002F\u002Fgithub.com\u002Fopenlm-research\u002Fopen_llama) 并采用 FoT 方法微调的模型，其中三层层被用于上下文扩展。**关键在于，LongLLaMA 能够将上下文长度外推至远超训练时所见的水平：8k。例如，在密钥检索任务中，它能够处理长度达 256k 的输入**。\n**LongLLaMA Code** 是一款基于 [Code Llama](https:\u002F\u002Fhuggingface.co\u002Fcodellama\u002FCodeLlama-7b-hf) 并采用 FoT 方法微调的模型。\n\n\n\u003Cdiv align=\"center\">\n\n|  | [LongLLaMA-3B](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b) | [LongLLaMA-3Bv1.1](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b_v1_1) | [LongLLaMA-Code 7B](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_code_7b) |\n|----------------|----------|----------|-----------|\n| 来源模型         | [OpenLLaMA-3B](https:\u002F\u002Fhuggingface.co\u002Fopenlm-research\u002Fopen_llama_3b_easylm)      | [OpenLLaMA-3Bv2](https:\u002F\u002Fhuggingface.co\u002Fopenlm-research\u002Fopen_llama_3b_v2_easylm) | [CodeLLaMA-7b-hf](https:\u002F\u002Fhuggingface.co\u002Fcodellama\u002FCodeLlama-7b-hf)       |\n| 来源模型标记数     | 1T      |  1 T |  2T + 0.5 T       |\n| 微调标记数  | 10B     | 5B | 35B     | - |\n| 内存层         |  6, 12, 18        |   6, 12, 18        |  8, 16, 24        |\n\n\u003C\u002Fdiv>\n\n\n### FoT 持续预训练\n在 [fot_continued_pretraining](fot_continued_pretraining\u002F) 子文件夹中，我们提供了可用于使用 FoT 调整 LLaMA 模型的代码。\n该代码使用 [JAX](https:\u002F\u002Fjax.readthedocs.io\u002Fen\u002Flatest\u002Fnotebooks\u002Fquickstart.html) 和 [Flax](https:\u002F\u002Fflax.readthedocs.io\u002Fen\u002Flatest\u002Fguides\u002Fflax_basics.html) 编写，并基于 [EasyLM](https:\u002F\u002Fgithub.com\u002Fyoung-geng\u002FEasyLM)。\n\n### 指令\u002F聊天调优\n\n在 [instruction_fine_tuning](instruction_fine_tuning\u002F) 子文件夹中，我们提供了用于创建 [LongLLaMA-指令-3Bv1.1](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b_instruct) 的代码，它是 [LongLLaMA-3Bv1.1](https:\u002F\u002Fhuggingface.co\u002Fsyzymon\u002Flong_llama_3b_v1_1) 的指令调优版本。我们在调优过程中使用了 [OpenOrca](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002FOpen-Orca\u002FOpenOrca)（指令）和 [zetavg\u002FShareGPT-Processed](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fzetavg\u002FShareGPT-Processed)（聊天）数据集。\n该代码利用了 [PyTorch](https:\u002F\u002Fpytorch.org\u002F) 和 [Hugging Face 训练器](https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Ftransformers\u002Fv4.30.0\u002Fen\u002Fmain_classes\u002Ftrainer)。\n\n### 推理代码\n在 [src](src\u002F) 子文件夹中，我们提供了 FoT 模型的推理代码。  \n该代码使用 [PyTorch](https:\u002F\u002Fpytorch.org\u002F) 编写，并基于 [Hugging Face 的 LLaMA 实现](https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Ftransformers\u002Fmain\u002Fmodel_doc\u002Fllama)。  \n代码应支持标准的 Hugging Face API。更多详情请参阅 [使用说明](#Usage) 部分。\n\n\n## 使用说明\n\n另请参阅：\n* [带有 LongLLaMA-Instruct-3Bv1.1 的 Colab 笔记本](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FCStanKonrad\u002Flong_llama\u002Fblob\u002Fmain\u002Flong_llama_instruct_colab.ipynb)。\n* [带有基础 LongLLaMA 示例用法的 Colab 笔记本](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FCStanKonrad\u002Flong_llama\u002Fblob\u002Fmain\u002Flong_llama_colab.ipynb)。\n### 需求\n```\npip install --upgrade pip\npip install transformers==4.33.2 sentencepiece accelerate\n```\n\n### 加载模型\n```python\nimport torch\nfrom transformers import LlamaTokenizer, AutoModelForCausalLM\n\ntokenizer = LlamaTokenizer.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\")\nmodel = AutoModelForCausalLM.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\", \n                                            torch_dtype=torch.float32, \n                                            trust_remote_code=True)\n```\n\n### 输入处理与生成\nLongLLaMA 使用 Hugging Face 接口，输入给模型的长文本将被分割成上下文窗口并加载到内存缓存中。\n```python\nprompt = \"My name is Julien and I like to\"\ninput_ids = tokenizer(prompt, return_tensors=\"pt\").input_ids\noutputs = model(input_ids=input_ids)\n```\n在调用模型时，可以提供参数 `last_context_length`（默认值为 $1024$），用于指定最后一个上下文窗口中保留的标记数。调整此参数可以改善生成效果，因为模型的前几层无法访问内存缓存。详细信息请参阅 [LongLLaMA 如何处理长输入](#How-LongLLaMA-handles-long-inputs)。\n\n```python\ngeneration_output = model.generate(\n    input_ids=input_ids,\n    max_new_tokens=256,\n    num_beams=1,\n    last_context_length=1792,\n    do_sample=True,\n    temperature=1.0,\n)\nprint(tokenizer.decode(generation_output[0]))\n```\n\n### 其他配置\nLongLLaMA 还有若干其他参数：\n* `mem_layers` 用于指定具有记忆功能的层（应为空列表或检查点描述中列出的所有记忆层的列表）。\n* `mem_dtype` 允许更改内存缓存的数据类型。\n* `mem_attention_grouping` 可以在速度和减少内存使用之间进行权衡。  \n  当设置为 `(4, 2048)` 时，记忆层每次最多可同时处理 $4 \\times 2048$ 个查询（每组 4 个注意力头，每个头处理 2048 个查询）。\n\n```python\nimport torch\nfrom transformers import LlamaTokenizer, AutoModelForCausalLM\n\ntokenizer = LlamaTokenizer.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\")\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"syzymon\u002Flong_llama_3b_v1_1\", torch_dtype=torch.float32, \n    mem_layers=[], \n    mem_dtype='bfloat16',\n    trust_remote_code=True,\n    mem_attention_grouping=(4, 2048),\n)\n```\n\n\n### 作为 LLaMA 代码的直接替换\nLongLLaMA 检查点也可以作为 [Hugging Face 的 LLaMA 实现](https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Ftransformers\u002Fmain\u002Fmodel_doc\u002Fllama) 中 LLaMA 检查点的直接替换使用，但在这种情况下，它们将被限制为原始的 $2048$ 标记上下文长度。\n\n```python\nfrom transformers import LlamaTokenizer, LlamaForCausalLM\nimport torch\n\ntokenizer = LlamaTokenizer.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\")\nmodel = LlamaForCausalLM.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\", torch_dtype=torch.float32)\n```\n\n\n### LongLLaMA 如何处理长输入\n超过 $lctx=2048$（对于 LongLLaMA Code 为 $lctx=4096$）标记的输入会自动被分割成窗口 $w_1, \\ldots, w_m$。前 $m-2$ 个窗口每个包含 $lctx$ 个标记，$w_{m-1}$ 包含不超过 $lctx$ 个标记，而 $w_m$ 则包含由 `last_context_length` 指定的标记数。模型会逐个处理这些窗口，并在每次处理后扩展内存缓存。如果 `use_cache` 设置为 `True`，则最后一个窗口不会被加载到内存缓存中，而是会被加载到本地（生成）缓存中。\n\n内存缓存为指定的记忆层中的每个注意力头存储 $(key, value)$ 对。此外，它还存储注意力掩码。\n\n如果 `use_cache=True`（即在生成过程中），LongLLaMA 将使用两种缓存：用于指定层的记忆缓存，以及用于所有层的本地（生成）缓存。当本地缓存中的元素数量超过 $lctx$ 时，其内容会被移动到记忆层的内存缓存中。\n\n为简化起见，本仓库中通过内存缓存和全注意力机制实现了上下文扩展。未来可以通过像 [Faiss](https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Ffaiss) 这样的系统，用外部数据库中的 KNN 搜索来替代这一简单机制，从而进一步扩展上下文长度。我们将此作为未来的工作方向。\n\n\n## LongLLaMA 性能\n我们展示了一些 LongLLaMA 结果的示例。更多细节请参阅我们的论文 [Focused Transformer: Contrastive Training for Context Scaling](https:\u002F\u002Farxiv.org\u002Fabs\u002F2307.03170)。\n\n我们在来自 [Landmark Attention: Random-Access Infinite Context Length for Transformers](https:\u002F\u002Farxiv.org\u002Fabs\u002F2305.16300) 的密码检索任务上取得了良好的效果。生成提示和运行模型的代码位于 `examples\u002Fpasskey.py` 中。\n\n\u003Cp align=\"center\" width=\"100%\">\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FCStanKonrad_long_llama_readme_07d73adcc5f6.png\" alt=\"LongLLaMA\" style=\"width: 70%; min-width: 300px; display: block; margin: auto;\">\n\u003C\u002Fp>\n\n我们的 LongLLaMA 3B 模型在两个下游任务——TREC 问题分类和 WebQS 问答——上也表现出使用长上下文时的改进效果。\n\u003Cdiv align=\"center\">\n\n\n| 上下文\u002F数据集 | TREC  | WebQS |\n| --- | --- | --- |\n| $2K$ | 67.0 |  21.2 |\n| $4K$ | 71.6 | 21.4 |\n| $6K$ | 72.9 | 22.2 |\n| $8K$ | **73.3** | **22.4** |\n\n\u003C\u002Fdiv>\n\nLongLLaMA 在不需要长上下文的任务上也能保持性能。\n\n特别是，经过代码微调后的 LongLLaMA-Code 7B 在推理能力（GSM8K）和知识储备（MMLU）方面都有所提升：\n\n\u003Cp align=\"center\" width=\"100%\">\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FCStanKonrad_long_llama_readme_e80026369fb9.png\" alt=\"LongLLaMA\" style=\"width: 70%; min-width: 300px; display: block; margin: auto;\">\n\u003C\u002Fp>\n\n我们在零样本设置下，使用 [lm-evaluation-harness](https:\u002F\u002Fgithub.com\u002FEleutherAI\u002Flm-evaluation-harness) 对比了 OpenLLaMA 和 LongLLaMA 的表现。\n\u003Cdiv align=\"center\">\n\n| 任务\u002F指标 | OpenLLaMA-3B | LongLLaMA-3B |\n|----------------|----------|-----------|\n| anli_r1\u002F准确率 | 0.33 | 0.32 |\n| anli_r2\u002F准确率 | 0.32 | 0.33 |\n| anli_r3\u002F准确率 | 0.35 | 0.35 |\n| arc_challenge\u002F准确率 | 0.34 | 0.34 |\n| arc_challenge\u002F归一化准确率 | 0.37 | 0.37 |\n| arc_easy\u002F准确率 | 0.69 | 0.68 |\n| arc_easy\u002F归一化准确率 | 0.65 | 0.63 |\n| boolq\u002F准确率 | 0.68 | 0.68 |\n| hellaswag\u002F准确率 | 0.49 | 0.48 |\n| hellaswag\u002F归一化准确率 | 0.67 | 0.65 |\n| openbookqa\u002F准确率 | 0.27 | 0.28 |\n| openbookqa\u002F归一化准确率 | 0.40 | 0.38 |\n| piqa\u002F准确率 | 0.75 | 0.73 |\n| piqa\u002F归一化准确率 | 0.76 | 0.75 |\n| record\u002FEM | 0.88 | 0.87 |\n| record\u002FF1 | 0.89 | 0.87 |\n| rte\u002F准确率 | 0.58 | 0.60 |\n| truthfulqa_mc\u002Fmc1 | 0.22 | 0.24 |\n| truthfulqa_mc\u002Fmc2 | 0.35 | 0.38 |\n| wic\u002F准确率 | 0.48 | 0.50 |\n| winogrande\u002F准确率 | 0.62 | 0.60 |\n| 平均得分 | 0.53 | 0.53 |\n\n\u003C\u002Fdiv>\n\n从v1.1版本的模型开始，我们决定使用[EleutherAI](https:\u002F\u002Fgithub.com\u002FEleutherAI)对[lm-evaluation-harness](https:\u002F\u002Fgithub.com\u002FEleutherAI\u002Flm-evaluation-harness)的实现，并做了一点小修改：在输入序列的开头添加了`\u003Cbos>`标记。结果如下表所示。\n\n\u003Cdiv align=\"center\">\n\n| 描述            | LongLLaMA-3B | OpenLLaMA-3Bv2 | LongLLaMA-3Bv1.1 | LongLLaMA-Instruct-3Bv1.1 |\n|:-----------------------|:--------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------|:--------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------|\n| anli_r1\u002Facc            | 0.32                                                                                  | 0.33                                                                               | 0.31                                                                      | 0.33                                                                                         |\n| anli_r2\u002Facc            | 0.33                                                                                  | 0.35                                                                               | 0.33                                                                      | 0.35                                                                                         |\n| anli_r3\u002Facc            | 0.35                                                                                  | 0.38                                                                               | 0.35                                                                      | 0.38                                                                                         |\n| arc_challenge\u002Facc      | 0.34                                                                                  | 0.33                                                                               | 0.32                                                                      | 0.36                                                                                         |\n| arc_challenge\u002Facc_norm | 0.37                                                                                  | 0.36                                                                               | 0.36                                                                      | 0.37                                                                                         |\n| arc_easy\u002Facc           | 0.67                                                                                  | 0.68                                                                               | 0.68                                                                      | 0.7                                                                                          |\n| arc_easy\u002Facc_norm      | 0.63                                                                                  | 0.63                                                                               | 0.63                                                                      | 0.63                                                                                         |\n| boolq\u002Facc              | 0.68                                                                                  | 0.67                                                                               | 0.66                                                                      | 0.77                                                                                         |\n| hellaswag\u002Facc          | 0.48                                                                                  | 0.53                                                                               | 0.52                                                                      | 0.52                                                                                         |\n| hellaswag\u002Facc_norm     | 0.65                                                                                  | 0.7                                                                                | 0.69                                                                      | 0.68                                                                                         |\n| openbookqa\u002Facc         | 0.28                                                                                  | 0.28                                                                               | 0.28                                                                      | 0.28                                                                                         |\n| openbookqa\u002Facc_norm    | 0.38                                                                                  | 0.39                                                                               | 0.37                                                                      | 0.41                                                                                         |\n| piqa\u002Facc               | 0.73                                                                                  | 0.77                                                                               | 0.77                                                                      | 0.78                                                                                         |\n| piqa\u002Facc_norm          | 0.75                                                                                  | 0.78                                                                               | 0.77                                                                      | 0.77                                                                                         |\n| record\u002Fem              | 0.87                                                                                  | 0.87                                                                               | 0.86                                                                      | 0.85                                                                                         |\n| record\u002Ff1              | 0.88                                                                                  | 0.88                                                                               | 0.87                                                                      | 0.86                                                                                         |\n| rte\u002Facc                | 0.6                                                                                   | 0.53                                                                               | 0.62                                                                      | 0.7                                                                                          |\n| truthfulqa_mc\u002Fmc1      | 0.24                                                                                  | 0.22                                                                               | 0.21                                                                      | 0.25                                                                                         |\n| truthfulqa_mc\u002Fmc2      | 0.38                                                                                  | 0.35                                                                               | 0.35                                                                      | 0.4                                                                                          |\n| wic\u002Facc                | 0.5                                                                                   | 0.5                                                                                | 0.5                                                                       | 0.54                                                                                         |\n| winogrande\u002Facc         | 0.6                                                                                   | 0.66                                                                               | 0.63                                                                      | 0.65                                                                                         |\n| 平均得分                   | 0.53                                                                                  | 0.53                                                                               | 0.53                                                                      | 0.55                                                                                         |\n\n\u003C\u002Fdiv>\n\n\n我们还提供了人工评估的结果。我们在以下任一标记后截断生成的文本：\n*  `\"\\ndef \"`\n*  `\"\\nclass \"`\n*  `\"\\nif __name__\"`\n\n\u003Cdiv align=\"center\">\n\n|  | OpenLLaMA-3Bv2 | LongLLaMA-3Bv1.1 | LongLLaMA-Instruct-3Bv1.1 |\n| - | - | - | - |\n| pass@1| 0.09| 0.12 |  0.12 |\n\n\u003C\u002Fdiv>\n\n\n\n## 作者\n- [Szymon Tworkowski](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=1V8AeXYAAAAJ&hl=en)\n- [Konrad Staniszewski](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=CM6PCBYAAAAJ)\n- [Mikołaj Pacek](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=eh6iEbQAAAAJ&hl=en&oi=ao)\n- [Henryk Michalewski](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=YdHW1ycAAAAJ&hl=en)\n- [Yuhuai Wu](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=bOQGfFIAAAAJ&hl=en)\n- [Piotr Miłoś](https:\u002F\u002Fscholar.google.pl\u002Fcitations?user=Se68XecAAAAJ&hl=pl&oi=ao)\n\n\n## 引用\n若要引用本工作，请使用以下 BibTeX 格式：\n```bibtex\n@misc{tworkowski2023focused,\n      title={Focused Transformer: Contrastive Training for Context Scaling}, \n      author={Szymon Tworkowski and Konrad Staniszewski and Mikołaj Pacek and Yuhuai Wu and Henryk Michalewski and Piotr Miłoś},\n      year={2023},\n      eprint={2307.03170},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n```\n\n\n## 许可证\n源代码和基础 LongLLaMA 3B 模型检查点采用 [Apache License, Version 2.0](http:\u002F\u002Fwww.apache.org\u002Flicenses\u002FLICENSE-2.0) 许可证授权。  \n经过指令\u002F聊天微调的模型仅用于研究目的。  \n关于 LongLLaMA-Code 7B，请参阅 [codellama\u002FCodeLlama-7b-hf](https:\u002F\u002Fhuggingface.co\u002Fcodellama\u002FCodeLlama-7b-hf\u002Fblob\u002Fmain\u002FLICENSE) 的许可证。  \nLongLLaMA-Code 7B Instruct 是在 [TIGER-Lab\u002FMathInstruct](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002FTIGER-Lab\u002FMathInstruct)、[OpenOrca](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002FOpen-Orca\u002FOpenOrca) 和 [ShareGPT-Processed](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fzetavg\u002FShareGPT-Processed) 数据集上对 LongLLaMA-Code 7B 进行微调得到的。  \n部分示例使用了外部代码（请参阅文件头部的版权声明和许可证信息）。\n\n## 致谢\n我们衷心感谢 TPU Research Cloud 计划，该计划通过提供重要的计算资源，对我们的研究起到了关键作用。同时，我们也感谢 Xinyang Geng 和 Hao Liu 发布了 [OpenLLaMA](https:\u002F\u002Fgithub.com\u002Fopenlm-research\u002Fopen_llama) 检查点以及 [EasyLM](https:\u002F\u002Fgithub.com\u002Fyoung-geng\u002FEasyLM) 库。\n\n特别感谢 [Keiran Paster](https:\u002F\u002Ftwitter.com\u002Fkeirp1)，他为 LongLLaMA-Code 的预训练数据提供了极其宝贵的建议。\n\n此外，我们还要感谢 [Xiaosong,He](https:\u002F\u002Fgithub.com\u002Fhxs91)，他为我们改进跨批次代码的解释提出了许多有益的建议。","# LongLLaMA 快速上手指南\n\nLongLLaMA 是一个基于 OpenLLaMA 和 Code Llama 构建的大语言模型，通过 **Focused Transformer (FoT)** 技术进行微调，能够处理长达 **256k tokens** 甚至更长的上下文。它支持作为现有 LLaMA 实现的直接替代品（在短上下文下），并提供了专门的推理代码以支持长文本输入。\n\n## 环境准备\n\n### 系统要求\n- **Python**: 建议 Python 3.8+\n- **GPU**: 推荐使用支持 CUDA 的 NVIDIA GPU（显存需求视模型大小而定，3B 版本约需 6-8GB，7B 版本需更高显存或使用量化\u002FOffload 技术）\n- **操作系统**: Linux \u002F macOS \u002F Windows (WSL)\n\n### 前置依赖\n请确保已安装 `pip` 并更新至最新版本。本项目主要依赖 `transformers`, `sentencepiece` 和 `accelerate`。\n\n> **国内加速提示**：如果下载 Hugging Face 模型或依赖包速度较慢，建议配置国内镜像源。\n> - 设置 pip 镜像：`pip config set global.index-url https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple`\n> - 设置 HF 镜像：在代码中设置环境变量 `export HF_ENDPOINT=https:\u002F\u002Fhf-mirror.com`\n\n## 安装步骤\n\n使用 pip 安装必要的 Python 库。注意 `transformers` 版本需为 `4.33.2` 以确保兼容性。\n\n```bash\npip install --upgrade pip\npip install transformers==4.33.2 sentencepiece accelerate\n```\n\n## 基本使用\n\n以下示例展示如何加载 **LongLLaMA-3Bv1.1** 模型并进行文本生成。该模型会自动将长输入分割为上下文窗口并加载到内存缓存中以支持长文本处理。\n\n### 1. 加载模型与分词器\n\n```python\nimport torch\nfrom transformers import LlamaTokenizer, AutoModelForCausalLM\n\n# 加载分词器和模型\n# trust_remote_code=True 是必须的，因为使用了自定义的 FoT 实现\ntokenizer = LlamaTokenizer.from_pretrained(\"syzymon\u002Flong_llama_3b_v1_1\")\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"syzymon\u002Flong_llama_3b_v1_1\", \n    torch_dtype=torch.float32, \n    trust_remote_code=True\n)\n\n# 如果有 GPU，将模型移至 GPU\nif torch.cuda.is_available():\n    model = model.to(\"cuda\")\n```\n\n### 2. 文本生成示例\n\nLongLLaMA 支持通过 `last_context_length` 参数优化生成长度。该参数指定最后一个上下文窗口保留的 token 数量，适当调整可提升生成质量。\n\n```python\nprompt = \"My name is Julien and I like to\"\ninput_ids = tokenizer(prompt, return_tensors=\"pt\").input_ids\n\nif torch.cuda.is_available():\n    input_ids = input_ids.to(\"cuda\")\n\n# 执行生成\ngeneration_output = model.generate(\n    input_ids=input_ids,\n    max_new_tokens=256,\n    num_beams=1,\n    last_context_length=1792,  # 调整此参数以优化长上下文表现\n    do_sample=True,\n    temperature=1.0,\n)\n\n# 解码并输出结果\nprint(tokenizer.decode(generation_output[0]))\n```\n\n### 3. 高级配置（可选）\n\n如需优化显存占用或指定特定的记忆层，可在加载模型时传入额外参数：\n\n```python\nmodel = AutoModelForCausalLM.from_pretrained(\n    \"syzymon\u002Flong_llama_3b_v1_1\", \n    torch_dtype=torch.float32, \n    trust_remote_code=True,\n    mem_layers=[],             # 指定带有记忆功能的层，空列表表示使用默认配置\n    mem_dtype='bfloat16',      # 更改记忆缓存的数据类型以节省显存\n    mem_attention_grouping=(4, 2048), # 权衡速度与显存：(头数, 每头查询数)\n)\n```\n\n> **注意**：如果仅用于短上下文（\u003C 2048 tokens），可以直接使用标准的 `LlamaForCausalLM` 加载，此时无需 `trust_remote_code=True`，但将无法利用长上下文扩展能力。","某法律科技团队正在开发一款智能合同审查系统，需要让 AI 一次性读取并分析长达数百页的并购协议全文，以识别潜在的风险条款。\n\n### 没有 long_llama 时\n- **上下文截断导致遗漏**：传统模型受限于 4k 或 8k 的窗口长度，被迫将合同切分成碎片处理，导致跨章节的风险关联（如前文的定义与后文的违约责任）无法被识别。\n- **人工拼接效率低下**：开发人员必须编写复杂的逻辑来手动管理文本切片和摘要拼接，不仅增加了代码维护成本，还引入了信息丢失的隐患。\n- **关键细节模糊**：在处理超长文档时，模型往往出现“中间迷失”现象，对文档中段的关键免责条款或细微的金额限制反应迟钝，准确率大幅下降。\n- **推理延迟高企**：为了弥补上下文不足，系统需要多次调用模型进行滚动总结，导致单次审查任务的响应时间从秒级延长至分钟级。\n\n### 使用 long_llama 后\n- **全量上下文无损输入**：凭借 256k+ 的超长上下文能力，long_llama 可直接吞下整份百页合同，精准捕捉跨越数十页的逻辑依赖和风险链条。\n- **架构简化开发提速**：团队移除了繁琐的切片与重组代码，直接将长文本传入模型，系统架构回归简洁，新功能的迭代周期缩短了一半。\n- **长程记忆精准定位**：基于 Focused Transformer 技术，long_llama 在海量文本中仍能像“聚光灯”一样精准聚焦于文档任何位置的关键条款，消除了“中间迷失”问题。\n- **单次推理即时响应**：无需多轮滚动查询，long_llama 一次前向传播即可完成全篇分析，将复杂合同的审查耗时压缩回秒级，大幅提升用户体验。\n\nlong_llama 通过突破上下文长度瓶颈，让 AI 真正具备了像人类专家一样通读并理解海量文档的核心能力。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FCStanKonrad_long_llama_07d73adc.png","CStanKonrad","Konrad Staniszewski","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FCStanKonrad_ea7c55bc.png",null,"https:\u002F\u002Fgithub.com\u002FCStanKonrad",[82,86,90],{"name":83,"color":84,"percentage":85},"Python","#3572A5",65.2,{"name":87,"color":88,"percentage":89},"Jupyter Notebook","#DA5B0B",34.1,{"name":91,"color":92,"percentage":93},"Shell","#89e051",0.7,1464,85,"2026-03-17T19:27:18","Apache-2.0","未说明","未明确说明具体型号，但基于 PyTorch\u002FCUDA 运行且处理长上下文（最高 256k tokens）及 3B\u002F7B 参数量，强烈建议使用支持 CUDA 的 NVIDIA GPU。显存需求取决于上下文长度和模型大小（7B 模型通常需要 14GB+，长上下文会显著增加 KV Cache 显存占用）。","未说明（建议 16GB+ 以应对长上下文数据处理）",{"notes":102,"python":98,"dependencies":103},"1. 该工具包含两个主要部分：推理代码基于 PyTorch 和 Hugging Face；继续预训练代码（FoT continued pretraining）则依赖 JAX 和 Flax。2. 加载模型时必须设置 trust_remote_code=True。3. 模型支持作为 LLaMA 的直接替代品使用，但若不使用专用推理代码，上下文长度将限制在 2048 tokens。4. 针对长上下文生成，可通过调整 last_context_length、mem_dtype（如 bfloat16）和 mem_attention_grouping 参数来优化显存使用和速度。",[104,105,106,107],"transformers==4.33.2","sentencepiece","accelerate","torch",[26,13],"2026-03-27T02:49:30.150509","2026-04-06T07:13:34.639925",[112,117,122,127,132,137],{"id":113,"question_zh":114,"answer_zh":115,"source_url":116},12454,"如何在 A100 等显存有限的显卡上训练长上下文（如 8k-10k 长度）的 Long Llama 模型？","官方推荐使用 JAX 代码库进行长上下文训练，因为 PyTorch 版本主要针对推理优化。JAX 版本包含两个关键优化：1. 对记忆层进行梯度检查点（gradient checkpointing）；2. 使用受 Flash Attention 启发的注意力实现，通过设置 `scan_cross_batch` 标志位启用，其核心思想是不实例化完整的 ∇Query x Key 矩阵，从而显著降低显存占用。","https:\u002F\u002Fgithub.com\u002FCStanKonrad\u002Flong_llama\u002Fissues\u002F23",{"id":118,"question_zh":119,"answer_zh":120,"source_url":121},12455,"CrossBatchAttention 中是否使用了论文提到的可学习温度参数（learnable temperature）？","在基于 LLaMA 的模型代码中并未应用可学习温度参数。该参数仅在早期基于非 LLaMA 模型（使用 meliad 代码库）的实验中使用，因为那些模型会对 Key 和 Query 进行归一化。而本仓库中的 LLaMA 模型不对 Key 和 Query 进行归一化，因此不需要该参数。","https:\u002F\u002Fgithub.com\u002FCStanKonrad\u002Flong_llama\u002Fissues\u002F21",{"id":123,"question_zh":124,"answer_zh":125,"source_url":126},12456,"如何将 CrossBatch 方法集成到使用分组查询注意力（GQA）的大型 LLaMA2 模型中？","虽然官方尚未测试，但根据核心原理可以自行实现：对于每一组查询（query group），让它们关注该组内的键（keys），以及该组在其他批次元素中所关注的键。即保持 GQA 的分组逻辑，同时在跨批次注意力机制中应用相同的组映射关系。","https:\u002F\u002Fgithub.com\u002FCStanKonrad\u002Flong_llama\u002Fissues\u002F18",{"id":128,"question_zh":129,"answer_zh":130,"source_url":131},12457,"官方的大规模持续预训练（FoT）代码何时发布？指令微调代码是否使用了 FoT？","官方的 FoT 大规模持续预训练代码计划以 JAX 版本发布。目前的指令微调代码并未使用完整的 FoT 机制（实际上它使用的是 `cross_batch=1` 的修改版本），这与用于调整基础模型的版本不同。","https:\u002F\u002Fgithub.com\u002FCStanKonrad\u002Flong_llama\u002Fissues\u002F11",{"id":133,"question_zh":134,"answer_zh":135,"source_url":136},12458,"关于论文附录 A.2 中提到的批次分段策略（1\u002F4(0,0) 等），具体是如何在批次内划分和处理的？","该策略是将一个批次（batch）中的样本在垂直方向上划分为四个大小相等的段。每个段对应不同的上下文暴露策略（例如某些段暴露于来自同一文档的额外上下文）。这并非指需要维护多个历史批次（如 i-1, i-2），而是在当前批次内部通过分段来实现不同样本看到不同数量正负样本上下文的效果。","https:\u002F\u002Fgithub.com\u002FCStanKonrad\u002Flong_llama\u002Fissues\u002F14",{"id":138,"question_zh":139,"answer_zh":140,"source_url":116},12459,"PyTorch 版本的代码是否适合进行长序列训练？","PyTorch 代码最初是为推理设计的，因此在长序列训练方面不如 JAX 版本优化得好。如果遇到显存不足（OOM）问题，建议切换到官方提供的 JAX 训练脚本，或者等待团队未来对 PyTorch 版本进行进一步优化。",[]]