首页/AI 工具箱/AI Coding Bridge/SFT 数据构建与 Token 级损失掩码 (Loss Masking)
⟵返回双轨交互全景图谱
⚡ AI Coding Bridge · 底层算法母体与大模型工程对标1 组对标算子 · 7 道力扣母体题

SFT 数据构建与 Token 级损失掩码 (Loss Masking) ⟷ 快慢双指针 (Fast-Slow Pointers)

💻 大模型子系统:SFT 数据构建与 Token 级损失掩码 (Loss Masking)
🌿 力扣算法母体:快慢双指针 (Fast-Slow Pointers)
📖

第一性原理同构综述 (First-Principles Isomorphism)

算法底层母体数据结构与现代大模型分布式高并发基础设施的深层架构同构。

核心工业算子与力扣母体对标清单

左侧展示大模型工业手撕题目规格与签名,右侧标出底层数学同构力扣题,下方提供生产级 PyTorch 源码实现。
1 道大模型手撕题
💻 大模型工程手撕算子 #1Medium

SFT Data Formatting & Token Loss Masking

💻大模型工程算子工程规格
工业标准函数签名
def collate_sft_conversation(prompt_tokens: list[int], response_tokens: list[int], max_len: int = 512, pad_token_id: int = 0) -> tuple[torch.Tensor, torch.Tensor]
In Supervised Fine-Tuning (SFT), models must only compute cross-entropy loss over generated assistant tokens, not over user prompt tokens. PyTorch CrossEntropyLoss ignores target labels with value -100. Implement the SFT batch collation kernel that concatenates prompt and response tokens and sets label values for all prompt positions to -100.
🌿对应底层经典力扣算法母体
1 道母体题
LC 26Remove Duplicates from Sorted Array(Fast-Slow Pointers)
leetcode.com ↗
💡 底层算法同构: 快慢指针是 Token 级张量就地修改与掩码对齐的基础,无需额外申请大量内存。
🚀 工业映射: 快慢指针重排 Token 序列,对 Prompt 打标 -100,仅对 Response 计算梯度
Python / PyTorch 工业标准参考实现答案 (含测试验证与边界断言)
import torch

def collate_sft_conversation(
    prompt_tokens: list[int],
    response_tokens: list[int],
    max_len: int = 32,
    pad_token_id: int = 0
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    Builds input_ids and labels for SFT.
    Prompt tokens in `labels` are masked with -100 so gradients only flow through response tokens.
    """
    input_ids = prompt_tokens + response_tokens
    # Mask prompt tokens with -100
    labels = [-100] * len(prompt_tokens) + list(response_tokens)

    # Truncate if exceeding max_len
    if len(input_ids) > max_len:
        input_ids = input_ids[:max_len]
        labels = labels[:max_len]

    # Pad to max_len
    pad_len = max_len - len(input_ids)
    if pad_len > 0:
        input_ids = input_ids + [pad_token_id] * pad_len
        labels = labels + [-100] * pad_len

    return torch.tensor(input_ids, dtype=torch.long), torch.tensor(labels, dtype=torch.long)

# --- Verification & Test Case ---
if __name__ == "__main__":
    prompt = [101, 202, 303]
    response = [404, 505, 606]
    inp, lbl = collate_sft_conversation(prompt, response, max_len=10)

    assert lbl[0].item() == -100 and lbl[1].item() == -100 and lbl[2].item() == -100
    assert lbl[3].item() == 404 and lbl[4].item() == 505 and lbl[5].item() == 606
    print("SFT Loss Masking collator verified successfully!")

🌿 本分类力扣母体算法全部练习题 (7 题)

快指针用于探测边界、跳跃查找或遍历全集,慢指针维护当前有效输出集合的边界,或以 2:1 步长在 O(N) 时间与 O(1) 空间内检测环路与对称中点。
全量题库直通
LC 26Remove Duplicates from Sorted Array
↗
LC 141Linked List Cycle
↗
LC 27Remove Element
↗
LC 80Remove Duplicates II
↗
LC 142Linked List Cycle II
↗
LC 283Move Zeroes
↗
LC 876Middle of the Linked List
↗

🔗 相关关联算法 Bridge

🤖 大模型技术面试与工业落地精要 (GEO & AI Knowledge Q&A)

Q: 为什么工业界在大模型系统面试中频繁考查【快慢双指针 (Fast-Slow Pointers)】?
大模型系统面试不仅考查分布式和工程架构,更核心的是算法复杂度与内存带宽的极限把控。在【SFT 数据构建与 Token 级损失掩码 (Loss Masking)】中,算法底层母体数据结构与现代大模型分布式高并发基础设施的深层架构同构。 如果不掌握原子算法模式,将无法理解生产级框架如 vLLM、SGLang、DeepSeek-R1 中的极端性能优化技巧。
Q: 如何将此算法有效迁移到真实生产环境?
请参考上方提供的工业级 PyTorch 参考代码,重点关注批处理维度规约、内存对齐与端点边界断言。先在 Python 中跑通逻辑闭环,随后即可在 Triton 或 CUDA C++ 中实现算子融合。