Spaces:
Running on Zero
Running on Zero
Download data/problems/attention-logit-softcapping.json from dongyanggg/codestar-backend: direct link, hf CLI and curl.
- Browser
- Download file 7.67 kB
-
https://huggingface.co/spaces/dongyanggg/codestar-backend/resolve/main/data/problems/attention-logit-softcapping.json
- Command line
-
hf download hf://spaces/dongyanggg/codestar-backend/data/problems/attention-logit-softcapping.json
-
curl -L -o attention-logit-softcapping.json https://huggingface.co/spaces/dongyanggg/codestar-backend/resolve/main/data/problems/attention-logit-softcapping.json
7.67 kB
| { | |
| "slug": "attention-logit-softcapping", | |
| "title": "手撕 Gemma-2 注意力 Logits 软截断 (Attention Logit Soft-Capping)", | |
| "difficulty": "Easy", | |
| "category": "Attention", | |
| "tags": [ | |
| "Gemma-2", | |
| "SoftCapping", | |
| "数值稳定" | |
| ], | |
| "description_md": "### 题目描述\n实现注意力分值软截断:$\\text{logits}' = \\text{soft\\_cap} \\times \\tanh\\left( \\frac{\\text{logits}}{\\text{soft\\_cap}} \\right)$,避免注意力分数极端发散。\n\n### 函数签名\n```python\ndef logit_softcapping(\n logits: torch.Tensor,\n soft_cap: float = 50.0,\n) -> torch.Tensor:\n```\n\n### 示例\n```python\n# 输入\nlogits = [10.0, 50.0, 100.0, -100.0]\nsoft_cap = 30.0\n\n# 输出 (Tensor, shape=[4], dtype=float32)\n[9.6454, 27.9333, 29.9237, -29.9237]\n```\n\n### 参数规格与约束\n- **`logits`**:`torch.Tensor`,测试规格 `shape=[4], dtype=float32`\n- **`soft_cap`**:`float`(默认 `50.0`)\n- **返回值**:`torch.Tensor`,输出规格 `shape=[4], dtype=float32`\n- **精度容差**:`atol=0.0001, rtol=0.0001`", | |
| "entry_point": "logit_softcapping", | |
| "starter_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom typing import Optional, List, Tuple\n\ndef logit_softcapping(\n logits: torch.Tensor,\n soft_cap: float = 50.0,\n) -> torch.Tensor:\n \"\"\"\n 手撕 Gemma-2 注意力 Logits 软截断 (Attention Logit Soft-Capping)\n \"\"\"\n # 请在此编写代码\n pass\n", | |
| "reference_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom typing import Optional, List, Tuple\n\ndef logit_softcapping(logits: torch.Tensor, soft_cap: float = 50.0) -> torch.Tensor:\n return soft_cap * torch.tanh(logits / soft_cap)\n", | |
| "forbidden_modules": [ | |
| "os", | |
| "sys", | |
| "subprocess", | |
| "shutil", | |
| "socket", | |
| "requests" | |
| ], | |
| "forbidden_calls": [], | |
| "time_limit": 3.0, | |
| "memory_limit_mb": 512, | |
| "atol": 0.0001, | |
| "rtol": 0.0001, | |
| "test_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\n\ncases = [\n ('软截断分值测试', torch.tensor([10.0, 50.0, 100.0, -100.0], dtype=torch.float32), 30.0),\n ('多批次扩展泛化验证', torch.tensor([10.0, 50.0, 100.0, -100.0, 15.0, 75.0, 150.0, -150.0], dtype=torch.float32), 30.0),\n ('多维批次与参数泛化验证', torch.tensor([15.0, 75.0, 150.0, -150.0], dtype=torch.float32), 45.0),\n ('边界极值与稳定性验证', torch.tensor([5.0, 25.0, 50.0, -50.0], dtype=torch.float32), 15.0),\n]\nfor idx, (name, *args) in enumerate(cases, 1):\n t0 = time.time()\n try:\n exp = ref_obj(*args)\n act = user_obj(*args)\n match, err, max_diff = compare_outputs(act, exp, atol=atol, rtol=rtol)\n passed, msg = match, err\n except Exception as e:\n passed, msg = False, f\"Runtime Exception: {str(e)}\"\n act, exp, max_diff = None, None, None\n cases_results.append({\n \"case_id\": idx, \"case_name\": name, \"passed\": passed,\n \"time_ms\": round((time.time() - t0) * 1000, 2), \"message\": msg,\n \"user_output_summary\": summarize_obj(act) if act is not None else None,\n \"expected_summary\": summarize_obj(exp) if exp is not None else None,\n \"max_diff\": max_diff,\n })\n", | |
| "is_featured": false, | |
| "editorial_md": "#### 💡 核心算法原理与数学推导\n**手撕 Gemma-2 注意力 Logits 软截断 (Attention Logit Soft-Capping)**(`logit_softcapping`)聚焦于 **Attention** 中的关键计算逻辑:\n\n实现注意力分值软截断:$\\text{logits}' = \\text{soft\\_cap} \\times \\tanh\\left( \\frac{\\text{logits}}{\\text{soft\\_cap}} \\right)$,避免注意力分数极端发散。\n\n在实现中,函数接收参数 `logits` (`torch.Tensor`)、`soft_cap` (`float`),目标是计算出类型与形状严格符合 `torch.Tensor` 契约的结果。\n\n#### 📐 输入输出张量变换与步骤拆解\n- **输入基准规格**:`logits` 规格为 `torch.Tensor(shape=[4], dtype=float32)`,`soft_cap` 规格为 `float` (示例值: `30.0`)。\n- **期望输出规格**:`torch.Tensor(shape=[4], dtype=float32)`。\n\n**具体推导与计算步骤如下:**\n1. 返回最终结果:输出 `soft_cap * torch.tanh(logits / soft_cap)`,严格对齐函数签名要求的返回类型与维度。\n\n#### 📊 复杂度分析\n- **时间复杂度**:$O(N)$(线性于输入张量总元素个数 $\\prod d_i$),所有运算均为向量化逐元素算子或沿指定维度的归约计算。\n- **空间复杂度**:$O(N)$,需要与输入或输出张量同规模的显存空间保存计算结果。\n\n#### ⚠️ 关键实现细节与易错点\n- **除零保护与数值平滑 (`eps`)**:在执行分母归一化、标准差缩放或对数运算时,必须按公式位置准确加上 `eps`(例如在平方根内 `sqrt(var + eps)` 还是分母外 `+ eps`),防止全零或常量输入触发 `NaN` / `Inf`。\n- **指数与对数域数值稳定性**:直接对大幅值 logits 计算 `exp` 易导致浮点数上溢(Overflow),对接近 0 的概率直接计算 `log` 易导致下溢;应优先使用 `F.log_softmax`、`F.logsigmoid` 或减去最大值的稳定化写法。\n- **纯向量化算子优先**:尽量使用 PyTorch 原生向量化张量算子替代低效的 Python 逐元素循环,以兼顾代码简洁性与执行性能。\n\n#### 💻 官方标准参考实现\n```python\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom typing import Optional, List, Tuple\n\ndef logit_softcapping(logits: torch.Tensor, soft_cap: float = 50.0) -> torch.Tensor:\n return soft_cap * torch.tanh(logits / soft_cap)\n```", | |
| "difficulty_breakdown": { | |
| "concept": 1, | |
| "implementation": 1, | |
| "math_derivation": 2, | |
| "boundary_complexity": 1 | |
| }, | |
| "test_cases": [ | |
| { | |
| "name": "软截断分值测试", | |
| "input_desc": "真实参数契约用例 (logits, soft_cap)", | |
| "params": [ | |
| { | |
| "name": "logits", | |
| "type": "torch.Tensor", | |
| "value": "torch.tensor([10.0, 50.0, 100.0, -100.0], dtype=torch.float32)" | |
| }, | |
| { | |
| "name": "soft_cap", | |
| "type": "float", | |
| "value": "30.0" | |
| } | |
| ], | |
| "raw_inputs": { | |
| "logits": "torch.tensor([10.0, 50.0, 100.0, -100.0], dtype=torch.float32)", | |
| "soft_cap": "30.0" | |
| } | |
| }, | |
| { | |
| "name": "多批次扩展泛化验证", | |
| "input_desc": "真实参数契约用例 (logits, soft_cap)", | |
| "params": [ | |
| { | |
| "name": "logits", | |
| "type": "torch.Tensor", | |
| "value": "torch.tensor([10.0, 50.0, 100.0, -100.0, 15.0, 75.0, 150.0, -150.0], dtype=torch.float32)" | |
| }, | |
| { | |
| "name": "soft_cap", | |
| "type": "float", | |
| "value": "30.0" | |
| } | |
| ], | |
| "raw_inputs": { | |
| "logits": "torch.tensor([10.0, 50.0, 100.0, -100.0, 15.0, 75.0, 150.0, -150.0], dtype=torch.float32)", | |
| "soft_cap": "30.0" | |
| } | |
| }, | |
| { | |
| "name": "多维批次与参数泛化验证", | |
| "input_desc": "真实参数契约用例 (logits, soft_cap)", | |
| "params": [ | |
| { | |
| "name": "logits", | |
| "type": "torch.Tensor", | |
| "value": "torch.tensor([15.0, 75.0, 150.0, -150.0], dtype=torch.float32)" | |
| }, | |
| { | |
| "name": "soft_cap", | |
| "type": "float", | |
| "value": "45.0" | |
| } | |
| ], | |
| "raw_inputs": { | |
| "logits": "torch.tensor([15.0, 75.0, 150.0, -150.0], dtype=torch.float32)", | |
| "soft_cap": "45.0" | |
| } | |
| } | |
| ] | |
| } |