File size: 9,975 Bytes
5f7afef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
{
  "slug": "arcface-additive-angular-margin",
  "title": "手撕 ArcFace 加性角度间隔损失 (ArcFace Angular Margin)",
  "difficulty": "Hard",
  "category": "Loss",
  "tags": [
    "ArcFace",
    "加性间隔",
    "人脸识别"
  ],
  "description_md": "### 题目描述\n在归一化权重和特征下,输入余弦值 $\\cos \\theta \\in [-1, 1]^{B \\times C}$ 及真实类别索引 $labels \\in [0, C-1]^B$。对目标类别施加角度间隔 $\\cos(\\theta + m) = \\cos\\theta \\cos m - \\sin\\theta \\sin m$(其中 $\\sin\\theta = \\sqrt{1 - \\cos^2\\theta}$),输出调整后的余弦值矩阵。\n\n### 函数签名\n```python\ndef arcface_margin(\n    cosine: torch.Tensor,\n    labels: torch.Tensor,\n    m: float = 0.5,\n) -> torch.Tensor:\n```\n\n### 示例\n```python\n# 输入\ncosine = [[0.8, 0.2], [0.3, 0.9]]\nlabels = [0, 1]\nm = 0.5\n\n# 输出 (Tensor, shape=[2, 2], dtype=float32)\n[[0.4144, 0.2], [0.3, 0.5808]]\n```\n\n### 参数规格与约束\n- **`cosine`**:`torch.Tensor`,测试规格 `shape=[2, 2], dtype=float32`\n- **`labels`**:`torch.Tensor`,测试规格 `shape=[2], dtype=int64`\n- **`m`**:`float`(默认 `0.5`)\n- **返回值**:`torch.Tensor`,输出规格 `shape=[2, 2], dtype=float32`\n- **精度容差**:`atol=0.0001, rtol=0.0001`",
  "entry_point": "arcface_margin",
  "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 arcface_margin(\n    cosine: torch.Tensor,\n    labels: torch.Tensor,\n    m: float = 0.5,\n) -> torch.Tensor:\n    \"\"\"\n    手撕 ArcFace 加性角度间隔损失 (ArcFace Angular Margin)\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 arcface_margin(cosine: torch.Tensor, labels: torch.Tensor, m: float = 0.5) -> torch.Tensor:\n    B = cosine.shape[0]\n    cos_m = math.cos(m)\n    sin_m = math.sin(m)\n    sine = torch.sqrt(torch.clamp(1.0 - cosine ** 2, min=0.0))\n    phi = cosine * cos_m - sine * sin_m\n    out = cosine.clone()\n    batch_idx = torch.arange(B, device=cosine.device)\n    out[batch_idx, labels] = phi[batch_idx, labels]\n    return out\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([[0.8, 0.2], [0.3, 0.9]], dtype=torch.float32), torch.tensor([0, 1]), 0.5),\n    ('多批次扩展泛化验证', torch.tensor([[0.8, 0.2], [0.3, 0.9], [1.2, 0.3], [0.45, 1.35]], dtype=torch.float32), torch.tensor([0, 1, 0, 1]), 0.5),\n    ('多维批次与参数泛化验证', torch.tensor([[1.2, 0.3], [0.45, 1.35]], dtype=torch.float32), torch.tensor([0, 1]), 0.75),\n    ('边界极值与稳定性验证', torch.tensor([[0.4, 0.1], [0.15, 0.45]], dtype=torch.float32), torch.tensor([0, 1]), 0.25),\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**手撕 ArcFace 加性角度间隔损失 (ArcFace Angular Margin)**(`arcface_margin`)聚焦于 **Loss** 中的关键计算逻辑:\n\n在归一化权重和特征下,输入余弦值 $\\cos \\theta \\in [-1, 1]^{B \\times C}$ 及真实类别索引 $labels \\in [0, C-1]^B$。对目标类别施加角度间隔 $\\cos(\\theta + m) = \\cos\\theta \\cos m - \\sin\\theta \\sin m$(其中 $\\sin\\theta = \\sqrt{1 - \\cos^2\\theta}$),输出调整后的余弦值矩阵。\n\n在实现中,函数接收参数 `cosine` (`torch.Tensor`)、`labels` (`torch.Tensor`)、`m` (`float`),目标是计算出类型与形状严格符合 `torch.Tensor` 契约的结果。\n\n#### 📐 输入输出张量变换与步骤拆解\n- **输入基准规格**:`cosine` 规格为 `torch.Tensor(shape=[2, 2], dtype=float32)`,`labels` 规格为 `torch.Tensor(shape=[2], dtype=int64)`,`m` 规格为 `float` (示例值: `0.5`)。\n- **期望输出规格**:`torch.Tensor(shape=[2, 2], dtype=float32)`。\n\n**具体推导与计算步骤如下:**\n1. 计算中间量 `B`:通过表达式 `cosine.shape[0]` 完成张量或数值变换。\n2. 计算中间量 `cos_m`:通过表达式 `math.cos(m)` 完成张量或数值变换。\n3. 计算中间量 `sin_m`:通过表达式 `math.sin(m)` 完成张量或数值变换。\n4. 计算中间量 `sine`:通过表达式 `torch.sqrt(torch.clamp(1.0 - cosine ** 2, min=0.0))` 完成张量或数值变换。\n5. 计算中间量 `phi`:通过表达式 `cosine * cos_m - sine * sin_m` 完成张量或数值变换。\n6. 计算中间量 `out`:通过表达式 `cosine.clone()` 完成张量或数值变换。\n7. 计算中间量 `batch_idx`:通过表达式 `torch.arange(B, device=cosine.device)` 完成张量或数值变换。\n8. 计算中间量 `out[batch_idx, labels]`:通过表达式 `phi[batch_idx, labels]` 完成张量或数值变换。\n9. 返回最终结果:输出 `out`,严格对齐函数签名要求的返回类型与维度。\n\n#### 📊 复杂度分析\n- **时间复杂度**:$O(N)$(线性于输入张量总元素个数 $\\prod d_i$),所有运算均为向量化逐元素算子或沿指定维度的归约计算。\n- **空间复杂度**:$O(N)$,需要与输入或输出张量同规模的显存空间保存计算结果。\n\n#### ⚠️ 关键实现细节与易错点\n- **避免非预期原地修改 (In-place Mutation)**:评测器会复用输入张量比对参考实现与用户实现的输出;若需修改输入张量的部分切片或掩码位置,请先执行 `.clone()` 再修改,避免污染原始输入。\n- **边界输入鲁棒性**:注意单样本(`Batch=1`)、单步序列(`Seq=1`)、零值输入或极端超参数下的计算行为,不要在代码中硬编码特定测试用例的维度常数。\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 arcface_margin(cosine: torch.Tensor, labels: torch.Tensor, m: float = 0.5) -> torch.Tensor:\n    B = cosine.shape[0]\n    cos_m = math.cos(m)\n    sin_m = math.sin(m)\n    sine = torch.sqrt(torch.clamp(1.0 - cosine ** 2, min=0.0))\n    phi = cosine * cos_m - sine * sin_m\n    out = cosine.clone()\n    batch_idx = torch.arange(B, device=cosine.device)\n    out[batch_idx, labels] = phi[batch_idx, labels]\n    return out\n```",
  "difficulty_breakdown": {
    "concept": 4,
    "implementation": 4,
    "math_derivation": 4,
    "boundary_complexity": 4
  },
  "test_cases": [
    {
      "name": "目标类余弦加间隔",
      "input_desc": "真实参数契约用例 (cosine, labels, m)",
      "params": [
        {
          "name": "cosine",
          "type": "torch.Tensor",
          "value": "torch.tensor([[0.8, 0.2], [0.3, 0.9]], dtype=torch.float32)"
        },
        {
          "name": "labels",
          "type": "torch.Tensor",
          "value": "torch.tensor([0, 1])"
        },
        {
          "name": "m",
          "type": "float",
          "value": "0.5"
        }
      ],
      "raw_inputs": {
        "cosine": "torch.tensor([[0.8, 0.2], [0.3, 0.9]], dtype=torch.float32)",
        "labels": "torch.tensor([0, 1])",
        "m": "0.5"
      }
    },
    {
      "name": "多批次扩展泛化验证",
      "input_desc": "真实参数契约用例 (cosine, labels, m)",
      "params": [
        {
          "name": "cosine",
          "type": "torch.Tensor",
          "value": "torch.tensor([[0.8, 0.2], [0.3, 0.9], [1.2, 0.3], [0.45, 1.35]], dtype=torch.float32)"
        },
        {
          "name": "labels",
          "type": "torch.Tensor",
          "value": "torch.tensor([0, 1, 0, 1])"
        },
        {
          "name": "m",
          "type": "float",
          "value": "0.5"
        }
      ],
      "raw_inputs": {
        "cosine": "torch.tensor([[0.8, 0.2], [0.3, 0.9], [1.2, 0.3], [0.45, 1.35]], dtype=torch.float32)",
        "labels": "torch.tensor([0, 1, 0, 1])",
        "m": "0.5"
      }
    },
    {
      "name": "多维批次与参数泛化验证",
      "input_desc": "真实参数契约用例 (cosine, labels, m)",
      "params": [
        {
          "name": "cosine",
          "type": "torch.Tensor",
          "value": "torch.tensor([[1.2, 0.3], [0.45, 1.35]], dtype=torch.float32)"
        },
        {
          "name": "labels",
          "type": "torch.Tensor",
          "value": "torch.tensor([0, 1])"
        },
        {
          "name": "m",
          "type": "float",
          "value": "0.75"
        }
      ],
      "raw_inputs": {
        "cosine": "torch.tensor([[1.2, 0.3], [0.45, 1.35]], dtype=torch.float32)",
        "labels": "torch.tensor([0, 1])",
        "m": "0.75"
      }
    }
  ]
}