Spaces:
Running on Zero
Running on Zero
File size: 7,554 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 | {
"slug": "cayley-orthogonal-transform",
"title": "斜对称矩阵 Cayley 变换构造正交矩阵",
"difficulty": "Medium",
"difficulty_breakdown": {
"concept": 3,
"implementation": 3,
"math_derivation": 3,
"boundary_complexity": 3
},
"category": "Math",
"tags": [
"LinearAlgebra",
"OrthogonalMatrix",
"CayleyTransform",
"TorchLeet"
],
"description_md": "### 题目描述\n实现正交权重参数化(Orthogonal RNN / ViT)中常用的 Cayley 变换:给定任意方阵参数 `w`(形状 `[N, N]`),先构造斜对称矩阵(Skew-Symmetric Matrix)$A = W - W^\\top$(满足 $A^\\top = -A$),再计算正交矩阵 $Q = (I - A)(I + A)^{-1}$(满足 $Q^\\top Q = I$ 且 $\\det Q = +1$)。\n\n### 函数签名\n```python\ndef cayley_orthogonal_matrix(w: torch.Tensor) -> torch.Tensor:\n```\n\n### 示例\n```python\n# 输入\nw = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]\n\n# 输出 (Tensor, shape=[3, 3], dtype=float32)\n[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]\n```\n\n### 参数规格与约束\n- **`w`**:`torch.Tensor`,测试规格 `shape=[3, 3], dtype=float32`\n- **返回值**:`torch.Tensor`,输出规格 `shape=[3, 3], dtype=float32`\n- **精度容差**:`atol=0.0001, rtol=0.0001`\n> 题目来源:改编自 [TorchLeet](https://github.com/Exorust/TorchLeet)(MIT License),已改写为函数式评测接口与中文题面。",
"entry_point": "cayley_orthogonal_matrix",
"starter_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom typing import List, Tuple, Dict, Optional\n\ndef cayley_orthogonal_matrix(w: torch.Tensor) -> torch.Tensor:\n # 请在此处编写你的实现代码\n pass\n",
"reference_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom typing import List, Tuple, Dict, Optional\n\ndef cayley_orthogonal_matrix(w: torch.Tensor) -> torch.Tensor:\n n = w.shape[0]\n eye = torch.eye(n, dtype=w.dtype)\n a = w - w.t()\n return torch.linalg.solve((eye + a).t(), (eye - a).t()).t()\n",
"test_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom typing import List, Tuple, Dict, Optional\n\ncases = [\n (\"零矩阵对应单位正交阵 I\", torch.zeros(3, 3)),\n (\"对称矩阵斜对称部分为 0 对应 I\", torch.ones(3, 3)),\n (\"2x2 旋转生成手算\", torch.tensor([[0.0, 0.5], [-0.5, 0.0]])),\n (\"随机 5x5 参数生成正交阵\", torch.randn(5, 5)),\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",
"test_cases": [
{
"name": "零矩阵对应单位正交阵 I",
"input_desc": "真实参数契约用例 (w)",
"params": [
{
"name": "w",
"type": "torch.Tensor",
"value": "torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=torch.float32)"
}
],
"raw_inputs": {
"w": "torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=torch.float32)"
}
},
{
"name": "对称矩阵斜对称部分为 0 对应 I",
"input_desc": "真实参数契约用例 (w)",
"params": [
{
"name": "w",
"type": "torch.Tensor",
"value": "torch.tensor([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], dtype=torch.float32)"
}
],
"raw_inputs": {
"w": "torch.tensor([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], dtype=torch.float32)"
}
},
{
"name": "2x2 旋转生成手算",
"input_desc": "真实参数契约用例 (w)",
"params": [
{
"name": "w",
"type": "torch.Tensor",
"value": "torch.tensor([[0.0, 0.5], [-0.5, 0.0]], dtype=torch.float32)"
}
],
"raw_inputs": {
"w": "torch.tensor([[0.0, 0.5], [-0.5, 0.0]], dtype=torch.float32)"
}
}
],
"time_limit": 5.0,
"memory_limit_mb": 512,
"atol": 0.0001,
"rtol": 0.0001,
"forbidden_modules": [
"os",
"sys",
"subprocess",
"socket",
"shutil",
"pathlib",
"ctypes",
"multiprocessing"
],
"forbidden_calls": [
"eval",
"exec",
"compile",
"open",
"__import__",
"input",
"breakpoint"
],
"is_featured": false,
"editorial_md": "#### 💡 核心算法原理与数学推导\n**斜对称矩阵 Cayley 变换构造正交矩阵**(`cayley_orthogonal_matrix`)聚焦于 **Math** 中的关键计算逻辑:\n\n实现正交权重参数化(Orthogonal RNN / ViT)中常用的 Cayley 变换:给定任意方阵参数 `w`(形状 `[N, N]`),先构造斜对称矩阵(Skew-Symmetric Matrix)$A = W - W^\\top$(满足 $A^\\top = -A$),再计算正交矩阵 $Q = (I - A)(I + A)^{-1}$(满足 $Q^\\top Q = I$ 且 $\\det Q = +1$)。\n\n在实现中,函数接收参数 `w` (`torch.Tensor`),目标是计算出类型与形状严格符合 `torch.Tensor` 契约的结果。\n\n#### 📐 输入输出张量变换与步骤拆解\n- **输入基准规格**:`w` 规格为 `torch.Tensor(shape=[3, 3], dtype=float32)`。\n- **期望输出规格**:`torch.Tensor(shape=[3, 3], dtype=float32)`。\n\n**具体推导与计算步骤如下:**\n1. 计算中间量 `n`:通过表达式 `w.shape[0]` 完成张量或数值变换。\n2. 计算中间量 `eye`:通过表达式 `torch.eye(n, dtype=w.dtype)` 完成张量或数值变换。\n3. 计算中间量 `a`:通过表达式 `w - w.t()` 完成张量或数值变换。\n4. 返回最终结果:输出 `torch.linalg.solve((eye + a).t(), (eye - a).t()).t()`,严格对齐函数签名要求的返回类型与维度。\n\n#### 📊 复杂度分析\n- **时间复杂度**:$O(N \\cdot D^2 + D^3)$,主要由矩阵乘积与线性代数求逆/奇异值分解开销主导。\n- **空间复杂度**:$O(N \\cdot D + D^2)$,用于存储核矩阵/协方差矩阵及分解结果张量。\n\n#### ⚠️ 关键实现细节与易错点\n- **输入输出类型与形状契约**:请严格按照函数签名返回对应类型(`torch.Tensor`、`Tuple` 或标量数值),避免改变张量维度。\n- **边界输入鲁棒性**:注意单样本(`Batch=1`)、零值输入或极端超参数下的计算行为,禁止硬编码特定测试用例常量。\n- **向量化算子优先**:优先使用 PyTorch 原生向量化张量算子,避免低效的逐元素循环。\n\n#### 💻 官方标准参考实现\n```python\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom typing import List, Tuple, Dict, Optional\n\ndef cayley_orthogonal_matrix(w: torch.Tensor) -> torch.Tensor:\n n = w.shape[0]\n eye = torch.eye(n, dtype=w.dtype)\n a = w - w.t()\n return torch.linalg.solve((eye + a).t(), (eye - a).t()).t()\n```"
} |