Compare commits
63
Commits
4ec5b63cfd
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c1108f011 | ||
|
|
49b1cd8b6d | ||
|
|
a01ca7eab7 | ||
|
|
e799e02e22 | ||
|
|
4fcb4f2372 | ||
|
|
d296acd34e | ||
|
|
1d179c2506 | ||
|
|
f7759f5331 | ||
|
|
f907d57b6a | ||
|
|
29491cae82 | ||
|
|
2103feddd7 | ||
|
|
6f6410554a | ||
|
|
1e862e577a | ||
|
|
7e73e9286a | ||
|
|
efe1ee6801 | ||
|
|
762b4d347d | ||
|
|
9d449f2108 | ||
|
|
2ddba5843c | ||
|
|
eb5f006f13 | ||
|
|
2f2a41ee3e | ||
|
|
851e8888b5 | ||
|
|
b46c76ce9a | ||
|
|
e798d8fc43 | ||
|
|
3a5bc1dbcd | ||
|
|
bf443062b4 | ||
|
|
36a8c073fc | ||
|
|
800bfdebfd | ||
|
|
271b3aeb79 | ||
|
|
188419a275 | ||
|
|
0c5ceb2d2c | ||
|
|
101e54858b | ||
|
|
5c77269e51 | ||
|
|
c3748c36c7 | ||
|
|
813be2906b | ||
|
|
c44a191f8b | ||
|
|
8bf7e9e770 | ||
|
|
0390afb932 | ||
|
|
76533b7ec3 | ||
|
|
dd906acf4b | ||
|
|
830bbac4f3 | ||
|
|
898e691fbf | ||
|
|
32819042e5 | ||
|
|
8ab284e146 | ||
|
|
90be753718 | ||
|
|
1a1cc38fea | ||
|
|
6fcf644115 | ||
|
|
46b084433f | ||
|
|
f055851ac2 | ||
|
|
8146511a64 | ||
|
|
e4c314b31a | ||
|
|
40f6bb52fa | ||
|
|
68380900ce | ||
|
|
ce3685b543 | ||
|
|
515bee2f01 | ||
|
|
08153b987d | ||
|
|
1e0dcd6fb4 | ||
|
|
6af4cb8799 | ||
|
|
f5443278b9 | ||
|
|
14f93019ac | ||
|
|
03e8db3f64 | ||
|
|
085ad1415f | ||
|
|
f31288bf06 | ||
|
|
2517132a53 |
No files matched your search
+24
-20
@@ -1,20 +1,24 @@
|
||||
.venv/
|
||||
nanoGPT/
|
||||
ckpt/
|
||||
data/
|
||||
data_*/
|
||||
out_*/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pt
|
||||
*.bin
|
||||
*.npy
|
||||
*.log
|
||||
*.tar
|
||||
*.zip
|
||||
*.gguf
|
||||
*.egg-info/
|
||||
.workbuddy-ai/
|
||||
vqcheck/
|
||||
.DS_Store
|
||||
.venv/
|
||||
nanoGPT/
|
||||
ckpt/
|
||||
data/
|
||||
data_*/
|
||||
out_*/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pt
|
||||
*.bin
|
||||
*.npy
|
||||
*.log
|
||||
*.tar
|
||||
*.zip
|
||||
*.gguf
|
||||
*.egg-info/
|
||||
.workbuddy-ai/
|
||||
vqcheck/
|
||||
.DS_Store
|
||||
archive/figures/
|
||||
*.bundle
|
||||
*.tar.bz2
|
||||
out_spatial/
|
||||
@@ -1,23 +1,53 @@
|
||||
# tiny-gpt
|
||||
|
||||
小模型的多模态与可控生成实验。代码在 `mm/`,需求与架构决策见 `mm/REQUIREMENTS.md`。
|
||||
小模型的空间结构与多模态实验。当前主线是 `spatial/`:一个不带因果掩码的关系主干,
|
||||
回答"这件事能不能被观测证明",证不了就说不知道。
|
||||
|
||||
## 目录
|
||||
|
||||
| 路径 | 内容 |
|
||||
| 路径 | 内容 | 状态 |
|
||||
|---|---|---|
|
||||
| `spatial/` | 关系主干、数据契约、生成器、检查器、训练与诊断工具 | **当前主线** |
|
||||
| `spatial/providers/` | 真实输入:KiCad 网表/板子 → `Observation` | 新增 |
|
||||
| `spatial/configs/` | 运行配置,规范配置在顶层,历史实验在 `archive/` | |
|
||||
| `docs/` | 全部文档:需求、路线、契约、测出来的结果 | |
|
||||
| `mm/` | 前一条线:45M 原生多模态 GPT,补全/可控生成实验 | 暂停,代码与探针保留 |
|
||||
| `vendor/llamagen_vq/` | VQ 编解码(第三方) | 依赖 |
|
||||
| `tools/` | 与模型无关的小工具 | |
|
||||
| `archive/` | 旧实验产物(图、对比图),不入库 | |
|
||||
|
||||
## 文档
|
||||
|
||||
| 文件 | 内容 |
|
||||
|---|---|
|
||||
| `mm/` | 训练、数据构建、评测探针 |
|
||||
| `vendor/llamagen_vq/` | VQ 编解码(第三方,56K) |
|
||||
| `pdl.sh` | 分片下载辅助 |
|
||||
|
||||
## 不入库
|
||||
|
||||
`.venv/` `ckpt/` `data_*/` `out_*/` `nanoGPT/` —— 环境、权重、数据集、训练输出。
|
||||
| [docs/FINDINGS.md](docs/FINDINGS.md) | **先读这个**:M1 全部测量结果、八处修复的单变量证据、三种子水位 |
|
||||
| [docs/M2_INPUT_SOURCE.md](docs/M2_INPUT_SOURCE.md) | **M2 起点**:关系图从哪来,三类关系三种来源的实测 |
|
||||
| [docs/M2_VIEW_CONTRACT.md](docs/M2_VIEW_CONTRACT.md) | **M2 契约**:哪部分"没看到"可推、哪部分必须声明、哪部分禁止 |
|
||||
| [docs/M2_PROVIDER_KICAD.md](docs/M2_PROVIDER_KICAD.md) | **M2 provider**:KiCad 网表/板子接进来,三块真实板子的实测 |
|
||||
| [docs/M2_SOURCE_CONFLICT.md](docs/M2_SOURCE_CONFLICT.md) | **M2 冲突**:两份来源说法相反时,只有两个世界都成立的答案才算答案 |
|
||||
| [docs/SPATIAL_FOUNDATION.md](docs/SPATIAL_FOUNDATION.md) | 架构提案与分阶段路线 |
|
||||
| [docs/REQUIREMENTS.md](docs/REQUIREMENTS.md) | 需求与架构决策 v3 |
|
||||
| [docs/PLAN_v2.md](docs/PLAN_v2.md) | 上一版路线(已被上面两份取代,留作对照) |
|
||||
|
||||
## 常用
|
||||
|
||||
```bash
|
||||
cd mm
|
||||
git log --oneline
|
||||
/home/lhj/projects/tiny-gpt/.venv/bin/python train.py --help
|
||||
python3 -m spatial.cli smoke # 契约测试,必须先过
|
||||
python3 -m spatial.baselines 128 # 平凡规则基线
|
||||
python3 -m spatial.extract 24 # 几何→关系图的保真度
|
||||
python3 -m spatial.extract tol 8 # 接触判定对余隙的敏感度
|
||||
python3 -m spatial.view 24 # 表面可见性能不能替代 hidden/dangling
|
||||
python3 -m spatial.providers.kicad_netlist <a.net> # 真实网表→关系图(零依赖)
|
||||
python3 -m spatial.providers.kicad_board <a.kicad_pcb> # 板子一侧,需 pcbnew
|
||||
python3 -m spatial.cli train --config spatial/configs/declared.json --seed 0
|
||||
python3 -m spatial.cli report --config spatial/configs/declared.json --seed 0 --n 128
|
||||
python3 -m spatial.cli report --config spatial/configs/dangling.json --n 128 --ablate dangling
|
||||
```
|
||||
|
||||
主实验是 `declared.json`(可用性只给合规的 scope);`dangling.json` 是泄漏对照组。
|
||||
结论一条:单次运行不构成证据,任何数字都要三种子(`--seed 0 1 2`)读。
|
||||
|
||||
## 不入库
|
||||
|
||||
`.venv/`、`ckpt/`、`data_*/`、`out_*/`、`archive/figures/`、`__pycache__/`。
|
||||
训练输出在服务器 `~/projects/tiny-gpt/out_spatial/`,只保留规范配置的三种子。
|
||||
@@ -0,0 +1,117 @@
|
||||
# 空间结构底座:M1 阶段的测量结果
|
||||
|
||||
这份文件只记录**测出来的东西**,不记录愿望。每条结论后面跟着能复现它的命令。
|
||||
|
||||
## 一句话
|
||||
|
||||
三个域里"证明或弃权"这件事现在是算出来的,不是按家族查表查出来的:
|
||||
`area.sup2d` 同一族内 54 条可判全部答对、74 条不可判全部弃权(三种子一致)。
|
||||
14 个家族 × 3 个种子里,seed1 与 seed2 全部 1.000,seed0 只在自由度的集合任务上
|
||||
失败。达成这一点的关键不是加了什么模块,而是修掉了四处信息在管道里丢失或被污染的
|
||||
地方,以及把标签语义从"两个世界比一比"改成"隐藏内容只会增加证据"。
|
||||
|
||||
## 一、必须先算平凡基线,否则数字没有意义
|
||||
|
||||
`python3 -m spatial.baselines 128`
|
||||
|
||||
第一版配置训练完,模型在 10 个家族里有 6 个与"发生编辑就答 false"这个一位分类器
|
||||
**精确到小数点后三位相同**(cond.p1 1.000、area.sup2 1.000、dof.c6 1.000、
|
||||
cond.p3 0.586、cond.p3h 0.641、dof.c6r 0.000)。那三个训练家族里"移走了东西"和
|
||||
"目标失去支撑"是同一个事件。
|
||||
|
||||
## 二、修掉的问题,每个都有单变量证据
|
||||
|
||||
| # | 问题 | 证据 |
|
||||
|---|---|---|
|
||||
| 1 | 稳定性家族唯一的编辑必然导致倒塌 | 加诱饵块 D + 无害编辑,edit 规则 1.000→0.594 |
|
||||
| 2 | `hidden_layers` 只在 digest 里、没进过张量 | cond.p1 **0.602→1.000**,其余 8 族不动 |
|
||||
| 3 | 只有 connection 域声明盲区 | `_observe` 改为自动导出 hidden 计数 |
|
||||
| 4 | `remove_entity` 没把关系边一起切断,图上目标仍被支撑 | 修后稳定性 3 种子里 2 个到 1.000 |
|
||||
| 5 | 已移除的边仍进入实体的入射求和 | 稳定性三种子从 0.898 抖动到全 1.000 |
|
||||
| 6 | 因果变量是固定值不是一个分布 | 族内两标签并存(area.sup2h 从 128 全不可判变成 36/92) |
|
||||
| 7 | **query 只能经由注意力取关联关系,被 13 个位置稀释** | `dof.set` 单族训练的答案 loss 卡在 ln2、准确率 0.49;给 query 一条直取关联关系的通路后 **→ 1.000** |
|
||||
| 8 | 前 100 步就是一次 10 倍 lr 跳变(warmup 太短) | 同 lr、同步数,只把 warmup 从 100 改到 300:seed0 的 dof.set **0.203→1.000**,三种子全绿 |
|
||||
|
||||
第 7 条是最重要的一处:模型连只有约 30 种不同场景的训练集都拟合不了,说明"六个轴
|
||||
是否全 lock"这种合取判断被注意力平均掉了。诊断方式是造一个没有干预的纯子任务族
|
||||
`dof.set`,把子技能从编辑交互里隔离出来。
|
||||
|
||||
## 三、标签语义的修正:隐藏内容只会增加证据
|
||||
|
||||
旧规则只比较"全状态"和"观测自己的世界"这两个世界。于是"底座在零件后面,而在这个
|
||||
具体场景里它本来也帮不上忙"被判成**可判 false**——这不是 agent 能知道的事实:另一个
|
||||
同样符合观测的世界把底座挪到形心底下,答案就翻了。实测 area.sup2h 因此出现 36 条
|
||||
假"可判",模型在"全答"和"全弃权"之间摇摆(seed0 acc 0 / seed2 同类配置 acc 1.000
|
||||
abst 0)。
|
||||
|
||||
隐藏内容只会增加证据:隐藏的 conduct 只会连上、隐藏的 contact 只会支撑、隐藏的配合
|
||||
只会锁轴,都不会推翻观测里已有的证明。所以:
|
||||
|
||||
* 可见结构已经证明 → 可判 `true`;
|
||||
* 没证明 → `unknown`,不管手上那一个全状态怎么裁。
|
||||
|
||||
代价是隐藏家族不再有"可判 false",于是"看到隐藏就弃权"成了完美答案。为此新增两个
|
||||
**诱饵隐藏**家族 `area.sup2d` / `dof.c6d`:诱饵自己藏在视野外、悬挂在地面上而从不
|
||||
悬挂在目标上,可见结构仍能证明目标成立。同族内因此既有可判也有不可判。
|
||||
|
||||
## 四、三种子(唯一可信的读法)
|
||||
|
||||
`python3 -m spatial.cli train --config spatial/configs/dangling.json --seed $s`
|
||||
`python3 -m spatial.cli report --config spatial/configs/dangling.json --seed $s --n 128`
|
||||
|
||||
| family | 可判 | 不可判 | 最便宜规则 | seed0 | seed1 | seed2 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| cond.p1 | 128 | 0 | 1.000 | 1.000 | 1.000 | 1.000 |
|
||||
| cond.p3 | 128 | 0 | 0.734 | 1.000 | 1.000 | 1.000 |
|
||||
| cond.p1h | 34 | 94 | 1.000 | 1.000 / abst 1.000 | 同 | 同 |
|
||||
| cond.p3h | 84 | 44 | 0.656 | 1.000 / abst 1.000 | 同 | 同 |
|
||||
| area.sup2 | 128 | 0 | 0.641 | 1.000 | 1.000 | 1.000 |
|
||||
| area.sup3 | 128 | 0 | 0.680 | 1.000 | 1.000 | 1.000 |
|
||||
| area.free | 128 | 0 | 0.609 | 1.000 | 1.000 | 1.000 |
|
||||
| **area.sup2d** | 54 | 74 | 0.580 | **1.000 / abst 1.000** | 同 | 同 |
|
||||
| area.sup2h | 0 | 128 | — | abst 1.000 | 1.000 | 1.000 |
|
||||
| area.sup3h | 0 | 128 | — | abst 1.000 | 1.000 | 1.000 |
|
||||
| dof.set | 128 | 0 | 0.508 | 1.000 | 1.000 | 1.000 |
|
||||
| dof.c6 | 128 | 0 | 0.789 | 1.000 | 1.000 | 1.000 |
|
||||
| dof.c6r | 128 | 0 | 1.000 | 1.000 | 1.000 | 1.000 |
|
||||
| **dof.c6d** | 18 | 110 | — | 1.000 / abst 1.000 | 1.000 / 1.000 | 1.000 / 1.000 |
|
||||
| dof.c6h | 0 | 128 | — | abst 1.000 | abst 1.000 | abst 1.000 |
|
||||
|
||||
(warmup 300 修正之后重测;此前 warmup 100 时 seed0 的 dof.set 0.203、dof.c6 0.680、
|
||||
dof.c6d 可判 0.000。)
|
||||
|
||||
**单次运行不构成证据**:同一份配置只改了边特征的维度就换过一次结论,所以表格必须是
|
||||
三种子。
|
||||
|
||||
## 五、消融:哪些结构件真的在被用
|
||||
|
||||
`python3 -m spatial.cli report --config ... --ablate dangling,scene`
|
||||
|
||||
- 只清 `dangling` 张量时,除了 area.sup2h 以外预测全部不变——因为悬空信号还写在边
|
||||
特征里。**消融必须同时清掉结构槽位和标志位**,否则测的是另一条通路。
|
||||
- 同时清掉 `dangling,scene` 后:cond.p1h / dof.c6h 的弃权掉到 0,说明这两族靠结构
|
||||
通道(图 + 编辑)而不是全局计数;area.sup2 的 1.000 掉到 0.594,说明它靠 scene
|
||||
知道"这一族没有隐藏"才敢算几何。
|
||||
|
||||
## 六、还没解决
|
||||
|
||||
1. ~~自由度域 1/3 种子失败~~ **已解决**:根因是预热带太短(100 步 ≈ 一次 10 倍
|
||||
lr 跳变),改为 300 后三种子全绿。它同时说明这类"某族学不会"的报告在改成
|
||||
三种子之前是不可读的——单次运行会把落地失败误报成表征失败。
|
||||
2. **校准仍是死旋钮。** top-1 置信度基本都 1.000,temp 学到 0.63–0.71,ECE 0–0.09
|
||||
(比之前好,但仍靠不住)。硬标签 + CE 趋 0 把 logits 推到饱和,温度改不动。
|
||||
3. **两个全隐藏族只测召回。** area.sup2h / dof.c6h 没有可判行,"看到隐藏就弃权"
|
||||
就能满分。真正的判别力在 area.sup2d / dof.c6d 上。
|
||||
|
||||
## 复现
|
||||
|
||||
```
|
||||
python3 -m spatial.cli smoke # 契约
|
||||
python3 -m spatial.baselines 128 # 平凡基线
|
||||
python3 -m spatial.cli train --config spatial/configs/dangling.json --seed 1
|
||||
python3 -m spatial.cli report --config spatial/configs/dangling.json --seed 1 --n 128
|
||||
python3 -m spatial.cli report --config spatial/configs/dangling.json --n 128 --ablate dangling,scene
|
||||
```
|
||||
|
||||
`configs/cross_oneshot.json` 保留最初那位一位可分的混合集,作为对照;
|
||||
`configs/setonly.json` 是隔离集合子技能的探针配置。
|
||||
@@ -0,0 +1,137 @@
|
||||
# M2:那张实体+关系图,由谁给出
|
||||
|
||||
M1 的全部结果都建立在一个从未验证的假设上:`Observation` 里的实体和关系是**给定**
|
||||
的。真实场景里没有这个"给定",所以这是 M2 的第一个问题,比任何模型改动都靠前。
|
||||
|
||||
结论先说:**三类关系来自三种不同的地方,几何只能给出其中一类。** 几何这一类
|
||||
原先把可靠性全押在一个距离容差上,容差跨过余隙就会伪造出能通过校验的支撑;现已
|
||||
改成共面精确匹配,那个参数退回数值噪声量级。剩下两类必须来自元数据。
|
||||
|
||||
## 一、实测:几何能给出多少
|
||||
|
||||
`python3 -m spatial.extract 24`
|
||||
|
||||
做法不接 CAD、不引第三方库:把盒子表面写成六张面,只按**两张面是不是同一张面**
|
||||
推接触关系,完全不读 schema 里的答案,然后拿几何图去重算检查器的结论。
|
||||
|
||||
| family | 真边 | 提取 | 真阳率 | 真阴率 | 凭证有效 | 余隙 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| area.sup2 | 3 | 3 | 1.00 | 1.00 | 1.00 | 10 |
|
||||
| area.sup3 | 4 | 4 | 1.00 | 1.00 | 1.00 | 16 |
|
||||
| area.sup2d | 3 | 3 | 1.00 | 1.00 | 1.00 | 10 |
|
||||
| area.free | 2 | 2 | — | 1.00 | — | 22 |
|
||||
| area.gap1/2/4 | 2 | 2 | — | 1.00 | — | 1–4 |
|
||||
| cond.p1 / p3 / p1h / p3h | 3–7 | **0** | **0.00** | — | 0.00 | — |
|
||||
| dof.c6 / c6d / set | 6 | **0** | **0.00** | 1.00 | 0.00 | — |
|
||||
|
||||
两件事:
|
||||
|
||||
* **接触关系可以 100% 从几何恢复**,连凭证都对得上(`area.*` 全列 1.00)。
|
||||
`area.gap*` 这一行也一致:1–4 格的余隙下,几何说没有接触,schema 也真的没有
|
||||
这条边,两边对得上——这是第三节那次夹具修复之后才成立的。
|
||||
* **连通和自由度一条都提不出来**(提取 0 条,真阳率 0.00)。不是"差一点"。
|
||||
|
||||
注意"真阴率 1.00"不是成绩:零关系的图对每一条都答 false,负类全是白送的。真阳率
|
||||
和真阴率必须分开看,这正是 M1 里反复吃过的亏。
|
||||
|
||||
## 二、三类关系,三种来源
|
||||
|
||||
| 关系 | 几何能不能给 | 真实来源 | 状态 |
|
||||
|---|---|---|---|
|
||||
| `contact` | **能**,100% | 共面精确匹配(`spatial/extract.py`) | 已实现并验证 |
|
||||
| `conduct` | 不能,0% | 材料、层定义、网表(PCB 的 netlist / 原理图) | 待接 |
|
||||
| `constraint` | 不能,0% | 装配配合、要素树(CAD 的 mates / 约束定义) | 待接 |
|
||||
|
||||
所以"谁来提供这张图"的正确答案不是某一个来源,而是**混合来源**。任何声称"纯几何
|
||||
理解结构"的路线,在这三类里只覆盖一类——而且覆盖的那一类还会对连通问题永远答
|
||||
false,看起来准确率还不错。
|
||||
|
||||
## 三、容差曾经是决定答案的参数(已改成共面精确匹配)
|
||||
|
||||
`python3 -m spatial.extract tol 8`
|
||||
|
||||
`area.gap1/2/4` 把上块抬离底座 1/2/4 格,然后扫参数。两版判定并排跑,旧版留作
|
||||
控制组:
|
||||
|
||||
```
|
||||
距离阈值(第一版,tol 以格为单位扫)
|
||||
family 间隙 0.0 0.5 1.0 2.0 4.0
|
||||
area.sup2 0 8/8 ok 8/8 ok 8/8 ok 8/8 ok 8/8 ok
|
||||
area.gap1 1 0/8 - 0/8 - 8/8 x 8/8 x 8/8 x
|
||||
area.gap2 2 0/8 - 0/8 - 0/8 - 8/8 x 8/8 x
|
||||
area.gap4 4 0/8 - 0/8 - 0/8 - 0/8 - 8/8 x
|
||||
|
||||
共面精确匹配(第二版,eps 以坐标单位扫)
|
||||
family 间隙 0 1e-12 1e-9 1e-6 1e-3 1.0
|
||||
area.sup2 0 8/8 ok 8/8 ok 8/8 ok 8/8 ok 8/8 ok 8/8 ok
|
||||
area.gap1 1 0/8 - 0/8 - 0/8 - 0/8 - 0/8 - 8/8 x
|
||||
area.gap2 2 0/8 - 0/8 - 0/8 - 0/8 - 0/8 - 0/8 -
|
||||
area.gap4 4 0/8 - 0/8 - 0/8 - 0/8 - 0/8 - 0/8 -
|
||||
```
|
||||
|
||||
`x` = 提取出了一条不存在的接触(这一步已经把答案 false 翻成 true),但凭证校验
|
||||
自己复核几何后拒了它。`!` = 假边连校验都过了,现在不该出现。
|
||||
|
||||
三件事:
|
||||
|
||||
* **距离法的假边条件恰好是 `容差 ≥ 间隙`。** 容差因此不是"精度参数",而是"决定
|
||||
答案的参数":真实装配的余隙是 0.2mm 级,跨过去就凭空焊出一个支撑。
|
||||
* **共面法里 eps 扫四个数量级(1e-12 → 1e-3)一格不动。** 因为贴合的两张面本来
|
||||
就是同一张面,判定不涉及"多近算近"。eps 只盖浮点噪声。
|
||||
* **滥用那一列说明了它为什么只能是数值兜底。** 把 eps 给到 1.0(设计容差量级),
|
||||
`area.gap1` 立刻回到 `8/8`——旧坑一模一样。参数换了类别,坑还在原地,所以这条
|
||||
不能被当成"可调"。
|
||||
|
||||
### 顺带修掉的夹具矛盾
|
||||
|
||||
近贴合家族原先一边把上块抬高 1/2/4 格,一边在 schema 里声明 T 和 P **接触**。这是
|
||||
夹具自己和自己矛盾:几何上没碰上,就不存在这条边。现在 `clearance > 0` 不再生成
|
||||
`kPT`,真边从 3 条降到 2 条,答案变成 false。
|
||||
|
||||
这一改动让这三个家族第一次变锋利:假接触不再只是"多画一条冗余边",而是**把结论
|
||||
从 false 翻成 true**。
|
||||
|
||||
代价也要记清楚:它们现在是**单答案家族**(恒 false),常量规则就能拿 1.000
|
||||
(`python3 -m spatial.baselines` 实测 majority share 1.00)。所以 `area.gap*`
|
||||
**只做提取器的回归测试,不进任何 split**。`smoke` 每次都会打印"哪些家族没被任何
|
||||
split 使用",这一条就是靠它守住的。
|
||||
|
||||
### 顺带发现的校验器漏洞(已修)
|
||||
|
||||
第一次跑这张表时,每一格都是 `!`——假边**全部通过了凭证校验**。原因:
|
||||
`validate_evidence` 对稳定性只检查"凭证链能不能够到地面",从不复核每一步是不是
|
||||
真的接触。于是一个 provider 只要吐出一条假接触,就能伪造出能通过校验的支撑。
|
||||
|
||||
现在 `_contact_is_real` 按盒子几何重新推导每一步(面必须相接、投影必须重叠、
|
||||
接地必须等高),假边一律拒绝。修完之后模型自己给出的凭证仍然 100% 有效
|
||||
(`report` 的 cert 列 1.000),说明它之前用的不是这条宽松通道。
|
||||
|
||||
**但这道防线只覆盖稳定性。** `conduct` 和 `constraint` 的答案**直接由边决定**,
|
||||
没有几何可以复核——那两类只能靠来源可信,不能靠校验兜底。这是接元数据 provider
|
||||
时最需要小心的地方。
|
||||
|
||||
## 四、接口不用改,缺的是 provider
|
||||
|
||||
`Observation` 已经是"我看到什么 + 我缺什么"的接口:`hidden` 说缺了哪类东西,
|
||||
`dangling` 说缺的那条关系挂在哪个可见实体上。M1 的弃权就是靠这两样算出来的。
|
||||
所以 M2 不需要新的数据契约,只需要两个把真实数据翻译成 `Observation` 的适配器:
|
||||
|
||||
```
|
||||
几何 网格/点云 ──┐
|
||||
├─→ Observation(entities, edges, hidden, dangling) ─→ 主干
|
||||
元数据 网表/装配树 ─┘
|
||||
```
|
||||
|
||||
## 五、下一步(按顺序)
|
||||
|
||||
1. ~~把接触判定从"距离阈值"换成"共面精确匹配"~~ **已完成**(第三节)。顺带修掉
|
||||
近贴合家族的夹具矛盾,并把它们标成不进 split 的诊断家族。
|
||||
2. **接一个真元数据 provider**:先做 PCB(KiCad 网表 → `conduct`),再做装配
|
||||
(FreeCAD 配合 → `constraint`)。验收标准不是"能跑",而是端到端一致:同一批
|
||||
样板,提取器 + 检查器给出的答案与人工确认的答案一致。
|
||||
|
||||
第 2 件里有一处必须提前想清楚:`hidden` 和 `dangling` 说"有东西我没看到",这要求
|
||||
系统知道**完整模型**是什么。真实场景里这等于要求"先有完整数据再谈不确定",正好
|
||||
和我们想摆脱的前提冲突。折中方案是让 provider 只声明**视野边界**(相机的可见锥、
|
||||
视图的遮挡范围),由边界推"什么可能没被看到",而不是从完整模型反推。这条要在接
|
||||
provider 之前定下来,否则弃权会退化成"有元数据才敢答"。
|
||||
@@ -0,0 +1,102 @@
|
||||
# M2 provider 之一:KiCad 网表与板子
|
||||
|
||||
`docs/M2_INPUT_SOURCE.md` 说 `conduct` 只能来自元数据,`docs/M2_VIEW_CONTRACT.md`
|
||||
说"缺口只能声明不能编造"。这份文档是这两条第一次落到**真实输入**上:拿 KiCad 官方
|
||||
自带的 18 个 demo 工程当输入,用 KiCad 自己的引擎当裁判。
|
||||
|
||||
代码:`spatial/providers/sexpr.py`(s-表达式,零依赖)、
|
||||
`spatial/providers/kicad_netlist.py`(网表 → `Observation`)、
|
||||
`spatial/providers/kicad_board.py`(板子一侧,需要 pcbnew)。
|
||||
|
||||
## 一、三块真实板子
|
||||
|
||||
KiCad 10.0.6,网表用 `kicad-cli sch export netlist` 导出,板子用 `pcbnew` 读。
|
||||
|
||||
| 工程 | 器件 | 焊盘节点 | 网 | 单点网 | 最大网 | conduct 边 | 板上焊盘 | 缺连接 |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| `ecc83` | 15 | 33 | 13 | 4 | 7 | 41 | 33 | 0 |
|
||||
| `complex_hierarchy` | 68 | 164 | 52 | 2 | 26 | 473 | 165 | 0 |
|
||||
| `stickhub` | 94 | 266 | 47 | 2 | **80** | **4129** | 278 | 0 |
|
||||
|
||||
三件事:
|
||||
|
||||
* **网表能直接翻译成 `Observation`**:一个 `(器件, 脚)` 一个实体,同一条网内两两
|
||||
`conduct`。`spatial/cli.py` 里 `check_netlist_provider` 把这个映射钉进了 smoke
|
||||
(3 器件 / 6 焊盘 / 4 边,跨网不许有边,单点网必须保持孤立)。
|
||||
* **单点网是真实现象,不是脏数据**:KiCad 给每个 no-connect 脚单独建一条网,名字形如
|
||||
`unconnected-(U1-Pad7)`。这是"这个脚什么也没连"的**显式**说法,所以它是"假"而不是
|
||||
"不知道"。4 / 2 / 2 条。
|
||||
* **边数是二次的**:`stickhub` 的 GND 网有 80 个节点,一条网就贡献 3160 条边,占全板
|
||||
76%。检查器无所谓(它只做可达性),但主干把边当序列喂,`max_entities` 是 32 ——
|
||||
要接的话必须换成"网 = 超边"的编码,不能靠两两展开。这是 M2 后续一个硬约束。
|
||||
|
||||
## 二、网表的盲区,实测 0–0.7%
|
||||
|
||||
原本的猜测写在了第一版代码注释里:"网表不提 NC 脚和机械脚"。**只对了一半**:
|
||||
|
||||
| 板子 | 板上焊盘 | 网表没提 | 比例 | 是什么 |
|
||||
|---|---|---|---|---|
|
||||
| `ecc83` | 33 | 0 | 0.0% | —— |
|
||||
| `complex_hierarchy` | 165 | 1 | 0.6% | `U102.1`(重复编号焊盘) |
|
||||
| `stickhub` | 278 | 2 | 0.7% | `H1.''`、`Y1.''`(无编号机械焊盘、晶振屏蔽脚) |
|
||||
|
||||
NC 脚是**覆盖的**(各自成单点网),真正漏掉的是**没有焊盘编号**的机械焊盘。所以
|
||||
netlist provider 的 `scope` 声明"这份网表就是全部"在 99.3% 以上是对的,剩下那一点
|
||||
只能由知道封装的一侧说出来(`kicad_board.coverage`)。
|
||||
|
||||
这条修正很典型:一个听起来合理、写进注释就没人再查的假设,和实测差了一个类别。
|
||||
|
||||
## 三、两份来源会不会打架:0 冲突,但检测器被测过了
|
||||
|
||||
网表说"这两个脚连通",板子说"铜箔连没连"。三块 demo 都是成品板,`缺连接` 全 0 ——
|
||||
也就是两份来源在连通性上零冲突。
|
||||
|
||||
但"一直返回 0 的指标"等于没测过。所以加了阳性对照:把某条网的铜删掉,要求数字动。
|
||||
|
||||
```
|
||||
control on ecc83-pp.kicad_pcb
|
||||
cut net 'Net-(U1B-K)': removed 2 track(s), 2 pads on it
|
||||
missing before: 0
|
||||
missing after : 1
|
||||
PASS the detector notices the cut
|
||||
```
|
||||
|
||||
**这个对照抓到了一个真 bug。** 第一版的计数写成:
|
||||
|
||||
```python
|
||||
try:
|
||||
return len(board.GetConnectivity().GetRatsnestForNet(code)) # 按网
|
||||
except Exception:
|
||||
return -1
|
||||
```
|
||||
|
||||
`GetRatsnestForNet` 在这个绑定里返回不透明对象,`len()` 抛 `TypeError`,被 `except`
|
||||
吞成 -1;调用方用 `n > 0` 判断,于是**每一次失败都渲染成"0 条未连通"**,报告上完美。
|
||||
修法两条:换成能用的 `GetUnconnectedCount(False)`(板级,按网取不到——见模块注释),
|
||||
以及**删掉所有兜底 `except`**:测量失败就该崩,不该给出一个像答案的数字。
|
||||
|
||||
## 四、还没做的
|
||||
|
||||
1. **"两份来源冲突"在契约里没有位置。** `checker` 只有 "缺了东西"(withheld),没有
|
||||
"两份来源说法相反"。现在能测出冲突数,但没法让系统对它弃权。要么给 `Observation`
|
||||
加一个 `conflict` 字段,要么让 provider 自己降级成"缺口"——这需要先想清楚,不能顺手加。
|
||||
2. **几何那一半仍然来自夹具。** 网表没有坐标;`pcbnew` 有焊盘坐标和 3D 模型,但没有
|
||||
B-rep 面,`spatial/extract.py` 的共面判定用不上。所以真实板子的 `contact` 关系还没
|
||||
接上,这一半仍是合成几何。
|
||||
3. **`constraint` 还没有来源。** 下一个该做装配(FreeCAD 的 mates),服务器上
|
||||
`openscad` / `cadquery` 都不在(`docs/M2_INPUT_SOURCE.md` 记过)。
|
||||
|
||||
## 五、命令
|
||||
|
||||
```bash
|
||||
python3 -m spatial.providers.kicad_netlist <a.net> ... # 任何机器,零依赖
|
||||
python3 -m spatial.providers.kicad_board <a.kicad_pcb> ... # 需要 pcbnew
|
||||
python3 -m spatial.providers.kicad_board <pcb> <net> # 覆盖度(盲区大小)
|
||||
python3 -m spatial.providers.kicad_board control <pcb> # 阳性对照
|
||||
```
|
||||
|
||||
服务器上现成的工程在 `/usr/share/kicad/demos/`,网表导到 `/tmp/nl/`:
|
||||
|
||||
```bash
|
||||
kicad-cli sch export netlist -o /tmp/nl/x.net /usr/share/kicad/demos/<p>/<p>.kicad_sch
|
||||
```
|
||||
@@ -0,0 +1,130 @@
|
||||
# M2:两份来源打架时怎么办
|
||||
|
||||
`docs/M2_PROVIDER_KICAD.md` 第三节留了个口子:网表说"这两个脚接通",板子说"没有铜",
|
||||
系统现在只能数出冲突,没法据此弃权。这份文档把这个口子补上。
|
||||
|
||||
## 一、冲突不是"缺东西"
|
||||
|
||||
已有的 `withheld` 表达的是**信息不全**:清单里有五件,交过来三件。它的逻辑是
|
||||
"少的那部分可能正是缺的那块",所以可见结构证不出来就答 `unknown`。
|
||||
|
||||
冲突是另一件事:两份来源**都在说同一件事,而且说法相反**。没有"缺的那部分"——两边都把
|
||||
话说完了,只是对不上。这带来两个后果:
|
||||
|
||||
* 不能靠"再等等就有数据"来解决;
|
||||
* 谁对谁错**不该由系统自己定**。版本号、谁更新、谁是权威,这是人的决定,不是推理。
|
||||
|
||||
所以契约里 `conflicts` 只记录"这两个端点之间的关系有争议",不记录票数、不记录优先级。
|
||||
|
||||
## 二、规则:只在两个世界都成立的答案才算答案
|
||||
|
||||
一条被争议的关系有两个自洽的世界:它存在,它不存在。两者都和我们被告知的一切相容。
|
||||
于是:
|
||||
|
||||
| 去掉争议边后(sure 世界) | 带上争议边(maybe 世界) | 结论 |
|
||||
|---|---|---|
|
||||
| 已证 `true` | —— | `true`:这条证明没用到争议关系,争议不影响它 |
|
||||
| 证不出 | 也 `false` | `false`:无论争议关系存不存在,答案都是假 |
|
||||
| 证不出 | `true` 或不确定 | `unknown` |
|
||||
|
||||
第二行是新的,也是这条契约唯一比 `withheld` 更强的地方:`withheld` 无法枚举缺了什么,
|
||||
所以只要可见结构证不出来就只能弃权;`conflicts` 是**点名**的,于是"两个世界都假"是一个
|
||||
合法的 `false`,不是弃权。
|
||||
|
||||
`src.scope` 里最常见的两种情况正好各占一边:
|
||||
|
||||
* 争议落在**支路**上,还有第二条支路 → 去掉它仍有通路 → `true`(证明绕开了争议);
|
||||
* 争议落在**主干**上 → 每条路都要过它 → 去掉就断 → `unknown`。
|
||||
|
||||
## 三、争议关系不能当证据
|
||||
|
||||
`checker.validate_evidence` 多了一个 `conflicts` 参数:引用了争议关系的凭证一律拒绝。
|
||||
和 `_contact_is_real` 拒收几何上不存在的接触是同一条原则——**能被争议的东西不能承担
|
||||
证明**。`src.scope` 里那些 `true` 的凭证实测只用未被争议的边(见下),所以这条不是空话。
|
||||
|
||||
## 四、家族:争议的位置是族内变量
|
||||
|
||||
新家族(`connection` 域):
|
||||
|
||||
| 家族 | 抽什么 | 标签 |
|
||||
|---|---|---|
|
||||
| `src.scope` | 支路数 2/3,争议位置在支路 或 主干 | `true` / `unknown` 混 |
|
||||
| `src.clean` | 支路数 0/1/2,无争议 | `false` / `true` 混 |
|
||||
| `src.scope4` | 支路数固定 4,争议位置在支路 或 主干 | 只做测试 |
|
||||
|
||||
关键是**同一个场景形状、同样的边数,只有争议落点不同**。这样族级捷径("这个家族总是
|
||||
true")全部失效:`baselines` 实测 majority share 0.61 / 0.64 / 0.52,不再是 1.00。
|
||||
|
||||
前两版设计被自己否掉了:先是四个单答案家族(`src.p1/p1c/p2c/p0`,maj 全 1.00,常数规则
|
||||
满分,和 `area.gap*` 掉的是同一个坑),再是"争议固定落在支路"(还是单答案)。
|
||||
|
||||
## 五、验证
|
||||
|
||||
本地与服务器 `smoke` 全绿,逐条对应上面每一条承诺:
|
||||
|
||||
```
|
||||
ok 132 labels agree with the full-state checker, certificates validate
|
||||
ok 49 unknown samples are undecided by the observation (undisputed part)
|
||||
ok 880 samples: no two families assign different labels to the same observation
|
||||
ok 528 samples: declared inventory agrees with the diagnostic one
|
||||
```
|
||||
|
||||
三条检查的语义也跟着改了,不是为了让测试变绿:
|
||||
|
||||
* `check_insufficient` 里的"可见结构已证"改成**未被争议的可见结构**已证——否则一条争议边
|
||||
就能让一个 `unknown` 看起来毫无根据。
|
||||
* `check_scope_agrees` 的期望值从"诊断量"改成"诊断量 **或** 有冲突"。完整状态没法知道
|
||||
两份来源打架,所以 scope 才是那个并集;另加一条单独的检查:有冲突就必须在 scope 里
|
||||
计上数,忘了就 FAIL。
|
||||
* `check_cross_family_digest` 顺带覆盖了新家族:880 个样本、384 个不同输入,没有同输入
|
||||
异标签。
|
||||
|
||||
`conflicts` 也进了张量与 digest(`edge_feat` 末尾一位"争议位" + `scope.conflicts` 计数)。
|
||||
这一条是硬要求:`hidden_layers` 曾经只在 digest 不在张量,导致两个反标签的家族拿到同一个
|
||||
输入,白跑一整轮。**能进 digest 的东西必须同时进张量,否则模型学不到而检查抓不住。**
|
||||
|
||||
## 六、模型学得会吗:会,而且不用重训
|
||||
|
||||
`spatial/configs/sources.json`(`declared.json` 加 `src.scope` / `src.clean`,`src.scope4`
|
||||
留作结构外测试,12000 步 × 三种子):
|
||||
|
||||
| 家族 | 训练里有没有 | acc | abst |
|
||||
|---|---|---|---|
|
||||
| `src.scope` | 有 | 1.00 / 1.00 / 1.00 | 1.00 / 1.00 / 1.00 |
|
||||
| `src.clean` | 有 | 1.00 / 1.00 / 1.00 | —— |
|
||||
| `src.scope4`(4 支路) | **没有** | 1.00 / 1.00 / 1.00 | 1.00 / 1.00 / 1.00 |
|
||||
|
||||
`declared.json` 与 `dangling.json` 的 train 里**一条 `src.*` 都没有**,同样三种子 1.000。
|
||||
也就是说这条规则**零样本迁移**了:争议边被当成"不可用于证明的边",而"必须用未争议的边
|
||||
才能证 true、否则弃权"正是模型原有的单调规则,只是输入多了一位。
|
||||
|
||||
这不是意外,反而是个好信号——契约的扩展没有要求新的推理能力,只要求把已有能力表达出来。
|
||||
|
||||
### 但这得验,不能假设
|
||||
|
||||
零样本满分也可能是蒙的:争议边和其他特征(层号、边数)相关,模型没读那一位也能对。所以
|
||||
单独消融争议位(`--ablate disputed`,只清 `edge_feat` 末尾那一位):
|
||||
|
||||
| | acc | abst | #true |
|
||||
|---|---|---|---|
|
||||
| 有争议位 | 1.000 | **1.000** | 66 |
|
||||
| 清零争议位 | 1.000 | **0.000** | 128 |
|
||||
|
||||
清零之后模型对**每一条**都答 `true`(`#true` = 128 = 全部),因为争议边看起来和普通边
|
||||
一模一样,通路总是存在。而 `src.clean`(族内没有争议)在这个消融下一位没变——影响是
|
||||
定点的,不是全局降级。这才叫"读懂了"。
|
||||
|
||||
## 六之二、一处退步
|
||||
|
||||
`dof.c6h`(全不可判家族)的弃权:`declared` 三种子 1.00,`sources` 与 `dangling` 的
|
||||
seed2 掉到 0.93 / 0.94。属于单种子噪声,但三种子里出现一次,按纪律记下来,不当作 1.00。
|
||||
|
||||
## 七、还没做的
|
||||
|
||||
1. **冲突的优先级**。现在所有争议一视同仁。真实系统里"网表比板子新"是有意义的,但那是
|
||||
版本元数据,得由人给,不能靠模型猜。
|
||||
2. **几何与元数据之间的冲突**还没接上。`contact` 来自几何、`conduct` 来自网表,两者本来
|
||||
不重叠,所以现在只在同类来源之间(网表 vs 铜箔)测冲突。跨类的冲突长什么样还没定义。
|
||||
3. **多份来源的多数票**。三份来源两票对一票算不算解决?我的判断是不算——票数不是证据,
|
||||
而且会把"两份都错"变成"多数对",这正好是这套系统要避免的事。这条留作明确的设计否决,
|
||||
不是遗漏。
|
||||
@@ -0,0 +1,159 @@
|
||||
# M2 输入契约:哪些"没看到"可以说,哪些不能说
|
||||
|
||||
`Observation.hidden` 和 `Observation.dangling` 是 M1 弃权的全部依据。它们现在的
|
||||
算法是**完整状态减去可见集合**。真实场景里没有完整状态 —— 否则就不需要谈不确定。
|
||||
所以这两个字段是一个循环:要知道"我少看到了一条关系",得先看到它的两端。
|
||||
|
||||
这篇文档定三件事:别的路走过没有(走过,走不通)、契约应该长什么样、以及它**能不能
|
||||
替代泄漏**(能:合规输入与泄漏输入在 19 个家族上三种子完全打平,见第四节)。
|
||||
|
||||
## 一、试过的路:表面可见性
|
||||
|
||||
最容易想到的替代品是几何:拿几台正交相机,一个面如果背朝所有相机、或者被别的零
|
||||
件挡住,就是"没看到的面";没看到的面正是关系可能附着的地方。
|
||||
|
||||
`python3 -m spatial.view 24`(`spatial/view.py`,只吃可见实体和相机方向,不碰完整
|
||||
状态):
|
||||
|
||||
```
|
||||
family 可见 有盒 悬空锚 有未见面 两者 仅悬空 仅见面 平均未见面
|
||||
cond.p1 4.0 0.0 0.0 0.0 0.0 0.0 0.0 0.00
|
||||
cond.p1h 4.0 0.0 2.0 0.0 0.0 2.0 0.0 0.00
|
||||
area.sup2 4.0 3.0 0.0 3.0 0.0 0.0 3.0 1.67
|
||||
area.sup2h 3.0 2.0 2.0 2.0 1.0 1.0 1.0 1.00
|
||||
area.sup3h 4.0 3.0 2.0 3.0 1.0 1.0 2.0 1.08
|
||||
area.sup2d 4.0 3.0 1.0 3.0 0.0 1.0 3.0 1.67
|
||||
dof.c6h 6.0 0.0 1.0 0.0 0.0 1.0 0.0 0.00
|
||||
```
|
||||
|
||||
两列数字就是判决书,方向相反:
|
||||
|
||||
* **`仅悬空`:有悬空关系,可六张面全被看到。** 连接域和自由度域全是这种。内层导体
|
||||
不是被挡住的,它在板子**里面**——表面可见性对它一个字都说不出来(`有盒 0.0`)。
|
||||
一个挂在完全可见焊盘上的隐藏支路,几何上没有任何痕迹。
|
||||
* **`仅见面`:有看不到的面,可那里没有悬空关系。** 坐着的东西底面永远看不到
|
||||
(平均 1–1.7 张面不可见),所以这个信号在稳定性域**恒亮**,对"哪个零件藏着"没有
|
||||
分辨力。
|
||||
|
||||
两条同时成立,而且交集几乎为空:**表面可见性既漏又滥,不能替代 `hidden`/`dangling`。**
|
||||
|
||||
这不是实现没做好,是问题本身的结构。遮挡能推出"某个面上可能有东西",推不出"这个
|
||||
场景里确实有一条关系,只是我看不到它的另一头"。
|
||||
|
||||
## 二、契约:三档
|
||||
|
||||
分档的标准只有一个:**这句话里有没有端点。**
|
||||
|
||||
| 档 | 内容 | 谁能给 | 为什么 |
|
||||
|---|---|---|---|
|
||||
| 可推 | 从可见几何算出接触、算出面朝哪、算出谁挡谁 | 几何 | 只看观测就够,`spatial/extract.py` 已实测接触 100% 可恢复 |
|
||||
| 必须声明(只给计数与名单) | 零件清单(BOM 几件、按类别)、关系清单(几条、按类别)、层清单(板子几层)、本次交付了哪些 | 元数据源 | 它是一条关于**源自己**的声明,不是关于场景的结论 |
|
||||
| 禁止 | 任何关系的端点、任何"这里应该有个支撑"、任何指认 | —— | 有端点就等于给了答案的一半;这是 M2 存在的理由 |
|
||||
|
||||
第二档是关键妥协,也是这份契约的全部内容:**源可以告诉你"我的清单比给你的多",
|
||||
不能告诉你"多出来的是什么"。**
|
||||
|
||||
`Observation.scope` 就是按这一档写的:
|
||||
|
||||
```python
|
||||
scope = {
|
||||
"parts": {kind: n}, # 清单里有几件(按类别)
|
||||
"rendered": {kind: n}, # 实际给了几件
|
||||
"relations": {kind: n}, # 清单里有几条关系
|
||||
"rendered_relations": {kind: n}, # 实际给了几条
|
||||
"layers": [...], # 板子说它有哪几层
|
||||
"rendered_layers": [...], # 实际导出了哪几层
|
||||
}
|
||||
```
|
||||
|
||||
判"有没有东西没给我"只读这个:`checker.withheld_flag(obs)`。
|
||||
|
||||
## 三、迁移已经落地,而且标签逐样本没变
|
||||
|
||||
判据不是"看起来对",是**换掉之后每一条标签都不许动**。
|
||||
|
||||
* `checker.label` 里的 `withheld` 从
|
||||
`bool(dangling) or hidden["entity"] or hidden["edge"]` 改成读 `scope`。
|
||||
* `cli.check_scope_agrees()` 进 smoke:两种口径必须在每个样本上一致。
|
||||
实测 **1152 个样本(17 家族 × 64)全部一致**。
|
||||
* 标签整体摘要(17 家族 × 32,含 answer/change/sufficient/evidence)在改动前后
|
||||
两个 commit 上分别是
|
||||
`dc935840…cb6f83` 与 `dc935840…cb6f83` —— 完全相同。
|
||||
|
||||
也就是说:**弃权这条能力不需要完整状态了。** 需要完整状态的那部分,从标签路径上被
|
||||
摘掉了。
|
||||
|
||||
## 四、契约通过了:合规输入与泄漏输入打平
|
||||
|
||||
判决要分两步,第一步差点被骗。
|
||||
|
||||
**第一步:eval 时消融(错的方法)。** 把 `dangling` 在评估时清零,弃权从 0.996 掉到
|
||||
0.305;连隐藏计数一起清掉,掉到 0.000。看上去像"没有泄漏就不会弃权"。
|
||||
|
||||
但它测的是**必要性**,不是充分性:训练时 `dangling` 一直在,模型从没学过用别的通道,
|
||||
评估时抽掉它只是制造了分布外输入。更直接的证据是另一组数字——只清场景特征
|
||||
(`--ablate scene`)时,18 个家族 27 个格子**逐位不变**,只有置信度动了。泄漏通道在
|
||||
场时,模型根本没看场景那一片。
|
||||
|
||||
**第二步:训练时就不给(`data.availability`)。**
|
||||
|
||||
* `leaked` = 现状:`dangling` 边 + 隐藏计数进图;
|
||||
* `declared` = 合规:`dangling` 边不入图、隐藏计数那 16 维清零,只留 `scope` 四位。
|
||||
|
||||
同数据、同预算(12000 步)、三种子,19 个家族:
|
||||
|
||||
```
|
||||
family dec 泄露输入 合规输入
|
||||
area.near 128 1.00/1.00/1.00 1.00/1.00/1.00
|
||||
area.gap1 128 1.00/1.00/1.00 1.00/1.00/1.00
|
||||
area.gap4 128 1.00/1.00/1.00 1.00/1.00/1.00
|
||||
area.sup2h 0 a1.00/1.00/1.00 a1.00/1.00/1.00
|
||||
cond.p1h 34 1.00/1.00/1.00 1.00/1.00/1.00
|
||||
cond.p3h 84 1.00/1.00/1.00 1.00/1.00/1.00
|
||||
dof.c6 128 1.00/1.00/1.00 1.00/1.00/1.00
|
||||
dof.c6d 18 1.00/1.00/1.00 1.00/1.00/1.00
|
||||
dof.c6h 0 a1.00/1.00/0.99 a1.00/1.00/0.99
|
||||
dof.set 128 1.00/1.00/1.00 1.00/1.00/1.00
|
||||
acc 均值 1.000 / 1.000 abst 均值 0.999 / 0.999
|
||||
```
|
||||
|
||||
**合规输入与泄漏输入打平,一个格子都不差。** 弃权可以用不含端点的信号学到,M1 的
|
||||
弃权不是靠泄漏撑起来的。
|
||||
|
||||
### 这个结论是被一个更早的错误掩盖过的
|
||||
|
||||
7200 步时两组各有一个种子在自由度域塌掉(dof.set 0.46–0.54、dof.c6d 0.00,`#true 0`,
|
||||
即退化成"按家族答 false"),而且塌的种子不同:泄露是 s0、合规是 s1。看上去像"合规
|
||||
更弱",实际是**两个种子都还没逃出常量解**。
|
||||
|
||||
验证方式很直接:给塌掉的种子各续训 4800 步,两个都跳到 1.000。所以那不是能力缺失,
|
||||
是预算不够。两件事因此定下来:
|
||||
|
||||
1. 规范预算 12000 步。4800 / 7200 都会让某个种子卡住,而**卡住的种子看起来和"学不会"
|
||||
一模一样** —— 单次运行不构成证据这条纪律在这里又一次生效。
|
||||
2. 判据只看三种子最小值,不看均值。均值会把一个塌掉的种子摊薄成 0.96,看上去像
|
||||
"差不多好"。
|
||||
|
||||
### 近贴合进训练:外推错误消失了
|
||||
|
||||
在契约验收之前,`area.gap1/2/4` 是纯外推(不在任何 split 里),合规输入在 7200 步时
|
||||
seed1 对 1 格间隙答"true":**模型把"下面有个块"当成"支撑",和距离法犯的是同一个错。**
|
||||
|
||||
修法不是调参,是让这件事在族内可学:新家族 `area.near` 把间隙在族内抽 0 或 1–2
|
||||
(`rng.choice((0, 0, 0, 1, 2))`),于是同一个场景、同样的边数,只有"两张面重不重合"
|
||||
不同,标签两种都有(true 42% / false 58%,`baselines` 的 majority share 0.58)。
|
||||
|
||||
结果:`area.near` 三种子 1.000,而且**没训过的 gap1/2/4(间隙 1/2/4 格)也全部 1.000**。
|
||||
这不是记住,是把"接触"这个概念学会了——1 格和 4 格的几何签名完全一样(都是没接触),
|
||||
它没有靠记住某个具体距离。
|
||||
|
||||
## 五、和另一条线的关系
|
||||
|
||||
`docs/M2_INPUT_SOURCE.md` 说三类关系三种来源。那份文档管**三类关系分别从哪来**,
|
||||
这份管**"没给你的那部分"怎么表达**。两份合起来才是完整的输入契约:
|
||||
|
||||
```
|
||||
几何 ──→ contact(已实测 100%)
|
||||
元数据 ─→ conduct / constraint(待接 provider)
|
||||
清单声明 ─→ scope(缺口;标签路径与模型输入都已改为只读它)
|
||||
```
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,59 @@
|
||||
# 空间结构底座:模型架构与实施路线
|
||||
|
||||
设计提案,2026-12-03。第一目标是在 4080S 32GB 上验证共享表示的价值,第二目标是在单张 96GB 卡上扩大已通过验证的模型。本方案承接 [v3 需求](REQUIREMENTS.md) 的外部验证机制,更新了 v3 的程序文本主表示和电路优先路线。CAD、普通 3D 与 PCB 是迁移和验收的三个领域。
|
||||
|
||||
## 1. 核心任务
|
||||
|
||||
给定可见观测、局部编辑和一个查询,预测关系是否成立、编辑是否改变答案,以及哪些证据支持判断。相机移动、单位换算和对象重命名应保持结构查询的答案;删除连接是否有影响,取决于是否存在替代路径。模型还要识别观测不足的情况,给出能区分候选解释的测量或工具调用。精确几何、约束求解与物理数值计算交给工具。
|
||||
|
||||
| 领域 | 可观察的局部编辑 | 验证问题与边界 |
|
||||
|---|---|---|
|
||||
| CAD 装配 | 删除一个固定约束,保持零件位姿 | 从完整约束集检查剩余自由度;另一组约束可能已限制同一运动 |
|
||||
| 普通 3D | 移除一个支撑,或改变重力方向 | 接触可由几何检查;是否稳定还需要载荷、重心与支撑条件。条件不足时请求测量 |
|
||||
| PCB | 删除跨层过孔,保留投影相交的铜线 | 完整板文件可验证端口间是否仍有导通路径;仅凭顶视图可能无法分辨内层连线 |
|
||||
|
||||
## 2. 主干和数据契约
|
||||
|
||||
**观测编码器 → 实体、端口与局部关系 → 查询驱动的图 Transformer → 判断、证据与工具动作。** 数值事实保留原始精度,特征用于学习关系和选择证据。下面是待实现的模块契约。
|
||||
|
||||
| 模块 | 输入和输出 | 实现约束 |
|
||||
|---|---|---|
|
||||
| 观测适配器 | 图片经共享视觉编码器产生区域特征;结构化数据解析为实体、几何、显式约束和端口。支持单模态与混合输入 | RGB-D 用位姿与深度投影;有标定的单图保留射线及深度未知标记;无标定图保留视图局部关系。坐标变换未经确认时保留独立参考系 |
|
||||
| 实体与关系 | 观测事实携带对象引用、类型、坐标系、单位、时间、来源与可见性。候选边区分包含、邻接、接触、约束、导通,并记录已知或推断状态 | 视觉区域经可学习对象槽聚合;训练用可见实例匹配监督,推理按几何与特征关联,歧义保留候选。几何邻近与显式连接分别建边,长距离导线和装配约束必须保留。场景内对象 ID 仅作引用,训练时随机重编号 |
|
||||
| 共享主干 | 实体、端口及其关系进入双向图 Transformer;注意力使用边类型、相对位置及有效性掩码,查询 token 从场景中读取相关实体和路径 | 32GB 首轮候选配置为 6 层、宽度 384、6 头、最多 128 个实体或端口 token、两张 128px 视图。单独记录视觉与图主干参数量。超过预算的场景分桶或显式报超限,避免截断替代路径而改变标签 |
|
||||
| 输出与执行 | 读出头给出真/假/证据不足、编辑前后变化及证据引用。动作头选择直接回答、获取观测或调用注册工具,参数引用场景对象 | 工具适配器校验对象、单位和前置条件,返回数值、单位、来源或失败原因。回写后重评一次;首版每题最多一次调用,仍缺证据则保留未知 |
|
||||
|
||||
**例** 若查询是“移除过孔 V 后,A 与 B 仍导通吗”,正例的证据可以是任意一条剩余有效路径;负例可由完整连通图中的分量分离验证。图像未覆盖内层且可能存在替代路径时,提供隐藏层数据是合理动作。工具只有在实际拥有对应板文件时才能承诺完成查询。
|
||||
|
||||
## 3. 训练与验收
|
||||
|
||||
训练单位是同一结构及其编辑、视角和观测子集。数据生成器维护两份记录:模型可见的观测,以及仅供标注与打分的完整状态。隐藏层、编辑后求解结果、检查器答案和真值路径均不得进入模型输入。遮掉唯一证据时,用两份可见观测相同、完整答案相反的结构构造“证据不足”标签,避免把随机遮挡一律标为未知。
|
||||
|
||||
训练损失采用按有效标签数归一化的加权和,包含三值查询分类、编辑前后变化分类、证据指针和工具动作及参数。阶段一用结构化样本验证关系推理;阶段二混入图像与混合样本,加跨表示查询一致性损失,仅约束双方均可辨识的关系。任一侧证据不足时,变化标签也允许未知。编辑后只提供可观察的变化或明确的编辑指令。合法证据可能有多条,由验证器检查所选路径或局部证书;训练允许多解。权重、采样比例与查询范围由版本化配置指定。
|
||||
|
||||
对照组使用相同观测、几何属性、显式边、适配器和监督,只把关系主干替换为平面 token Transformer。主对照固定样本、顺序和更新次数,记录各自 GPU 秒;另按相同 GPU 时间截取学习曲线,检验效率。按基础拓扑族先切分,再生成视图、编辑和反事实;等价重编号与近重复结构归同组。阈值只在验证集选择。分别报告各领域、各输入类型和未见组合上的成绩:
|
||||
|
||||
- 编辑成对正确率要求编辑前后两次都答对;另报改变/保持两个子集以及证据经验证有效的比例。
|
||||
- 直答报告在固定错误率下的覆盖率,单列隐藏信息样本的过度自信率。允许弃答,报告分母和置信区间。
|
||||
- 工具贡献在同等成功率下比较 GPU 秒、调用次数和求解耗时,同时对照始终直答与能调用时始终调用工具。单列工具输入缺失、调用失败与单位错误。
|
||||
- 迁移测试冻结主干,在同等标签预算下训练新领域适配器和读出头,同时对照冻结的平面主干与从头训练。报告域外查询的学习曲线。
|
||||
|
||||
## 4. Roadmap 与决策门
|
||||
|
||||
| 阶段 | 交付 | 进入下一阶段的条件 |
|
||||
|---|---|---|
|
||||
| M0 · CPU | 统一场景 schema、程序化小场景生成器、参考检查器和固定夹具。首批夹具覆盖替代路径、隐藏连接、约束冗余、单位换算和相机变化 | 已知正反例与未知例逐条通过;同种子重建样本摘要一致;切分间结构族交集为空 |
|
||||
| M1 · 32GB | 在 PCB 连通和普通 3D 支撑两域训练平面基线及关系主干;按图像、结构、混合三路评测。CAD 保留作迁移域 | 先测峰值显存和样本吞吐;三个预先登记种子复跑。报告各种子成绩,对按种子平均的配对差值按拓扑族做 bootstrap;域外编辑成对正确率差值的 95% 区间下限大于零,同时检查各域是否退化 |
|
||||
| M2 · 32GB | 接入查询/测量工具并冻结主干迁移到 CAD 约束查询。复查工具返回与初判冲突的案例 | 固定标注预算下 CAD 迁移优于同预算基线;与始终调用工具相比,在预先登记的成功率容差内减少调用且总耗时下降。证据不足样本和各域退化超出预登记容差时停止扩容 |
|
||||
| M3 · 96GB | 先在新卡复验同一 checkpoint,再逐项增加实体数、遮挡、拓扑深度、真实观测和参数量。相邻任务先试适配器 | 与 32GB 模型用同一冻结评测集比较,每次只改变一个因素,报告新增能力、旧域保留率及每 GPU 小时的收益。若收益只来自更大工具预算,保留原主干 |
|
||||
|
||||
以上是设计门槛。M0 用开发集估算样本规模并登记有效差值、成功率容差、旧域退化容差与预算,然后锁定测试集;M1 结果用于定位空间对齐、关系辨识或路径推理中的瓶颈。
|
||||
|
||||
## 5. 工程边界、复现与产物
|
||||
|
||||
规划在一个 `spatial/` 包内分开 schema、观测适配器、模型、工具及训练评测入口;实验差异用配置表达。现有 `mm/model.py` 的 RMSNorm、SwiGLU 可复用;原有注意力显式使用因果掩码,关系主干需要双向注意力。`mm/train.py` 的扁平 token 加载、验证回退和仅保存权重的逻辑不满足这里的契约。
|
||||
|
||||
- **入口** 规划统一 CLI 提供 `smoke`、`train`、`resume` 和 `eval`。`smoke` 从固定种子流式造样,覆盖一次训练更新、断点恢复和评测;各入口共享 schema 校验,独立测试集缺失或工具执行异常时以明确状态返回。配置路径相对项目根目录解析。
|
||||
- **复现** 锁定依赖和工具版本;记录源代码提交、解析后的配置及摘要、数据/切分/生成器版本、种子、硬件和精度。按样本键派生随机种子,避免 worker 调度改变样本。断点原子替换,含权重、优化器、调度器、混合精度状态(若启用)、步数、采样游标及随机状态。用连续运行与中断恢复对照下一批样本键和损失;跨设备按预登记数值容差验收。
|
||||
- **限量产物** 默认按种子在线生成视图和编辑对;真实输入用只读清单定位。每个运行只保留一份清单、一份聚合指标、最近与最佳两个 checkpoint;诊断样例有显式数量上限。设置运行级字节预算并为原子写入预留空间,预算不足时停止写入并报错。临时文件限于本次运行自有目录,正常或可捕获异常退出时清理;中断遗留仅在恢复时按本次清单核对处理。
|
||||
- **版本控制** 源码、配置、依赖锁和小型确定性夹具入库;运行目录放在已有忽略规则覆盖的 `out_spatial/`。权重、渲染帧、逐样本预测和缓存留在运行目录。提交前按文件白名单检查差异和新增文件大小。清理范围限定本次运行,保留用户已有数据与实验。
|
||||
@@ -0,0 +1,19 @@
|
||||
# mm —— 45M 原生多模态 GPT(暂停的一条线)
|
||||
|
||||
文本 BPE 与图像 VQ 码共享一个词表和 softmax,多流残差、GQA、bigram 哈希表、Muon。
|
||||
这一条线得出的结论(可用标注质量门槛、样本/属性值是学习瓶颈、验证损失与学习反相关)
|
||||
仍然成立,但路线已被 `docs/SPATIAL_FOUNDATION.md` 取代,代码保留以便复现。
|
||||
|
||||
文件按前缀分组,**保持平铺**:这些脚本以 `mm/` 为工作目录互相 `import model`,
|
||||
移动目录会打断相对导入,收益不值这个风险。
|
||||
|
||||
| 前缀 | 内容 |
|
||||
|---|---|
|
||||
| `model.py` `train.py` `muon.py` `smoke.py` | 主干:模型、训练循环、优化器、冒烟 |
|
||||
| `build_*` `split.py` `recaption.py` `caption_all.py` `retok_*` | 数据构建与重标注(strata 批量改写 caption) |
|
||||
| `probe_*` `*_eval.py` `stream_probe.py` `chk.py` `modecheck.py` `vqres.py` `test_vq.py` | 行为探针:反事实换词、交叉积、位置分桶、流耦合 |
|
||||
| `train_report.py` | 四层体检一次出(规模/曲线/留存/TV/行为/结论) |
|
||||
| `bench_strata.py` `compare_gen.py` `curve.py` `distcheck.py` `sample.py` `generate.py` | 基准、采样与画图 |
|
||||
| `run_arm?*.sh` | 实验编排(A–F 六组) |
|
||||
|
||||
文档已移出到 `docs/`。
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Spatial-structure foundation.
|
||||
|
||||
A slice of the plan in ``docs/SPATIAL_FOUNDATION.md``: one observation contract,
|
||||
one procedural generator, one reference checker, one bidirectional backbone,
|
||||
and a CLI that can smoke / train / resume / eval.
|
||||
|
||||
M0 is CPU-only on purpose -- the point is that the labels are provably right
|
||||
before any GPU time is spent learning them.
|
||||
"""
|
||||
|
||||
__all__ = ["schema", "generator", "checker", "model", "train", "cli"]
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Trivial baselines, per family.
|
||||
|
||||
A model is only interesting relative to the cheapest rule that fits the training
|
||||
set. The plan already says a model that answers "true" everywhere would look
|
||||
fine on accuracy alone; the same is true of any one-bit rule, and if such a rule
|
||||
fits every training family perfectly then accuracy on those families measures
|
||||
nothing at all.
|
||||
|
||||
Two numbers per family:
|
||||
|
||||
* ``acc_all`` -- accuracy if the rule answers every row
|
||||
* ``acc_dec`` -- accuracy restricted to rows whose observation decides the
|
||||
answer, i.e. the same denominator the model's ``acc`` uses
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from collections import Counter
|
||||
|
||||
from . import generator
|
||||
|
||||
ANSWERS = ("true", "false", "unknown")
|
||||
|
||||
|
||||
def _rule(name: str, sc) -> str:
|
||||
if name == "agree": # the label itself: ceiling for any rule
|
||||
return sc.label.answer
|
||||
if name == "true":
|
||||
return "true"
|
||||
if name == "false":
|
||||
return "false"
|
||||
if name == "unknown":
|
||||
return "unknown"
|
||||
if name == "edit": # one bit: an intervention happened -> false
|
||||
return "false" if sc.query.edit else "true"
|
||||
raise ValueError(name)
|
||||
|
||||
|
||||
def score(family: str, rule: str, seed: int, n: int) -> dict:
|
||||
rows = [generator.make(family, seed=seed, index=i) for i in range(n)]
|
||||
all_hit = dec_hit = dec = 0
|
||||
for sc in rows:
|
||||
pred = _rule(rule, sc)
|
||||
all_hit += int(pred == sc.label.answer)
|
||||
if sc.label.answer != "unknown":
|
||||
dec += 1
|
||||
dec_hit += int(pred == sc.label.answer)
|
||||
maj = Counter(sc.label.answer for sc in rows).most_common(1)[0]
|
||||
return {"n": n, "acc_all": all_hit / n, "dec": dec,
|
||||
"acc_dec": dec_hit / max(1, dec), "majority": maj[0], "maj_share": maj[1] / n}
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
argv = argv or sys.argv[1:]
|
||||
n = int(argv[0]) if argv else 128
|
||||
seed = 0
|
||||
rules = ("true", "false", "unknown", "edit")
|
||||
head = f"{'family':11s} {'n':>4s} {'dec':>4s} {'maj':>8s} {'share':>5s} " + \
|
||||
" ".join(f"{r:>7s}" for r in rules)
|
||||
print(head)
|
||||
print("-" * len(head))
|
||||
for fam in generator.FAMILIES:
|
||||
cells = [score(fam, r, seed, n) for r in rules]
|
||||
s = cells[0]
|
||||
print(f"{fam:11s} {s['n']:4d} {s['dec']:4d} {s['majority']:>8s} {s['maj_share']:5.2f} " +
|
||||
" ".join(f"{c['acc_dec']:7.3f}" for c in cells))
|
||||
print(f"\nacc_dec = accuracy on rows the observation can decide (seed {seed}, n {n})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,397 @@
|
||||
"""Reference checker.
|
||||
|
||||
The generator only builds structure; every label is produced here from the full
|
||||
state, then downgraded to ``unknown`` whenever the observation admits a
|
||||
different answer. That downgrade rule is what makes "evidence insufficient" a
|
||||
real label instead of a random occlusion tag:
|
||||
|
||||
answers = {answer(full), answer(full restricted to the observation)}
|
||||
if len(answers) != 1 -> unknown
|
||||
|
||||
Restricting the full state to what is visible is the cheapest way to build the
|
||||
"same observation, opposite truth" pair that the plan asks for, and it needs no
|
||||
special case per domain.
|
||||
|
||||
Nothing here imports the model, so a disagreement between the two is real.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict, deque
|
||||
from typing import Iterable, Optional
|
||||
|
||||
from .schema import (DOF_AXES, Edge, Entity, FullState, Label, Observation,
|
||||
Query)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# query edits
|
||||
|
||||
|
||||
def _removed_edge(query: Query) -> Optional[str]:
|
||||
if query.edit and query.edit.get("op") == "remove_edge":
|
||||
return query.edit.get("edge")
|
||||
return None
|
||||
|
||||
|
||||
def _removed_entity(query: Query) -> Optional[str]:
|
||||
if query.edit and query.edit.get("op") == "remove_entity":
|
||||
return query.edit.get("entity")
|
||||
return None
|
||||
|
||||
|
||||
def _alive_edges(edges: Iterable[Edge], query: Query) -> list:
|
||||
drop = _removed_edge(query)
|
||||
return [e for e in edges if e.eid != drop]
|
||||
|
||||
|
||||
def _alive_entities(entities: Iterable[Entity], query: Query) -> list:
|
||||
drop = _removed_entity(query)
|
||||
return [e for e in entities if e.eid != drop]
|
||||
|
||||
|
||||
def _index(entities: Iterable[Entity]) -> dict:
|
||||
return {e.eid: e for e in entities}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# connection
|
||||
|
||||
|
||||
def conduct_path(edges: Iterable[Edge], src: str, dst: str) -> Optional[list]:
|
||||
adj = defaultdict(list)
|
||||
for e in edges:
|
||||
if e.kind != "conduct":
|
||||
continue
|
||||
adj[e.a].append((e.b, e.eid))
|
||||
adj[e.b].append((e.a, e.eid))
|
||||
if src == dst:
|
||||
return []
|
||||
prev = {src: (None, None)}
|
||||
q = deque([src])
|
||||
while q:
|
||||
u = q.popleft()
|
||||
for v, eid in adj[u]:
|
||||
if v in prev:
|
||||
continue
|
||||
prev[v] = (u, eid)
|
||||
if v == dst:
|
||||
path = []
|
||||
while v != src:
|
||||
v, pe = prev[v]
|
||||
path.append(pe)
|
||||
return list(reversed(path))
|
||||
q.append(v)
|
||||
return None
|
||||
|
||||
|
||||
def _connection_answer(entities, edges, query: Query) -> Optional[bool]:
|
||||
idx = _index(_alive_entities(entities, query))
|
||||
if query.a not in idx or query.b not in idx:
|
||||
return None
|
||||
return conduct_path(_alive_edges(edges, query), query.a, query.b) is not None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# stability
|
||||
|
||||
|
||||
def _box(e: Entity):
|
||||
b = e.attrs.get("box")
|
||||
return tuple(b) if b else None
|
||||
|
||||
|
||||
def _overlap(a, b):
|
||||
ox0, oy0 = max(a[0], b[0]), max(a[1], b[1])
|
||||
ox1, oy1 = min(a[3], b[3]), min(a[4], b[4])
|
||||
if ox0 >= ox1 or oy0 >= oy1:
|
||||
return None
|
||||
return (ox0, oy0, ox1, oy1)
|
||||
|
||||
|
||||
def stable_blocks(entities) -> dict:
|
||||
"""{block eid: supporter eid or "ground"} for blocks that stand."""
|
||||
blocks = [e for e in entities if e.kind == "block" and _box(e)]
|
||||
support, stable = {}, set()
|
||||
changed = True
|
||||
while changed:
|
||||
changed = False
|
||||
for b in blocks:
|
||||
if b.eid in stable:
|
||||
continue
|
||||
x0, y0, z0, x1, y1, _ = _box(b)
|
||||
if z0 == 0:
|
||||
stable.add(b.eid)
|
||||
support[b.eid] = "ground"
|
||||
changed = True
|
||||
continue
|
||||
cx2, cy2 = x0 + x1, y0 + y1 # twice the centroid: stays integer
|
||||
for s in blocks:
|
||||
if s.eid == b.eid or s.eid not in stable:
|
||||
continue
|
||||
sx0, sy0, _, sx1, sy1, sz1 = _box(s)
|
||||
if sz1 != z0:
|
||||
continue
|
||||
ov = _overlap(_box(b), _box(s))
|
||||
if ov is None:
|
||||
continue
|
||||
if 2 * ov[0] <= cx2 <= 2 * ov[2] and 2 * ov[1] <= cy2 <= 2 * ov[3]:
|
||||
stable.add(b.eid)
|
||||
support[b.eid] = s.eid
|
||||
changed = True
|
||||
break
|
||||
return support
|
||||
|
||||
|
||||
def _stability_answer(entities, edges, query: Query) -> Optional[bool]:
|
||||
alive = _alive_entities(entities, query)
|
||||
part = _index(alive).get(query.a)
|
||||
if part is None or part.kind != "block":
|
||||
return None
|
||||
return query.a in stable_blocks(alive)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# freedom
|
||||
|
||||
|
||||
def _freedom_answer(entities, edges, query: Query) -> Optional[bool]:
|
||||
idx = _index(_alive_entities(entities, query))
|
||||
part = idx.get(query.a)
|
||||
if part is None or part.kind != "part":
|
||||
return None
|
||||
covered = {e.attrs.get("axis") for e in _alive_edges(edges, query) if e.kind == "constraint"}
|
||||
return len(covered & set(DOF_AXES)) == len(DOF_AXES)
|
||||
|
||||
|
||||
_ANSWER_FN = {
|
||||
"connection": _connection_answer,
|
||||
"stability": _stability_answer,
|
||||
"freedom": _freedom_answer,
|
||||
}
|
||||
|
||||
|
||||
def evaluate(entities, edges, query: Query) -> Optional[bool]:
|
||||
fn = _ANSWER_FN.get(query.kind)
|
||||
if fn is None:
|
||||
raise ValueError(f"unknown query kind {query.kind!r}")
|
||||
return fn(list(entities), list(edges), query)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# certificates
|
||||
|
||||
|
||||
def evidence_for(full: FullState, query: Query) -> list:
|
||||
"""One certificate, as edge ids. Several may be valid; the checker accepts
|
||||
any that validates."""
|
||||
edges = _alive_edges(full.edges, query)
|
||||
ents = _alive_entities(full.entities, query)
|
||||
if query.kind == "connection":
|
||||
return conduct_path(edges, query.a, query.b) or []
|
||||
if query.kind == "freedom":
|
||||
picked, seen = [], set()
|
||||
for e in edges:
|
||||
if e.kind != "constraint":
|
||||
continue
|
||||
ax = e.attrs.get("axis")
|
||||
if ax in DOF_AXES and ax not in seen:
|
||||
seen.add(ax)
|
||||
picked.append(e.eid)
|
||||
return picked if len(seen) == len(DOF_AXES) else []
|
||||
if query.kind == "stability":
|
||||
support = stable_blocks(ents)
|
||||
if query.a not in support:
|
||||
return []
|
||||
chain, cur = [], query.a
|
||||
while support.get(cur) not in (None, "ground"):
|
||||
nxt = support[cur]
|
||||
edge = next((e for e in edges if e.kind == "contact"
|
||||
and {e.a, e.b} == {cur, nxt}), None)
|
||||
if edge is None:
|
||||
break
|
||||
chain.append(edge.eid)
|
||||
cur = nxt
|
||||
return chain
|
||||
return []
|
||||
|
||||
|
||||
def _contact_is_real(ents: dict, e: Edge) -> bool:
|
||||
"""Re-derive a contact from the boxes instead of trusting the edge label.
|
||||
|
||||
A certificate is only worth something if the thing it cites can be checked
|
||||
independently. Until this existed, `validate_evidence` walked the claimed
|
||||
chain and stopped as soon as it reached anything sitting on the ground -- so
|
||||
a provider that emitted one bogus contact edge could forge support that
|
||||
validated. Measured: with a distance tolerance of one grid unit (0.25mm)
|
||||
every part pair separated by 0.25mm produced an edge that passed.
|
||||
"""
|
||||
a, b = ents.get(e.a), ents.get(e.b)
|
||||
if a is None or b is None:
|
||||
return False
|
||||
ba, bb = _box(a), _box(b)
|
||||
if ba and bb:
|
||||
if not (ba[5] == bb[2] or bb[5] == ba[2]):
|
||||
return False # faces do not meet: no load path
|
||||
return _overlap(ba, bb) is not None # and they must share a footprint
|
||||
box, other = (ba, b) if ba else (bb, a)
|
||||
if box is None or other.kind != "ground":
|
||||
return False
|
||||
return box[2] == float(other.attrs.get("plane", 0))
|
||||
|
||||
|
||||
def validate_evidence(full: FullState, query: Query, evidence,
|
||||
conflicts=()) -> bool:
|
||||
"""Independent re-check of a claimed certificate.
|
||||
|
||||
A certificate may not cite a relation two sources disagree on: the whole
|
||||
point of the dispute is that nobody has established that relation, so it
|
||||
cannot carry a proof. Same principle as ``_contact_is_real`` refusing a
|
||||
contact the geometry does not show.
|
||||
"""
|
||||
evidence = list(evidence or [])
|
||||
if not evidence or _removed_edge(query) in evidence:
|
||||
return False
|
||||
by_id = {e.eid: e for e in full.edges}
|
||||
if any(eid not in by_id for eid in evidence):
|
||||
return False
|
||||
edges = [by_id[eid] for eid in evidence]
|
||||
if conflicts:
|
||||
named = {(c.get("kind"), frozenset((c.get("a"), c.get("b")))) for c in conflicts}
|
||||
if any((e.kind, frozenset((e.a, e.b))) in named for e in edges):
|
||||
return False
|
||||
if query.kind == "connection":
|
||||
return conduct_path(edges, query.a, query.b) is not None
|
||||
if query.kind == "freedom":
|
||||
covered = {e.attrs.get("axis") for e in edges if e.kind == "constraint"}
|
||||
return len(covered & set(DOF_AXES)) == len(DOF_AXES)
|
||||
if query.kind == "stability":
|
||||
if any(e.kind != "contact" for e in edges):
|
||||
return False
|
||||
ents = _index(full.entities)
|
||||
if query.a not in ents:
|
||||
return False
|
||||
# every cited step has to be a contact that the geometry actually shows
|
||||
if not all(_contact_is_real(ents, e) for e in edges):
|
||||
return False
|
||||
reached = {query.a}
|
||||
for _ in range(len(edges) + 1):
|
||||
for e in edges:
|
||||
if e.a in reached:
|
||||
reached.add(e.b)
|
||||
elif e.b in reached:
|
||||
reached.add(e.a)
|
||||
return any(eid in ents and ents[eid].kind == "ground" for eid in reached) or \
|
||||
any(eid in ents and _box(ents[eid]) is not None and _box(ents[eid])[2] == 0
|
||||
for eid in reached)
|
||||
return False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# label
|
||||
|
||||
|
||||
def hostile(obs, edge) -> bool:
|
||||
"""Is this relation disputed between two sources."""
|
||||
key = frozenset((edge.a, edge.b))
|
||||
return any(c.get("kind") == edge.kind and frozenset((c.get("a"), c.get("b"))) == key
|
||||
for c in (obs.conflicts or []))
|
||||
|
||||
|
||||
def withheld_flag(obs) -> bool:
|
||||
"""Is the inventory bigger than what was handed over.
|
||||
|
||||
Read from ``obs.scope`` only -- counts of parts and relations, and the layer
|
||||
stack. It deliberately does **not** consult ``hidden`` or ``dangling``:
|
||||
those are computed as "full state minus visible", and no real provider can
|
||||
compute them, because knowing that a relation exists with one end off-screen
|
||||
requires seeing both ends.
|
||||
|
||||
What a provider can say is that its inventory is bigger: a BOM lists five
|
||||
parts and three were rendered; a netlist has nine conductors on two layers
|
||||
and one layer was exported. That statement carries no endpoints, so it
|
||||
cannot decide the answer -- only suspend it.
|
||||
"""
|
||||
scope = obs.scope or {}
|
||||
parts = scope.get("parts") or {}
|
||||
rendered = scope.get("rendered") or {}
|
||||
if any(parts.get(k, 0) > rendered.get(k, 0) for k in parts):
|
||||
return True
|
||||
rel = scope.get("relations") or {}
|
||||
rel_r = scope.get("rendered_relations") or {}
|
||||
if any(rel.get(k, 0) > rel_r.get(k, 0) for k in rel):
|
||||
return True
|
||||
if scope.get("conflicts"):
|
||||
return True
|
||||
return bool(set(scope.get("layers") or []) - set(scope.get("rendered_layers") or []))
|
||||
|
||||
|
||||
def label(obs: Observation, full: FullState, query: Query,
|
||||
alternatives: Iterable[FullState] = ()) -> Label:
|
||||
"""Full state decides; the observation decides whether we may say so.
|
||||
|
||||
When something is withheld the rule is *monotone*: a hidden conduct edge can
|
||||
only connect, a hidden contact can only support, a hidden mate can only lock
|
||||
an axis. None of them can undo a proof the observation already contains. So
|
||||
|
||||
* the visible structure already proves the answer -> decidable "true";
|
||||
* it does not -> the withheld item could be exactly the missing piece, and
|
||||
the answer is unknown, however the one full state we happen to hold
|
||||
resolves it.
|
||||
|
||||
The cheaper rule -- compare the full state against the observation's own
|
||||
world -- marks "the pedestal is behind the part and in this particular scene
|
||||
it would not have helped" as decidable false. That is not a fact the agent
|
||||
can know: another equally consistent world puts the pedestal under the
|
||||
centroid and the answer flips. Measured: area.sup2h came out 36 decidable /
|
||||
92 not, and the model swung between answering all of them and abstaining
|
||||
from all of them, because the split is not in the observation.
|
||||
"""
|
||||
ans_full = evaluate(full.entities, full.edges, query)
|
||||
alt = list(alternatives)
|
||||
ans_vis = evaluate(alt[0].entities, alt[0].edges, query) if alt else ans_full
|
||||
withheld = withheld_flag(obs)
|
||||
|
||||
conflicts = list(obs.conflicts or [])
|
||||
if conflicts or withheld:
|
||||
# Two sources naming the same relation and disagreeing is not the same
|
||||
# kind of ignorance as "nobody told me". A disputed relation can be
|
||||
# present or absent, both consistent with everything we were told, so the
|
||||
# honest answer is whatever holds in *both* worlds -- and nothing else.
|
||||
#
|
||||
# That is sharper than the withheld rule, which cannot enumerate the
|
||||
# missing content and so must answer "unknown" as soon as the visible
|
||||
# structure fails to prove. Here the disputed item is named, so "false in
|
||||
# both worlds" is a legitimate false rather than an abstention.
|
||||
sure = alt[0] if alt else full
|
||||
if conflicts:
|
||||
disputed = {(c.get("kind"), frozenset((c.get("a"), c.get("b"))))
|
||||
for c in conflicts}
|
||||
kept = [e for e in sure.edges if (e.kind, frozenset((e.a, e.b))) not in disputed]
|
||||
sure = FullState(entities=list(sure.entities), edges=kept)
|
||||
ans_sure = evaluate(sure.entities, sure.edges, query)
|
||||
if ans_sure is True:
|
||||
# this proof never touches a disputed relation, so it stands
|
||||
return Label(answer="true", change=_change(full, query, True),
|
||||
evidence=evidence_for(sure, query), sufficient=True)
|
||||
if not withheld and ans_vis is False:
|
||||
# the answer is false whether the disputed relation exists or not
|
||||
return Label(answer="false", change=_change(full, query, False),
|
||||
evidence=[], sufficient=True)
|
||||
return Label(answer="unknown", change="unknown", evidence=[], sufficient=False)
|
||||
|
||||
if ans_full is None or ans_vis is None or ans_full != ans_vis:
|
||||
return Label(answer="unknown", change="unknown", evidence=[], sufficient=False)
|
||||
|
||||
return Label(answer="true" if ans_full else "false",
|
||||
change=_change(full, query, ans_full),
|
||||
evidence=evidence_for(full, query), sufficient=True)
|
||||
|
||||
|
||||
def _change(full: FullState, query: Query, ans_after) -> str:
|
||||
if query.edit is None:
|
||||
return "same"
|
||||
before = Query(kind=query.kind, a=query.a, b=query.b, edit=None)
|
||||
ans_before = evaluate(full.entities, full.edges, before)
|
||||
if ans_before is None:
|
||||
return "unknown"
|
||||
return "changed" if ans_before != ans_after else "same"
|
||||
+372
@@ -0,0 +1,372 @@
|
||||
"""Unified entry point: smoke / train / resume / eval.
|
||||
|
||||
``smoke`` is the M0 gate. It does not care about accuracy; it cares that the
|
||||
contract holds -- labels provably right, same seed rebuilds the same scene, the
|
||||
insufficient-evidence pair really is indistinguishable, units and camera do not
|
||||
move the answer, and a checkpoint survives an interruption.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from . import checker, generator
|
||||
from .schema import FullState, Query
|
||||
|
||||
|
||||
def _load_config(path: str) -> dict:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
# configs live in spatial/configs, so the run root is the package's parent
|
||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
cfg["out_dir"] = os.path.join(root, cfg.get("out_dir", "out_spatial/smoke"))
|
||||
return cfg
|
||||
|
||||
|
||||
def _fail(msg: str):
|
||||
print(f"FAIL {msg}")
|
||||
return False
|
||||
|
||||
|
||||
def check_splits(cfg) -> bool:
|
||||
d = cfg["data"]
|
||||
tr, va, te = set(d["train_families"]), set(d["val_families"]), set(d["test_families"])
|
||||
known = set(generator.FAMILIES)
|
||||
if not (tr | va | te) <= known:
|
||||
return _fail(f"unknown families: {(tr | va | te) - known}")
|
||||
if tr & va or tr & te or va & te:
|
||||
return _fail(f"split families overlap: {sorted(tr & va)} {sorted(tr & te)} {sorted(va & te)}")
|
||||
if tr | va | te != known:
|
||||
missing = known - (tr | va | te)
|
||||
print(f"note families not used by any split: {sorted(missing)}")
|
||||
print(f"ok splits disjoint over families: {len(tr)}/{len(va)}/{len(te)}")
|
||||
return True
|
||||
|
||||
|
||||
def check_determinism() -> bool:
|
||||
ok = True
|
||||
for fam in generator.FAMILIES:
|
||||
a = generator.make(fam, seed=11, index=3)
|
||||
b = generator.make(fam, seed=11, index=3)
|
||||
if a.full_digest() != b.full_digest():
|
||||
ok = _fail(f"{fam} not reproducible from the same seed")
|
||||
if ok:
|
||||
print("ok same seed rebuilds an identical scene (10 families)")
|
||||
return ok
|
||||
|
||||
|
||||
def check_labels() -> bool:
|
||||
"""Every sufficient positive label must carry a certificate the checker
|
||||
accepts, and every sufficient label must agree with a rerun on the full
|
||||
state alone."""
|
||||
bad = 0
|
||||
n = 0
|
||||
for fam in generator.FAMILIES:
|
||||
for i in range(6):
|
||||
sc = generator.make(fam, seed=23, index=i)
|
||||
n += 1
|
||||
if sc.label.sufficient:
|
||||
ans = checker.evaluate(sc.full.entities, sc.full.edges, sc.query)
|
||||
if (ans is True) != (sc.label.answer == "true"):
|
||||
bad += 1
|
||||
print(f" {fam}[{i}] label {sc.label.answer} vs checker {ans}")
|
||||
if sc.label.answer == "true" and not checker.validate_evidence(
|
||||
sc.full, sc.query, sc.label.evidence):
|
||||
bad += 1
|
||||
print(f" {fam}[{i}] certificate rejected: {sc.label.evidence}")
|
||||
if bad:
|
||||
return _fail(f"{bad} label/certificate mismatches over {n} samples")
|
||||
print(f"ok {n} labels agree with the full-state checker, certificates validate")
|
||||
return True
|
||||
|
||||
|
||||
def check_insufficient() -> bool:
|
||||
"""The point of the unknown label: the observation does not settle it.
|
||||
|
||||
Under the monotone rule an unknown label no longer implies that *the one full
|
||||
state we hold* answers differently from the observation's own world -- it
|
||||
implies that the withheld content could be the missing piece. So the check is
|
||||
that something is withheld and the visible structure does not already prove
|
||||
the answer, which is exactly the condition the label promises.
|
||||
"""
|
||||
found = 0
|
||||
for fam in generator.FAMILIES:
|
||||
for i in range(8):
|
||||
sc = generator.make(fam, seed=5, index=i)
|
||||
if sc.label.answer != "unknown":
|
||||
continue
|
||||
# "visible proves it" must mean *undisputed* visible structure: a
|
||||
# relation two sources disagree on cannot carry a proof, so it is
|
||||
# excluded here exactly as the label rule excludes it.
|
||||
disputed = {(c.get("kind"), frozenset((c.get("a"), c.get("b"))))
|
||||
for c in (sc.obs.conflicts or [])}
|
||||
kept = [e for e in sc.obs.edges
|
||||
if (e.kind, frozenset((e.a, e.b))) not in disputed]
|
||||
a_vis = checker.evaluate(list(sc.obs.entities), kept, sc.query)
|
||||
withheld = checker.withheld_flag(sc.obs)
|
||||
if withheld and a_vis is not True:
|
||||
found += 1
|
||||
else:
|
||||
return _fail(f"{fam}[{i}] unknown without withheld content or with a "
|
||||
f"visible proof; label is not justified")
|
||||
if found == 0:
|
||||
return _fail("no insufficient-evidence sample was produced")
|
||||
print(f"ok {found} unknown samples are undecided by the observation "
|
||||
f"(undisputed part)")
|
||||
return True
|
||||
|
||||
|
||||
def check_invariances() -> bool:
|
||||
bad = 0
|
||||
for fam in generator.FAMILIES:
|
||||
sc = generator.make(fam, seed=31, index=1)
|
||||
scaled = generator.rescale(sc, 10, "0.1mm")
|
||||
if scaled.label.answer != sc.label.answer:
|
||||
bad += 1
|
||||
print(f" {fam} unit change moved the answer")
|
||||
cam = generator.with_camera(sc, "iso")
|
||||
if cam.label.answer != sc.label.answer:
|
||||
bad += 1
|
||||
print(f" {fam} camera change moved the answer")
|
||||
if bad:
|
||||
return _fail(f"{bad} invariance violations")
|
||||
print("ok answer invariant to unit scaling and camera relabel")
|
||||
return True
|
||||
|
||||
|
||||
def check_cross_family_digest() -> bool:
|
||||
"""Two samples with the same ``input_digest`` must carry the same label.
|
||||
|
||||
This is the whole contract, and it has to hold *across* families, not only
|
||||
inside one: "no hidden branch exists" and "a hidden branch exists but is not
|
||||
visible" produce the same observation, so a label that says "decidable" in
|
||||
the first case and "unknown" in the second is a label the model can never
|
||||
reproduce -- absence of evidence is not evidence of absence. Samples whose
|
||||
scores differ are still a bug, just a quieter one.
|
||||
"""
|
||||
seen = {}
|
||||
bad = []
|
||||
n = 0
|
||||
for fam in generator.FAMILIES:
|
||||
for i in range(40):
|
||||
sc = generator.make(fam, seed=71, index=i)
|
||||
n += 1
|
||||
d = sc.input_digest()
|
||||
prev = seen.get(d)
|
||||
if prev is None:
|
||||
seen[d] = (fam, sc.label.answer, sc.label.change)
|
||||
elif (prev[1], prev[2]) != (sc.label.answer, sc.label.change):
|
||||
bad.append((prev, (fam, sc.label.answer, sc.label.change)))
|
||||
if bad:
|
||||
# collapse to the distinct family pairs, the list itself is long
|
||||
pairs = sorted({(a[0], b[0]) for a, b in bad})
|
||||
print(f" {len(bad)} samples share an input digest with a different label")
|
||||
for a, b in pairs[:6]:
|
||||
print(f" {a:11s} vs {b:11s}")
|
||||
return _fail("same input, different label -- the observation does not "
|
||||
"determine the answer, so both cannot be decidable")
|
||||
print(f"ok {n} samples: no two families assign different labels to "
|
||||
f"the same observation ({len(seen)} distinct inputs)")
|
||||
return True
|
||||
|
||||
|
||||
def check_extract_contacts(n: int = 8) -> bool:
|
||||
"""The geometry provider must not invent a contact across a clearance.
|
||||
|
||||
``area.gap1/2/4`` place the same block 1, 2 and 4 units above its pedestal.
|
||||
Contact is decided by coincident faces, not by distance, so at a numerical
|
||||
epsilon the extractor has to report no T-P edge there -- and still report
|
||||
the two contacts that are real. This is the regression gate for the
|
||||
parameter that used to decide the answer by itself.
|
||||
"""
|
||||
from . import extract
|
||||
bad = set()
|
||||
for fam in ("area.gap1", "area.gap2", "area.gap4"):
|
||||
for i in range(n):
|
||||
sc = generator.make(fam, seed=0, index=i)
|
||||
if any({e.a, e.b} == {"T", "P"}
|
||||
for e in extract.extract_edges(sc.obs.entities, eps=1e-9)):
|
||||
bad.add(fam)
|
||||
break
|
||||
if bad:
|
||||
return _fail(f"extractor welded T to P across a clearance: {sorted(bad)}")
|
||||
got = len(extract.extract_edges(
|
||||
generator.make("area.sup2", seed=0, index=0).obs.entities, eps=1e-9))
|
||||
if got != 3:
|
||||
return _fail(f"area.sup2: extractor found {got} contacts, expected 3")
|
||||
print("ok extractor: nothing welded across a clearance, 3/3 real contacts kept")
|
||||
return True
|
||||
|
||||
|
||||
def check_scope_agrees(n: int = 24) -> bool:
|
||||
"""The declared inventory must say "something withheld" exactly when the
|
||||
diagnostic one does.
|
||||
|
||||
``hidden``/``dangling`` are computed from the full state, so they are not
|
||||
something a provider can produce. ``scope`` is. This check pins the
|
||||
migration: wherever the two disagree, the label path would have to fall back
|
||||
on full-state data -- and that is the leak M2 exists to remove.
|
||||
"""
|
||||
bad = []
|
||||
rows = 0
|
||||
for fam in generator.FAMILIES:
|
||||
for i in range(n):
|
||||
sc = generator.make(fam, seed=11, index=i)
|
||||
old = bool(sc.obs.dangling) or bool((sc.obs.hidden or {}).get("entity")) or bool((sc.obs.hidden or {}).get("edge"))
|
||||
new = checker.withheld_flag(sc.obs)
|
||||
rows += 1
|
||||
# conflicts are a second, independent reason to suspend: they are
|
||||
# declared by the sources, not derived from the full state, so they
|
||||
# have no diagnostic analogue. Two ways to be wrong, both checked:
|
||||
# a withheld fact the scope cannot express, or a declared conflict
|
||||
# the scope forgot to count.
|
||||
# scope must equal the diagnostic *plus* the declared conflicts: the
|
||||
# full state has no way to know that two sources disagree, so the
|
||||
# union is what "something is not settled" should mean.
|
||||
declared = bool(sc.obs.conflicts)
|
||||
forgot = declared and not (sc.obs.scope or {}).get("conflicts")
|
||||
if new != (old or declared) or forgot:
|
||||
bad.append((fam, i, old, new))
|
||||
if bad:
|
||||
fams = sorted({f for f, _, _, _ in bad})
|
||||
print(f" {len(bad)}/{rows} samples disagree, families {fams}")
|
||||
for f, i, o, nn in bad[:4]:
|
||||
print(f" {f}[{i}] diagnostic={o} scope={nn}")
|
||||
return _fail("scope cannot express what was withheld, or a conflict went "
|
||||
"undeclared")
|
||||
print(f"ok {rows} samples: declared inventory agrees with the diagnostic one")
|
||||
return True
|
||||
|
||||
|
||||
def check_netlist_provider() -> bool:
|
||||
"""The netlist provider must reproduce membership, and must not over-claim.
|
||||
|
||||
Built from the same membership it is checked against, so "the edges are
|
||||
right" is a construction. What this pins is the mapping's *shape*: one
|
||||
entity per (ref, pin), pairwise conduct inside a net, nothing invented
|
||||
across nets, and a single-node net that stays isolated instead of being
|
||||
silently promoted to "connected to something".
|
||||
"""
|
||||
from .providers import kicad_netlist
|
||||
path = os.path.join(os.path.dirname(__file__), "providers", "fixtures", "tiny.net")
|
||||
nl = kicad_netlist.load(path)
|
||||
obs = kicad_netlist.to_observation(nl)
|
||||
want = {"comp": 3, "node": 6, "net": 3, "edge": 4}
|
||||
got = {"comp": len(nl.comps), "node": len(nl.nodes()), "net": len(nl.nets),
|
||||
"edge": len(obs.edges)}
|
||||
if got != want:
|
||||
return _fail(f"netlist mapping changed: {got} != {want}")
|
||||
if checker.withheld_flag(obs):
|
||||
return _fail("a complete netlist reported itself as incomplete")
|
||||
pairs = [("R1.2", "U1.1", True), # same net
|
||||
("R1.1", "R1.2", False), # same part, different nets
|
||||
("U1.7", "R1.2", False)] # single-node net: connected to nothing
|
||||
for a, b, want_ans in pairs:
|
||||
got_ans = checker.evaluate(obs.entities, obs.edges,
|
||||
Query(kind="connection", a=a, b=b))
|
||||
if got_ans is not want_ans:
|
||||
return _fail(f"netlist says {a}-{b} is {got_ans}, expected {want_ans}")
|
||||
print("ok netlist provider: 3 comps / 6 pads / 4 conduct edges, "
|
||||
"no cross-net edge, isolated pin stays isolated")
|
||||
return True
|
||||
|
||||
|
||||
def cmd_smoke(args) -> int:
|
||||
cfg = _load_config(args.config)
|
||||
print(f"config {args.config} out {cfg['out_dir']}")
|
||||
results = [check_splits(cfg), check_determinism(), check_labels(),
|
||||
check_insufficient(), check_invariances(), check_cross_family_digest(),
|
||||
check_extract_contacts(), check_scope_agrees(),
|
||||
check_netlist_provider()]
|
||||
|
||||
# one update, then interrupt and resume: the step counter must advance
|
||||
from . import train as trainer
|
||||
short = json.loads(json.dumps(cfg))
|
||||
short["optim"]["steps"] = 2
|
||||
short["optim"]["log_every"] = 1
|
||||
short["eval"]["n"] = 12
|
||||
m1 = trainer.run(short, verbose=False)
|
||||
ckpt = os.path.join(short["out_dir"], "ckpt.pt")
|
||||
if not os.path.exists(ckpt):
|
||||
results.append(_fail("checkpoint not written"))
|
||||
elif os.path.exists(ckpt + ".tmp"):
|
||||
results.append(_fail("temporary checkpoint left behind"))
|
||||
else:
|
||||
print(f"ok checkpoint written atomically, val answer_acc {m1['answer_acc']:.2f}")
|
||||
|
||||
from . import train as trainer2
|
||||
m2 = trainer2.run(short, resume=True, steps=1, verbose=False)
|
||||
_, _, step, _ = trainer2.load(ckpt)
|
||||
if step != 3:
|
||||
results.append(_fail(f"resume advanced to step {step}, expected 3"))
|
||||
else:
|
||||
print(f"ok resume continued at step {step} (2 + 1)")
|
||||
|
||||
print("---")
|
||||
if all(results):
|
||||
print("smoke PASS")
|
||||
return 0
|
||||
print("smoke FAIL")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_train(args) -> int:
|
||||
from . import train as trainer
|
||||
cfg = _load_config(args.config)
|
||||
if args.seed is not None:
|
||||
cfg["seed"] = args.seed
|
||||
cfg["out_dir"] = f"{cfg['out_dir']}_s{args.seed}"
|
||||
trainer.run(cfg, resume=args.resume, steps=args.steps)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_eval(args) -> int:
|
||||
from . import train as trainer
|
||||
cfg = _load_config(args.config)
|
||||
if args.seed is not None:
|
||||
cfg["seed"] = args.seed
|
||||
cfg["out_dir"] = f"{cfg['out_dir']}_s{args.seed}"
|
||||
model, _, step, cfg = trainer.load(os.path.join(cfg["out_dir"], "ckpt.pt"))
|
||||
for split in ("train", "val", "test"):
|
||||
fams = cfg["data"][f"{split}_families"]
|
||||
m = trainer.evaluate(model, fams, cfg["seed"], cfg["eval"]["n"])
|
||||
print(f"{split:5s} " + json.dumps({k: (round(v, 3) if isinstance(v, float) else v)
|
||||
for k, v in m.items() if k != "loss"}))
|
||||
print(f"step {step}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_report(args) -> int:
|
||||
from . import report
|
||||
report.report(args.config, n=args.n, ablate=args.ablate, seed=args.seed)
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
p = argparse.ArgumentParser(prog="spatial")
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
for name, fn in (("smoke", cmd_smoke), ("train", cmd_train), ("eval", cmd_eval),
|
||||
("report", cmd_report)):
|
||||
sp = sub.add_parser(name)
|
||||
sp.add_argument("--config", default=os.path.join(os.path.dirname(__file__), "configs", "smoke.json"))
|
||||
sp.add_argument("--seed", type=int, default=None,
|
||||
help="override config seed (data and init both follow it)")
|
||||
if name != "eval":
|
||||
sp.add_argument("--steps", type=int, default=None)
|
||||
if name == "train":
|
||||
sp.add_argument("--resume", action="store_true")
|
||||
if name == "report":
|
||||
sp.add_argument("--n", type=int, default=128)
|
||||
sp.add_argument("--ablate", default=None,
|
||||
help="comma list of dangling | scene | hidden | edge_feat; "
|
||||
"hidden zeroes only the full-state-derived slice of "
|
||||
"the scene features, leaving the scope block intact")
|
||||
sp.set_defaults(fn=fn)
|
||||
args = p.parse_args(argv)
|
||||
return args.fn(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,39 @@
|
||||
# 运行配置
|
||||
|
||||
`out_dir` 相对仓库根,输出落在 `out_spatial/<名字>/`。`--seed N` 会追加 `_sN`。
|
||||
|
||||
## 规范配置
|
||||
|
||||
| 文件 | 用途 | 结果 |
|
||||
|---|---|---|
|
||||
| `smoke.json` | 契约测试(`cli smoke` 的默认值),2 步即可 | 必须 PASS |
|
||||
| `declared.json` | **主实验**:14 训练族 / 2 测试族,12000 步;可用性只给 `scope`(合规) | 三种子:19 族 acc 全 1.000,abst 0.999 |
|
||||
| `sources.json` | 契约扩展:加 `src.scope`/`src.clean`(两份来源冲突),`src.scope4` 作结构外测试 | 三种子 21 族全 1.000;`declared` 也能零样本迁移 |
|
||||
| `dangling.json` | **对照组**:同数据同预算,可用性给 `dangling` + 隐藏计数(泄漏) | 与上面逐格相同 —— 泄漏不是弃权的必要条件 |
|
||||
| `setonly.json` | 只训 `dof.set`,隔离"六个轴是否全覆盖"这个子技能 | 1.000(用于定位读出缺陷) |
|
||||
| `cross_oneshot.json` | 对照:第一版混合集,被一位规则完全可分 | 6 族与平凡规则逐位相同 |
|
||||
|
||||
## 不进 split 的家族
|
||||
|
||||
`area.gap1/gap2/gap4` 是**单答案家族**(恒 false),常量规则就能拿 1.000,加进任何
|
||||
split 都会造出一个假满分。它们只做两件事:`spatial.extract` 的回归测试(把上块抬离
|
||||
底座 1/2/4 格,问提取器会不会焊出一条不存在的接触),以及**外推探针**——训练里有
|
||||
`area.near`(间隙族内抽 0 或 1–2),gap 家族问的是"1/2/4 格这个没见过的尺度还认不
|
||||
认得"。三种子实测 1.000,说明学到的是"接触"而不是某个具体距离。
|
||||
|
||||
`smoke` 每次都会打印"哪些家族没被任何 split 使用",加家族时先看那行。
|
||||
|
||||
## 归档(`archive/`)
|
||||
|
||||
| 文件 | 当时的用途 | 留下它的理由 |
|
||||
|---|---|---|
|
||||
| `floor.json` | 单族 `cond.p3` 400 步基线 | 最早的"看起来满分"样本,后被证伪 |
|
||||
| `cross.json` | 首次跨族,7 族 | 一位规则可分的证据 |
|
||||
| `abstain.json` | 弃权是否跨域(connection+freedom 监督,测 stability) | 当时 abst 0.000,定位到标签语义问题 |
|
||||
| `dang_b.json` | lr 1.5e-3 / warmup 300 / 4800 步 | 证明降 lr 救不回 dof.set(0.328) |
|
||||
| `dang_c.json` | lr 3e-3 / warmup 300 / 4800 步 | 与 `dangling.json` 等价,是 warmup 对照组的原件 |
|
||||
| `dang_d.json` | lr 1.5e-3 / warmup 300 / 7200 步 | 证明加步数不是必需(1.000) |
|
||||
| `dangling_long.json` | 4800→等价于主配置加长版 | 双倍步数曾修掉 seed2 的坏结果 |
|
||||
|
||||
四组 warmup 对照的结论在 [docs/FINDINGS.md](../../docs/FINDINGS.md) 第二节第 8 条:
|
||||
根因是预热长度,不是学习率也不是步数。
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192, "n_layer": 4, "n_head": 6, "dropout": 0.1, "max_entities": 32,
|
||||
"rounds": 2, "n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": ["cond.p1", "cond.p3", "area.sup2", "area.sup3", "dof.c6", "dof.c6r", "cond.p1h", "dof.c6h"],
|
||||
"val_families": ["area.sup2h", "cond.p3h"],
|
||||
"test_families": ["area.sup2h", "cond.p3h"]
|
||||
},
|
||||
"optim": { "lr": 0.003, "weight_decay": 0.01, "steps": 2400, "batch": 32, "log_every": 400 },
|
||||
"eval": { "n": 192 },
|
||||
"out_dir": "out_spatial/abstain"
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.1,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p1",
|
||||
"cond.p3",
|
||||
"area.sup2",
|
||||
"area.sup3",
|
||||
"area.free",
|
||||
"dof.c6",
|
||||
"dof.c6r"
|
||||
],
|
||||
"val_families": [
|
||||
"cond.p1h",
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
],
|
||||
"test_families": [
|
||||
"cond.p1h",
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
]
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.003,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 2400,
|
||||
"batch": 32,
|
||||
"log_every": 400,
|
||||
"warmup": 300
|
||||
},
|
||||
"eval": {
|
||||
"n": 192
|
||||
},
|
||||
"out_dir": "out_spatial/cross"
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.1,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p1",
|
||||
"cond.p3",
|
||||
"cond.p3h",
|
||||
"cond.p1h",
|
||||
"area.sup2",
|
||||
"area.sup3",
|
||||
"area.sup3h",
|
||||
"area.sup2d",
|
||||
"area.free",
|
||||
"dof.c6",
|
||||
"dof.c6r",
|
||||
"dof.c6d",
|
||||
"dof.set"
|
||||
],
|
||||
"val_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
],
|
||||
"test_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
]
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.0015,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 4800,
|
||||
"batch": 32,
|
||||
"log_every": 400,
|
||||
"warmup": 300
|
||||
},
|
||||
"eval": {
|
||||
"n": 192
|
||||
},
|
||||
"out_dir": "out_spatial/dang_b"
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.1,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p1",
|
||||
"cond.p3",
|
||||
"cond.p3h",
|
||||
"cond.p1h",
|
||||
"area.sup2",
|
||||
"area.sup3",
|
||||
"area.sup3h",
|
||||
"area.sup2d",
|
||||
"area.free",
|
||||
"dof.c6",
|
||||
"dof.c6r",
|
||||
"dof.c6d",
|
||||
"dof.set"
|
||||
],
|
||||
"val_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
],
|
||||
"test_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
]
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.003,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 4800,
|
||||
"batch": 32,
|
||||
"log_every": 400,
|
||||
"warmup": 300
|
||||
},
|
||||
"eval": {
|
||||
"n": 192
|
||||
},
|
||||
"out_dir": "out_spatial/dang_c"
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.1,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p1",
|
||||
"cond.p3",
|
||||
"cond.p3h",
|
||||
"cond.p1h",
|
||||
"area.sup2",
|
||||
"area.sup3",
|
||||
"area.sup3h",
|
||||
"area.sup2d",
|
||||
"area.free",
|
||||
"dof.c6",
|
||||
"dof.c6r",
|
||||
"dof.c6d",
|
||||
"dof.set"
|
||||
],
|
||||
"val_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
],
|
||||
"test_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
]
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.0015,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 7200,
|
||||
"batch": 32,
|
||||
"log_every": 400,
|
||||
"warmup": 300
|
||||
},
|
||||
"eval": {
|
||||
"n": 192
|
||||
},
|
||||
"out_dir": "out_spatial/dang_d"
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.1,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p1",
|
||||
"cond.p3",
|
||||
"cond.p3h",
|
||||
"cond.p1h",
|
||||
"area.sup2",
|
||||
"area.sup3",
|
||||
"area.sup3h",
|
||||
"area.free",
|
||||
"dof.c6",
|
||||
"dof.c6r",
|
||||
"dof.c6h",
|
||||
"dof.set"
|
||||
],
|
||||
"val_families": [
|
||||
"area.sup2h"
|
||||
],
|
||||
"test_families": [
|
||||
"area.sup2h",
|
||||
"cond.p3h"
|
||||
]
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.003,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 4800,
|
||||
"batch": 32,
|
||||
"log_every": 400,
|
||||
"warmup": 300
|
||||
},
|
||||
"eval": {
|
||||
"n": 192
|
||||
},
|
||||
"out_dir": "out_spatial/dangling_long"
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.0,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p3"
|
||||
],
|
||||
"val_families": [
|
||||
"cond.p3"
|
||||
],
|
||||
"test_families": [
|
||||
"cond.p3"
|
||||
]
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.003,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 400,
|
||||
"batch": 32,
|
||||
"log_every": 100,
|
||||
"warmup": 300
|
||||
},
|
||||
"eval": {
|
||||
"n": 96
|
||||
},
|
||||
"out_dir": "out_spatial/floor"
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.1,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p1",
|
||||
"area.sup2",
|
||||
"dof.c6"
|
||||
],
|
||||
"val_families": [
|
||||
"cond.p1h",
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
],
|
||||
"test_families": [
|
||||
"cond.p3h",
|
||||
"area.sup3",
|
||||
"dof.c6r"
|
||||
]
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.003,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 1200,
|
||||
"batch": 32,
|
||||
"log_every": 200
|
||||
},
|
||||
"eval": {
|
||||
"n": 192
|
||||
},
|
||||
"out_dir": "out_spatial/cross_oneshot"
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.1,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p1",
|
||||
"cond.p3",
|
||||
"cond.p3h",
|
||||
"cond.p1h",
|
||||
"area.sup2",
|
||||
"area.sup3",
|
||||
"area.sup3h",
|
||||
"area.sup2d",
|
||||
"area.free",
|
||||
"dof.c6",
|
||||
"dof.c6r",
|
||||
"dof.c6d",
|
||||
"dof.set",
|
||||
"area.near"
|
||||
],
|
||||
"val_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
],
|
||||
"test_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
],
|
||||
"availability": "leaked"
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.003,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 12000,
|
||||
"batch": 32,
|
||||
"log_every": 400,
|
||||
"warmup": 300
|
||||
},
|
||||
"eval": {
|
||||
"n": 192
|
||||
},
|
||||
"out_dir": "out_spatial/dangling"
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.1,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p1",
|
||||
"cond.p3",
|
||||
"cond.p3h",
|
||||
"cond.p1h",
|
||||
"area.sup2",
|
||||
"area.sup3",
|
||||
"area.sup3h",
|
||||
"area.sup2d",
|
||||
"area.free",
|
||||
"dof.c6",
|
||||
"dof.c6r",
|
||||
"dof.c6d",
|
||||
"dof.set",
|
||||
"area.near"
|
||||
],
|
||||
"val_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
],
|
||||
"test_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
],
|
||||
"availability": "declared"
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.003,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 12000,
|
||||
"batch": 32,
|
||||
"log_every": 400,
|
||||
"warmup": 300
|
||||
},
|
||||
"eval": {
|
||||
"n": 192
|
||||
},
|
||||
"out_dir": "out_spatial/declared"
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.1,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"dof.set"
|
||||
],
|
||||
"val_families": [
|
||||
"dof.set"
|
||||
],
|
||||
"test_families": [
|
||||
"dof.c6"
|
||||
]
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.003,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 2400,
|
||||
"batch": 32,
|
||||
"log_every": 400,
|
||||
"warmup": 300
|
||||
},
|
||||
"eval": {
|
||||
"n": 192
|
||||
},
|
||||
"out_dir": "out_spatial/setonly"
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 64,
|
||||
"n_layer": 2,
|
||||
"n_head": 4,
|
||||
"dropout": 0.0,
|
||||
"max_entities": 32
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p1",
|
||||
"area.sup2",
|
||||
"dof.c6",
|
||||
"area.near"
|
||||
],
|
||||
"val_families": [
|
||||
"cond.p3",
|
||||
"area.sup3",
|
||||
"dof.c6r"
|
||||
],
|
||||
"test_families": [
|
||||
"cond.p1h",
|
||||
"cond.p3h",
|
||||
"area.sup2h",
|
||||
"dof.c6h",
|
||||
"src.scope"
|
||||
],
|
||||
"availability": "declared"
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.003,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 2,
|
||||
"batch": 16,
|
||||
"log_every": 1
|
||||
},
|
||||
"eval": {
|
||||
"n": 12
|
||||
},
|
||||
"out_dir": "out_spatial/smoke"
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"seed": 0,
|
||||
"model": {
|
||||
"d": 192,
|
||||
"n_layer": 4,
|
||||
"n_head": 6,
|
||||
"dropout": 0.1,
|
||||
"max_entities": 32,
|
||||
"rounds": 2,
|
||||
"n_evidence": 4
|
||||
},
|
||||
"data": {
|
||||
"train_families": [
|
||||
"cond.p1",
|
||||
"cond.p3",
|
||||
"cond.p3h",
|
||||
"cond.p1h",
|
||||
"area.sup2",
|
||||
"area.sup3",
|
||||
"area.sup3h",
|
||||
"area.sup2d",
|
||||
"area.free",
|
||||
"dof.c6",
|
||||
"dof.c6r",
|
||||
"dof.c6d",
|
||||
"dof.set",
|
||||
"area.near",
|
||||
"src.scope",
|
||||
"src.clean"
|
||||
],
|
||||
"val_families": [
|
||||
"src.scope4"
|
||||
],
|
||||
"test_families": [
|
||||
"area.sup2h",
|
||||
"dof.c6h"
|
||||
],
|
||||
"availability": "declared"
|
||||
},
|
||||
"optim": {
|
||||
"lr": 0.003,
|
||||
"weight_decay": 0.01,
|
||||
"steps": 12000,
|
||||
"batch": 32,
|
||||
"log_every": 400,
|
||||
"warmup": 300
|
||||
},
|
||||
"eval": {
|
||||
"n": 192
|
||||
},
|
||||
"out_dir": "out_spatial/sources"
|
||||
}
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
"""Tensorisation.
|
||||
|
||||
Padding lives here and only here. A scenario with more entities than
|
||||
``max_entities`` is rejected explicitly -- the plan forbids silently truncating
|
||||
a scene, because cutting a node can turn "still connected" into "disconnected"
|
||||
and quietly corrupt the label.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
from collections import deque
|
||||
|
||||
from .schema import ANSWERS, CHANGES, DOF_AXES, EDGE_KINDS, ENTITY_KINDS, Scenario
|
||||
from .model import EDGE_FEAT_DIM, FEAT_DIM, N_AXIS, N_EDGE, QUERY_KINDS, SCENE_DIM
|
||||
|
||||
|
||||
def _reach(edges, src: str, alive) -> set:
|
||||
adj = {}
|
||||
for e in edges:
|
||||
if not alive(e):
|
||||
continue
|
||||
adj.setdefault(e.a, []).append(e.b)
|
||||
adj.setdefault(e.b, []).append(e.a)
|
||||
seen, q = {src}, deque([src])
|
||||
while q:
|
||||
u = q.popleft()
|
||||
for v in adj.get(u, ()):
|
||||
if v not in seen:
|
||||
seen.add(v)
|
||||
q.append(v)
|
||||
return seen
|
||||
|
||||
|
||||
def evidence_target(sc: Scenario) -> set:
|
||||
"""Every edge that can appear in *some* valid certificate counts as positive.
|
||||
|
||||
For a connection the checker returns one shortest path, but any a-b path is
|
||||
a correct answer; training against a single one marks its equally valid
|
||||
siblings as negatives and the head learns nothing usable. An edge lies on
|
||||
some a-b path exactly when it can be traversed from a towards b.
|
||||
"""
|
||||
if sc.query.kind == "connection" and sc.label.answer == "true":
|
||||
removed = (sc.query.edit or {}).get("edge")
|
||||
alive = lambda e: e.eid != removed
|
||||
ra = _reach(sc.obs.edges, sc.query.a, alive)
|
||||
rb = _reach(sc.obs.edges, sc.query.b, alive)
|
||||
return {e.eid for e in sc.obs.edges
|
||||
if e.eid != removed
|
||||
and ((e.a in ra and e.b in rb) or (e.b in ra and e.a in rb))}
|
||||
return set(sc.label.evidence or [])
|
||||
|
||||
|
||||
def _unit_onehot(per_unit: int):
|
||||
return {1: 0, 10: 1, 100: 2}.get(per_unit, 0)
|
||||
|
||||
|
||||
def entity_features(sc: Scenario, e) -> list:
|
||||
f = [0.0] * FEAT_DIM
|
||||
f[ENTITY_KINDS.index(e.kind)] = 1.0
|
||||
f[len(ENTITY_KINDS) + (0 if e.source == "given" else 1)] = 1.0
|
||||
f[len(ENTITY_KINDS) + 2 + _unit_onehot(sc.obs.units.get("per_unit", 1))] = 1.0
|
||||
base = len(ENTITY_KINDS) + 2 + 3
|
||||
scale = 200.0 * max(1, sc.obs.units.get("per_unit", 1))
|
||||
box = e.attrs.get("box")
|
||||
if box:
|
||||
cx, cy, cz = (box[0] + box[3]) / 2, (box[1] + box[4]) / 2, (box[2] + box[5]) / 2
|
||||
d = [cx / scale, cy / scale, cz / scale, e.attrs.get("layer", 0) / 6.0,
|
||||
(box[3] - box[0]) / scale, (box[4] - box[1]) / scale, (box[5] - box[2]) / scale]
|
||||
else:
|
||||
d = [e.attrs.get("x", 0) / scale, e.attrs.get("y", 0) / scale,
|
||||
e.attrs.get("z", 0) / scale, e.attrs.get("layer", 0) / 6.0, 0.0, 0.0, 0.0]
|
||||
f[base:base + 7] = d
|
||||
return f
|
||||
|
||||
|
||||
def _contact_geom(by_id: dict, ed, per_unit: int = 1):
|
||||
"""(area, faces_meet, centroid_inside, area_ratio) for a contact edge.
|
||||
|
||||
The checker's stability rule is local: two boxes support each other when
|
||||
their faces actually meet and the upper centroid falls inside the overlap
|
||||
rectangle. Leaving that predicate to be recomputed from two coordinate
|
||||
vectors is leaving arithmetic to a classifier; measuring it per edge is what
|
||||
a caliper would do and it says nothing about the answer.
|
||||
"""
|
||||
a, b = by_id.get(ed.a), by_id.get(ed.b)
|
||||
if a is None or b is None:
|
||||
return 0.0, 0.0, 0.0, 0.0
|
||||
ba, bb = a.attrs.get("box"), b.attrs.get("box")
|
||||
if not ba or not bb:
|
||||
return 0.0, 0.0, 0.0, 0.0
|
||||
scale = 400.0 * max(1, per_unit) ** 2
|
||||
ox0, oy0 = max(ba[0], bb[0]), max(ba[1], bb[1])
|
||||
ox1, oy1 = min(ba[3], bb[3]), min(ba[4], bb[4])
|
||||
if ox0 >= ox1 or oy0 >= oy1:
|
||||
return 0.0, 0.0, 0.0, 0.0
|
||||
area = min(1.0, (ox1 - ox0) * (oy1 - oy0) / scale)
|
||||
meet = 1.0 if (ba[5] == bb[2] or bb[5] == ba[2]) else 0.0
|
||||
# the support is the lower one; its centroid has to sit on the overlap
|
||||
up = ba if ba[2] >= bb[2] else bb
|
||||
cx2, cy2 = up[0] + up[3], up[1] + up[4] # twice the centroid, stays integer
|
||||
inside = 1.0 if (2 * ox0 <= cx2 <= 2 * ox1 and 2 * oy0 <= cy2 <= 2 * oy1) else 0.0
|
||||
foot = max(1, (up[3] - up[0]) * (up[4] - up[1]))
|
||||
return area, meet, inside, min(1.0, (ox1 - ox0) * (oy1 - oy0) / foot)
|
||||
|
||||
|
||||
def _contact_area(by_id: dict, ed, per_unit: int = 1) -> float:
|
||||
return _contact_geom(by_id, ed, per_unit)[0]
|
||||
|
||||
|
||||
def edge_features(sc: Scenario, ed, removed: bool, dangling: bool = False) -> list:
|
||||
f = [0.0] * EDGE_FEAT_DIM
|
||||
f[EDGE_KINDS.index(ed.kind)] = 1.0
|
||||
ax = ed.attrs.get("axis")
|
||||
if ax in DOF_AXES:
|
||||
f[N_EDGE + DOF_AXES.index(ax)] = 1.0
|
||||
f[N_EDGE + N_AXIS] = 1.0 if removed else 0.0
|
||||
f[N_EDGE + N_AXIS + 1] = ed.layer / 6.0
|
||||
by_id = {e.eid: e for e in sc.obs.entities}
|
||||
geom = _contact_geom(by_id, ed, sc.obs.units.get("per_unit", 1))
|
||||
f[N_EDGE + N_AXIS + 2] = geom[0]
|
||||
f[N_EDGE + N_AXIS + 3] = 1.0 if dangling else 0.0
|
||||
f[N_EDGE + N_AXIS + 4:N_EDGE + N_AXIS + 7] = list(geom[1:])
|
||||
f[N_EDGE + N_AXIS + 7] = 1.0 if _disputed(sc, ed) else 0.0
|
||||
return f
|
||||
|
||||
|
||||
def _disputed(sc: Scenario, ed) -> bool:
|
||||
"""Named by two sources and disagreed on. Carries no vote: which source wins
|
||||
is the one thing the system must not decide by itself."""
|
||||
pair = {ed.a, ed.b}
|
||||
return any(c.get("kind") == ed.kind and {c.get("a"), c.get("b")} == pair
|
||||
for c in (sc.obs.conflicts or []))
|
||||
|
||||
|
||||
def scene_features(sc: Scenario, availability: str = "leaked") -> list:
|
||||
"""The observation's own admission of what it is missing.
|
||||
|
||||
``hidden_layers`` and ``hidden_faces`` are in the digest but were never in
|
||||
the tensor, so "no hidden branch" and "a hidden branch off-view" arrived at
|
||||
the model as the same input with opposite labels. That is not an
|
||||
under-fitting problem; it is information the contract promised and the
|
||||
tensorisation dropped.
|
||||
|
||||
Counts by kind, not identities: "one contact is missing" is a fact the
|
||||
agent can act on, "kPT is missing" would be a leak of the answer.
|
||||
"""
|
||||
f = [0.0] * SCENE_DIM
|
||||
for layer in sc.obs.hidden_layers:
|
||||
if 1 <= layer <= 3:
|
||||
f[layer - 1] = 1.0
|
||||
f[3] = min(1.0, len(sc.obs.hidden_faces) / 6.0)
|
||||
hidden = sc.obs.hidden or {}
|
||||
for kind, cnt in (hidden.get("entity") or {}).items():
|
||||
if kind in ENTITY_KINDS:
|
||||
f[4 + ENTITY_KINDS.index(kind)] = min(1.0, cnt / 2.0)
|
||||
for kind, cnt in (hidden.get("edge") or {}).items():
|
||||
if kind in EDGE_KINDS:
|
||||
f[4 + len(ENTITY_KINDS) + EDGE_KINDS.index(kind)] = min(1.0, cnt / 3.0)
|
||||
base = 4 + len(ENTITY_KINDS) + len(EDGE_KINDS)
|
||||
f[base] = 1.0 if (hidden.get("entity") or hidden.get("edge")) else 0.0
|
||||
f[base + 1] = len(sc.obs.entities) / 32.0
|
||||
# the declared inventory: what the source says it has versus what it handed
|
||||
# over. No endpoints, so it can suspend an answer but never decide one. This
|
||||
# is the only availability channel the contract allows; the block above is
|
||||
# computed as "full minus visible" and therefore is not something a provider
|
||||
# can produce.
|
||||
scope = sc.obs.scope or {}
|
||||
parts = scope.get("parts") or {}
|
||||
rendered = scope.get("rendered") or {}
|
||||
rel = scope.get("relations") or {}
|
||||
rel_r = scope.get("rendered_relations") or {}
|
||||
tot_parts = sum(parts.values()) or 0
|
||||
tot_rel = sum(rel.values()) or 0
|
||||
f[base + 2] = (tot_parts - sum(rendered.values())) / tot_parts if tot_parts else 0.0
|
||||
f[base + 3] = (tot_rel - sum(rel_r.values())) / tot_rel if tot_rel else 0.0
|
||||
missing_layers = set(scope.get("layers") or []) - set(scope.get("rendered_layers") or [])
|
||||
f[base + 4] = min(1.0, len(missing_layers) / 4.0)
|
||||
f[base + 5] = 1.0 if (scope.get("layers") or []) and (
|
||||
tot_parts > sum(rendered.values()) or tot_rel > sum(rel_r.values())
|
||||
or missing_layers) else 0.0
|
||||
if availability != "leaked":
|
||||
# training-time, not eval-time: the model must never see a channel it
|
||||
# could not be given at inference. Zeroing at eval only measures whether
|
||||
# a channel was necessary, never whether the rest is sufficient.
|
||||
f[0:base] = [0.0] * base
|
||||
return f
|
||||
|
||||
|
||||
def collate(batch, max_entities: int = 32, availability: str = "leaked"):
|
||||
B = len(batch)
|
||||
N = max(1, max(len(sc.obs.entities) for sc in batch))
|
||||
E = max(1, max(len(sc.obs.edges) + (len(sc.obs.dangling) if availability == "leaked"
|
||||
else 0) for sc in batch))
|
||||
if N > max_entities:
|
||||
raise ValueError(f"scene needs {N} entity slots > max_entities {max_entities}; "
|
||||
"bucket it instead of truncating")
|
||||
|
||||
feat = torch.zeros(B, N, FEAT_DIM)
|
||||
scene = torch.zeros(B, SCENE_DIM)
|
||||
pad_mask = torch.ones(B, N, dtype=torch.bool)
|
||||
edge_index = torch.zeros(B, E, 2, dtype=torch.long)
|
||||
edge_type = torch.zeros(B, E, dtype=torch.long)
|
||||
edge_feat = torch.zeros(B, E, EDGE_FEAT_DIM)
|
||||
edge_mask = torch.zeros(B, E, dtype=torch.bool)
|
||||
evidence = torch.zeros(B, E)
|
||||
edge_removed = torch.zeros(B, E)
|
||||
dangling = torch.zeros(B, E)
|
||||
q_ents = torch.full((B, 2), -1, dtype=torch.long)
|
||||
q_kind = torch.zeros(B, dtype=torch.long)
|
||||
edit_op = torch.zeros(B, dtype=torch.long) # 0 none, 1 remove_edge, 2 remove_entity
|
||||
edit_idx = torch.full((B,), -1, dtype=torch.long)
|
||||
answer = torch.zeros(B, dtype=torch.long)
|
||||
change = torch.zeros(B, dtype=torch.long)
|
||||
|
||||
for i, sc in enumerate(batch):
|
||||
ids = {e.eid: j for j, e in enumerate(sc.obs.entities)}
|
||||
scene[i] = torch.tensor(scene_features(sc, availability))
|
||||
for j, e in enumerate(sc.obs.entities):
|
||||
feat[i, j] = torch.tensor(entity_features(sc, e))
|
||||
pad_mask[i, j] = False
|
||||
ev = evidence_target(sc)
|
||||
removed_eid = (sc.query.edit or {}).get("edge")
|
||||
for k, ed in enumerate(sc.obs.edges):
|
||||
edge_index[i, k, 0] = ids.get(ed.a, 0)
|
||||
edge_index[i, k, 1] = ids.get(ed.b, 0)
|
||||
edge_type[i, k] = EDGE_KINDS.index(ed.kind)
|
||||
edge_mask[i, k] = True
|
||||
evidence[i, k] = 1.0 if ed.eid in ev else 0.0
|
||||
rm = ed.eid == removed_eid
|
||||
edge_removed[i, k] = 1.0 if rm else 0.0
|
||||
edge_feat[i, k] = torch.tensor(edge_features(sc, ed, rm))
|
||||
# dangling relations go after the real ones and point at the unknown
|
||||
# slot via the sentinel endpoint ``N``; their far end is never an entity,
|
||||
# so they can never be mistaken for a traversable edge
|
||||
for j, dl in enumerate(sc.obs.dangling if availability == "leaked" else ()):
|
||||
k = len(sc.obs.edges) + j
|
||||
edge_index[i, k, 0] = ids.get(dl.a, 0)
|
||||
edge_index[i, k, 1] = N
|
||||
edge_type[i, k] = EDGE_KINDS.index(dl.kind)
|
||||
edge_mask[i, k] = True
|
||||
dangling[i, k] = 1.0
|
||||
edge_feat[i, k] = torch.tensor(edge_features(sc, dl, False, dangling=True))
|
||||
q_ents[i, 0] = ids.get(sc.query.a, -1)
|
||||
q_ents[i, 1] = ids.get(sc.query.b, -1)
|
||||
q_kind[i] = QUERY_KINDS.index(sc.query.kind)
|
||||
# the intervention is part of the input, not something to infer from a
|
||||
# missing edge: without it "removed the trunk" and "removed a branch"
|
||||
# are the same tensor and the answer is unlearnable
|
||||
edit = sc.query.edit or {}
|
||||
if edit.get("op") == "remove_edge":
|
||||
eid2idx = {e.eid: k for k, e in enumerate(sc.obs.edges)}
|
||||
edit_op[i] = 1
|
||||
edit_idx[i] = eid2idx.get(edit.get("edge"), -1)
|
||||
elif edit.get("op") == "remove_entity":
|
||||
edit_op[i] = 2
|
||||
edit_idx[i] = ids.get(edit.get("entity"), -1)
|
||||
# an entity that is gone takes its relations with it. Without this
|
||||
# the post-intervention graph still has T resting on the pedestal it
|
||||
# just lost, the hop distance still reports support, and the only
|
||||
# evidence against support is the edit token itself -- which makes
|
||||
# "an edit happened, answer false" the cheapest consistent rule.
|
||||
gone = edit.get("entity")
|
||||
for k, ed in enumerate(sc.obs.edges):
|
||||
if gone in (ed.a, ed.b):
|
||||
edge_removed[i, k] = 1.0
|
||||
answer[i] = ANSWERS.index(sc.label.answer)
|
||||
change[i] = CHANGES.index(sc.label.change)
|
||||
|
||||
return {
|
||||
"feat": feat, "pad_mask": pad_mask,
|
||||
"edge_index": edge_index, "edge_type": edge_type, "edge_mask": edge_mask,
|
||||
"edge_feat": edge_feat,
|
||||
"scene": scene,
|
||||
"q_ents": q_ents, "q_kind": q_kind,
|
||||
"edit_op": edit_op, "edit_idx": edit_idx,
|
||||
"edge_removed": edge_removed,
|
||||
"dangling": dangling,
|
||||
"answer": answer, "change": change, "evidence": evidence,
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
"""几何 → 关系图:提取器,以及它证明不出来的东西。
|
||||
|
||||
M2 的第一件事不是加结构,而是查一个从没查过的前提:``Observation`` 里那张
|
||||
实体+关系图,在真实场景里由谁给出。
|
||||
|
||||
这里不接 CAD、不引第三方几何库,只做最小可判定的实验:把夹具的盒子表面变成
|
||||
三角形,再从**几何本身**推接触关系(不看 schema 里的答案),然后问两个问题:
|
||||
|
||||
1. 从几何提取的图,能不能复现检查器给出的凭证?
|
||||
2. 连通和自由度这两类关系,能不能从几何里提出来?
|
||||
|
||||
第 2 问的答案决定了 M2 的输入从哪来,比任何模型改动都重要。
|
||||
|
||||
接触的判定方式换过一次,这件事本身是个结论。第一版按**表面距离 <= 容差**判,
|
||||
于是容差变成了决定答案的参数:真实装配的余隙是 0.2mm 级,容差一旦跨过余隙,
|
||||
两个根本没碰上的零件就被焊在一起,而且这种假接触还能通过凭证校验
|
||||
(``area.gap1`` 在容差 1 格时 8/8 全错)。第二版按**共面精确匹配**判:B-rep 里
|
||||
贴合的两个面本来就是同一张面,平面坐标相等、法向相反、矩形投影有正面积重叠,
|
||||
不需要容差。``eps`` 从"决定答案的参数"降级成"吃掉浮点噪声的兜底"。
|
||||
两版都留着,``report_tolerance`` 把它们并排跑——旧版是这一节的控制组。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from . import checker, generator
|
||||
from .schema import Edge, FullState, Query
|
||||
|
||||
CONTACT = "contact"
|
||||
|
||||
|
||||
from .geom import _aabb_gap, box_contact_area, surface_gap
|
||||
|
||||
|
||||
def extract_edges(entities, eps: float = 0.0) -> list:
|
||||
"""Contacts implied by geometry alone: coincident faces.
|
||||
|
||||
``eps`` is a numerical epsilon, not a design tolerance. It should be zero
|
||||
for exact coordinates and a few ulps when boxes come out of a transform.
|
||||
Everything else -- conduct, constraint -- has no geometric signature and is
|
||||
simply not produced.
|
||||
"""
|
||||
boxes = {e.eid: tuple(float(v) for v in e.attrs["box"])
|
||||
for e in entities if e.attrs.get("box")}
|
||||
planes = {e.eid: float(e.attrs.get("plane", 0)) for e in entities
|
||||
if e.kind == "ground"}
|
||||
ids = sorted(boxes)
|
||||
edges = []
|
||||
n = 0
|
||||
for i in range(len(ids)):
|
||||
for j in range(i + 1, len(ids)):
|
||||
if box_contact_area(boxes[ids[i]], boxes[ids[j]], eps) > 0:
|
||||
edges.append(Edge(f"x{n}", CONTACT, ids[i], ids[j]))
|
||||
n += 1
|
||||
for eid in ids:
|
||||
b = boxes[eid]
|
||||
for gid, z in planes.items():
|
||||
if abs(b[2] - z) <= eps:
|
||||
edges.append(Edge(f"x{n}", CONTACT, eid, gid))
|
||||
n += 1
|
||||
return edges
|
||||
|
||||
|
||||
def extract_edges_by_distance(entities, tol: float = 0.5) -> list:
|
||||
"""The first version, kept as the control group.
|
||||
|
||||
Touching = surfaces within ``tol`` and a shared footprint. It looks
|
||||
reasonable and it is the reason ``tol`` was a live parameter: whether a
|
||||
contact exists depends on how big ``tol`` is, so a part 0.25mm away can be
|
||||
welded to its neighbour by choosing ``tol = 0.5``. Used by
|
||||
``report_tolerance`` only; production paths use :func:`extract_edges`.
|
||||
"""
|
||||
boxes = {e.eid: tuple(float(v) for v in e.attrs["box"])
|
||||
for e in entities if e.attrs.get("box")}
|
||||
planes = {e.eid: float(e.attrs.get("plane", 0)) for e in entities
|
||||
if e.kind == "ground"}
|
||||
ids = sorted(boxes)
|
||||
edges = []
|
||||
n = 0
|
||||
for i in range(len(ids)):
|
||||
for j in range(i + 1, len(ids)):
|
||||
a, b = boxes[ids[i]], boxes[ids[j]]
|
||||
if _aabb_gap(a, b) > tol:
|
||||
continue
|
||||
if min(a[3], b[3]) <= max(a[0], b[0]) or min(a[4], b[4]) <= max(a[1], b[1]):
|
||||
continue # no shared footprint: no contact
|
||||
if surface_gap(a, b) <= tol:
|
||||
edges.append(Edge(f"x{n}", CONTACT, ids[i], ids[j]))
|
||||
n += 1
|
||||
for eid in ids:
|
||||
b = boxes[eid]
|
||||
for gid, z in planes.items():
|
||||
if abs(b[2] - z) <= tol:
|
||||
edges.append(Edge(f"x{n}", CONTACT, eid, gid))
|
||||
n += 1
|
||||
return edges
|
||||
|
||||
|
||||
def _answer(sc, edges) -> bool:
|
||||
return checker.evaluate(sc.obs.entities, edges, Query(kind=sc.query.kind,
|
||||
a=sc.query.a, b=sc.query.b))
|
||||
|
||||
|
||||
def report(n: int = 32) -> None:
|
||||
"""Positive and negative recall are reported apart on purpose.
|
||||
|
||||
A graph with no relations answers "false" to every query, so a single
|
||||
"agreement" number would hand it the whole negative class for free. What M2
|
||||
needs to know is whether geometry alone can ever establish the positive.
|
||||
"""
|
||||
print(f"{'family':11s} {'真边':>5s} {'提取':>5s} {'真阳率':>6s} {'真阴率':>6s} "
|
||||
f"{'凭证':>5s} {'余隙':>5s}")
|
||||
print("-" * 54)
|
||||
for fam in generator.FAMILIES:
|
||||
n_true = n_false = hit_true = hit_false = cert_ok = 0
|
||||
got = truth = total = 0
|
||||
gap = float("inf")
|
||||
for i in range(n):
|
||||
sc = generator.make(fam, seed=3, index=i)
|
||||
if sc.query.edit is not None:
|
||||
continue
|
||||
edges = extract_edges(sc.obs.entities)
|
||||
boxes = [e.attrs["box"] for e in sc.obs.entities if e.attrs.get("box")]
|
||||
for p in range(len(boxes)):
|
||||
for q in range(p + 1, len(boxes)):
|
||||
g = surface_gap(boxes[p], boxes[q])
|
||||
if g > 0:
|
||||
gap = min(gap, g) # clearance, not the touching pairs
|
||||
total += 1
|
||||
truth += len(sc.obs.edges)
|
||||
got += len(edges)
|
||||
world = FullState(entities=list(sc.obs.entities), edges=edges)
|
||||
if _answer(sc, sc.obs.edges):
|
||||
n_true += 1
|
||||
hit_true += int(bool(_answer(sc, edges)))
|
||||
ev = checker.evidence_for(world, sc.query)
|
||||
cert_ok += int(bool(ev) and checker.validate_evidence(world, sc.query, ev))
|
||||
else:
|
||||
n_false += 1
|
||||
hit_false += int(not _answer(sc, edges))
|
||||
rec = f"{hit_true / n_true:6.2f}" if n_true else " —"
|
||||
neg = f"{hit_false / n_false:6.2f}" if n_false else " —"
|
||||
cert = f"{cert_ok / n_true:5.2f}" if n_true else " —"
|
||||
g = "—" if gap == float("inf") else f"{gap:.0f}"
|
||||
print(f"{fam:11s} {truth / max(1, total):5.1f} {got / max(1, total):5.1f} "
|
||||
f"{rec} {neg} {cert} {g:>5s}")
|
||||
print()
|
||||
print("真边 = 观测里的关系数;提取 = 只看几何能得到的关系数(共面精确匹配)")
|
||||
print("真阳率 = 真值为真的样本里几何图也判真的比例,即几何能不能自己证明")
|
||||
print("真阴率 = 真值为假的样本里几何图也判假的比例,零关系的图靠这一列刷分")
|
||||
print("凭证 = 真值为真的样本里,几何图给出的凭证能通过检查的比例")
|
||||
print("余隙 = 互不接触的零件表面之间的最小距离,说明有没有零件是悬空的")
|
||||
|
||||
|
||||
GAP_FAMILIES = (("area.sup2", 0), ("area.gap1", 1), ("area.gap2", 2), ("area.gap4", 4))
|
||||
# grid units. The last two entries are the abuse case: an eps of a quarter
|
||||
# millimetre is not a numerical epsilon any more, it is a design tolerance
|
||||
# wearing a numerical epsilon's name -- and the old failure comes straight back.
|
||||
DIST_TOLS = (0.0, 0.5, 1.0, 2.0, 4.0)
|
||||
NUM_EPS = (0.0, 1e-12, 1e-9, 1e-6, 1e-3, 0.25)
|
||||
|
||||
|
||||
def _panel(title: str, families, cols, extract, n: int) -> None:
|
||||
"""One sweep of the same four clearances under one extraction rule.
|
||||
|
||||
``cols`` is a list of (label, value): the label is what the header shows, the
|
||||
value is what the rule is actually called with.
|
||||
"""
|
||||
print(title)
|
||||
print(f" {'family':10s} {'间隙':>4s} " + " ".join(f"{c[0]:>9s}" for c in cols))
|
||||
for fam, gap in families:
|
||||
cells = []
|
||||
for _, val in cols:
|
||||
got = forged = total = 0
|
||||
for i in range(n):
|
||||
sc = generator.make(fam, seed=7, index=i)
|
||||
edges = extract(sc.obs.entities, val)
|
||||
world = FullState(entities=list(sc.obs.entities), edges=edges)
|
||||
tp = [e for e in edges if {e.a, e.b} == {"T", "P"}]
|
||||
total += 1
|
||||
if tp:
|
||||
got += 1
|
||||
forged += int(checker.validate_evidence(
|
||||
world, Query(kind="stability", a="T"), [tp[0].eid]))
|
||||
if gap == 0:
|
||||
cells.append(f"{got:2d}/{total} {'ok' if got else 'miss'}")
|
||||
elif not got:
|
||||
cells.append(f"{got:2d}/{total} -")
|
||||
else:
|
||||
cells.append(f"{got:2d}/{total} {'x' if not forged else '!'}")
|
||||
print(f" {fam:10s} {gap:4d} " + " ".join(f"{c:>9s}" for c in cells))
|
||||
print()
|
||||
|
||||
|
||||
def report_tolerance(n: int = 8) -> None:
|
||||
"""Does the contact rule decide anything by accident, and what does it cost.
|
||||
|
||||
Same four clearances, two extraction rules. For each cell: does an edge
|
||||
between the block and its (absent) pedestal appear, and does the checker
|
||||
accept that edge as a certificate. A rule that fuses two parts 0.25mm apart
|
||||
does not merely add noise -- it forges a support that validates, i.e. it
|
||||
turns a wrong graph into a wrong *proof*.
|
||||
"""
|
||||
_panel("距离阈值(第一版,tol 以格为单位扫)", GAP_FAMILIES,
|
||||
[(f"{t:.1f}", t) for t in DIST_TOLS],
|
||||
lambda ents, t: extract_edges_by_distance(ents, tol=t), n)
|
||||
_panel("共面精确匹配(第二版,eps 以坐标单位扫)", GAP_FAMILIES,
|
||||
[("0", 0.0), ("1e-12", 1e-12), ("1e-9", 1e-9), ("1e-6", 1e-6),
|
||||
("1e-3", 1e-3), ("1.0", 1.0)],
|
||||
lambda ents, e: extract_edges(ents, eps=e), n)
|
||||
print("单元格 = 提取到 T-P 边的样本数 / 总数")
|
||||
print("ok = 间隙为 0,零件本来就贴着,提取到了")
|
||||
print("miss = 间隙为 0 却没提取到(该报的没报)")
|
||||
print("- = 间隙 > 0,没有提取到边(正确)")
|
||||
print("x = 间隙 > 0 却焊出一条接触(这一步就把答案 false 翻成了 true),但凭证")
|
||||
print(" 校验自己复核几何后拒了它 —— 校验器只挡住了「错还能当证明用」")
|
||||
print("! = 假边连凭证校验都过了。现在不该出现,出现就是校验器回退了")
|
||||
print("间隙 = 上面那块被抬高的坐标单位数(夹具 per_unit=1,1 格即 1 单位)")
|
||||
print()
|
||||
print("两版差别就一条:距离法在 tol >= 间隙时必然焊出一个接触,容差因此是决定")
|
||||
print("答案的参数;共面法只看两张面是不是同一张面,eps 只盖浮点噪声,扫描从 1e-12")
|
||||
print("到 1e-3 一格都不动。最后一列 1.0 是把 eps 当容差用的滥用——旧坑原样回来,")
|
||||
print("这正说明它只能是数值兜底,不能是设计容差。")
|
||||
print()
|
||||
print("顺带修掉夹具自己的矛盾:近贴合家族原先一边把上面那块抬高 1/2/4 格,一边")
|
||||
print("还在 schema 里声明 T 和 P 接触。几何上没碰上就不存在这条边,所以现在只剩")
|
||||
print("真边 2 条、答案 false。也正因为少了那条边,任何跨越间隙的假接触都会让答案")
|
||||
print("从 false 变成 true —— 假边才第一次真的骗到了结论,而不只是画错了一条线。")
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
if argv and argv[0] == "tol":
|
||||
report_tolerance(int(argv[1]) if len(argv) > 1 else 8)
|
||||
else:
|
||||
report(int(argv[0]) if argv else 32)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,406 @@
|
||||
"""Procedural scenes.
|
||||
|
||||
Three domains, each built so that a *structure family* -- not a single sample --
|
||||
is the unit of split. Families differ in topology depth and in what the
|
||||
observation withholds, never in rendering noise, so a test family is genuinely
|
||||
unseen structure.
|
||||
|
||||
Builders only construct geometry and visible subsets. They never write a label:
|
||||
``checker.label`` does that, using the full state plus the world obtained by
|
||||
restricting the full state to what the observation shows.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from collections import Counter
|
||||
from dataclasses import replace
|
||||
|
||||
from . import checker
|
||||
from .schema import (DOF_AXES, Edge, Entity, FullState, Observation, Query,
|
||||
Scenario)
|
||||
|
||||
# family -> builder parameters. Splits are assigned in configs/*.json and must
|
||||
# be disjoint over families.
|
||||
FAMILIES = {
|
||||
"cond.p1": {"domain": "connection", "n_paths": 1, "hidden": 0},
|
||||
"cond.p3": {"domain": "connection", "n_paths": 3, "hidden": 0},
|
||||
"cond.p1h": {"domain": "connection", "n_paths": 2, "hidden": 1},
|
||||
"cond.p3h": {"domain": "connection", "n_paths": 4, "hidden": 1},
|
||||
# source conflicts. The dispute is drawn *within* the family and its
|
||||
# position is the causal variable: a branch is redundant once a second one
|
||||
# exists, the trunk never is. So the same scene shape yields true when the
|
||||
# dispute sits on a branch and unknown when it sits on the trunk -- which is
|
||||
# the rule the contract has to teach, and no constant answer fits it.
|
||||
"src.scope": {"domain": "connection", "n_paths_pick": (2, 3),
|
||||
"conflict_pick": (1, 3), "hidden": 0, "no_edit": 1},
|
||||
"src.clean": {"domain": "connection", "n_paths_pick": (0, 1, 2),
|
||||
"conflict": 0, "hidden": 0, "no_edit": 1},
|
||||
"src.scope4": {"domain": "connection", "n_paths": 4,
|
||||
"conflict_pick": (1, 3), "hidden": 0, "no_edit": 1},
|
||||
"area.sup2": {"domain": "stability", "n_blocks": 2, "hidden": 0},
|
||||
"area.sup3": {"domain": "stability", "n_blocks": 3, "hidden": 0},
|
||||
"area.sup2h": {"domain": "stability", "n_blocks": 2, "hidden": 1},
|
||||
"area.free": {"domain": "stability", "n_blocks": 2, "hidden": 0, "free": 1},
|
||||
"area.sup3h": {"domain": "stability", "n_blocks": 3, "hidden": 1},
|
||||
"area.sup2d": {"domain": "stability", "n_blocks": 2, "hidden": 0, "notch": 1},
|
||||
"area.gap1": {"domain": "stability", "n_blocks": 2, "hidden": 0, "clearance": 1},
|
||||
"area.gap2": {"domain": "stability", "n_blocks": 2, "hidden": 0, "clearance": 2},
|
||||
"area.gap4": {"domain": "stability", "n_blocks": 2, "hidden": 0, "clearance": 4},
|
||||
"area.near": {"domain": "stability", "n_blocks": 2, "hidden": 0, "near": 1},
|
||||
"dof.c6": {"domain": "freedom", "n_cons": 6, "hidden": 0},
|
||||
"dof.c6r": {"domain": "freedom", "n_cons": 7, "hidden": 0},
|
||||
"dof.c6h": {"domain": "freedom", "n_cons": 6, "hidden": 1},
|
||||
# the pure sub-skill: no intervention at all, so the answer is exactly "are
|
||||
# all six axes covered". If this family cannot be learned, the edit families
|
||||
# are not the problem -- the set readout is.
|
||||
"dof.c6d": {"domain": "freedom", "n_cons": 6, "hidden": 0, "notch": 1},
|
||||
"dof.set": {"domain": "freedom", "n_cons": 6, "hidden": 0, "no_edit": 1},
|
||||
}
|
||||
|
||||
DOMAIN_OF = {f: spec["domain"] for f, spec in FAMILIES.items()}
|
||||
|
||||
|
||||
def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, cameras,
|
||||
units, conflicts=()):
|
||||
vis_e = [e for e in edges if e.eid in visible_edges]
|
||||
keep = set(visible_ents) | {e.a for e in vis_e} | {e.b for e in vis_e}
|
||||
# derived, not hand-written: the gap between the full state and this view is
|
||||
# exactly what an agent has to know in order to decide it cannot decide.
|
||||
# Computing it here means a new occluder cannot silently go undeclared.
|
||||
hidden = {
|
||||
"entity": dict(Counter(e.kind for e in entities if e.eid not in keep)),
|
||||
"edge": dict(Counter(e.kind for e in edges if e.eid not in visible_edges)),
|
||||
}
|
||||
# a hidden relation with one visible end becomes a dangling edge anchored on
|
||||
# that visible end. Both ends hidden leaves no mouth to report, so it stays
|
||||
# a bare count. The anchor is always something already in view: this says
|
||||
# where the ignorance attaches, never where it leads.
|
||||
dangling = []
|
||||
for e in edges:
|
||||
if e.eid in visible_edges:
|
||||
continue
|
||||
anchor = e.a if e.a in keep else (e.b if e.b in keep else None)
|
||||
if anchor is None:
|
||||
continue
|
||||
dangling.append(Edge(f"d{len(dangling)}", e.kind, anchor, "",
|
||||
layer=e.layer, source="inferred"))
|
||||
# The same gap, stated the way a provider can actually state it: what the
|
||||
# inventory contains versus what was handed over. Counts and layer names,
|
||||
# no endpoints. ``hidden`` and ``dangling`` above stay for diagnostics and
|
||||
# as model features, but the label is decided from ``scope`` -- see
|
||||
# ``checker.withheld``.
|
||||
def _layers(items):
|
||||
return sorted({int(e.attrs.get("layer", 0)) for e in items})
|
||||
|
||||
scope = {
|
||||
"parts": dict(Counter(e.kind for e in entities)),
|
||||
"rendered": dict(Counter(e.kind for e in entities if e.eid in keep)),
|
||||
"relations": dict(Counter(e.kind for e in edges)),
|
||||
"rendered_relations": dict(Counter(e.kind for e in vis_e)),
|
||||
"layers": _layers(entities),
|
||||
"rendered_layers": _layers([e for e in entities if e.eid in keep]),
|
||||
"conflicts": dict(Counter(c["kind"] for c in conflicts)),
|
||||
}
|
||||
return Observation(
|
||||
entities=[e for e in entities if e.eid in keep],
|
||||
edges=vis_e,
|
||||
cameras=list(cameras),
|
||||
units=dict(units),
|
||||
hidden_layers=sorted(hidden_layers),
|
||||
hidden=hidden,
|
||||
dangling=dangling,
|
||||
conflicts=list(conflicts),
|
||||
scope=scope,
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# connection: parallel branches into one trunk, optional inner-layer branch
|
||||
#
|
||||
# A --branch i--> M --trunk--> B
|
||||
#
|
||||
# removing one branch is harmless while another exists; removing the trunk is
|
||||
# never harmless. With one visible branch and one hidden branch the observation
|
||||
# cannot tell those apart.
|
||||
|
||||
|
||||
def _build_connection(rng, n_paths: int, hidden: int, conflict: int = 0,
|
||||
no_edit: int = 0):
|
||||
ents = [Entity("A", "pad", attrs={"x": 0, "y": 0, "z": 0, "layer": 0}),
|
||||
Entity("B", "pad", attrs={"x": 100, "y": 0, "z": 0, "layer": 0}),
|
||||
Entity("M", "via", attrs={"x": 50, "y": 0, "z": 0, "layer": 0})]
|
||||
edges, visible, layers = [], set(), set()
|
||||
branch_edges = []
|
||||
for i in range(n_paths):
|
||||
is_hidden = i >= (n_paths - hidden)
|
||||
layer = (1 + i % 2) if is_hidden else 0
|
||||
vid = f"V{i}"
|
||||
ents.append(Entity(vid, "via", attrs={"x": 50, "y": 10 * (i + 1), "z": layer, "layer": layer}))
|
||||
e1 = Edge(f"c{i}a", "conduct", "A", vid, layer=layer)
|
||||
e2 = Edge(f"c{i}b", "conduct", vid, "M", layer=layer)
|
||||
edges += [e1, e2]
|
||||
if layer == 0:
|
||||
visible.update({e1.eid, e2.eid})
|
||||
branch_edges += [e1.eid, e2.eid]
|
||||
else:
|
||||
layers.add(layer)
|
||||
trunk = Edge("trunk", "conduct", "M", "B", layer=0)
|
||||
edges.append(trunk)
|
||||
visible.add(trunk.eid)
|
||||
|
||||
query = Query(kind="connection", a="A", b="B")
|
||||
# The source-conflict families stay edit-free on purpose: the query is about
|
||||
# what two observers disagree on, and an intervention would be a third
|
||||
# variable changing the answer at the same time.
|
||||
if not (conflict or no_edit):
|
||||
r = rng.random()
|
||||
if r < 0.4 and branch_edges:
|
||||
query.edit = {"op": "remove_edge", "edge": branch_edges[0]}
|
||||
elif r < 0.7:
|
||||
query.edit = {"op": "remove_edge", "edge": "trunk"}
|
||||
|
||||
# a hidden branch must not appear as an isolated node either: the mere
|
||||
# presence of a via on layer 1 is already a leak of the hidden detour
|
||||
vis_ents = {"A", "B", "M"} | {f"V{i}" for i in range(n_paths - hidden)}
|
||||
# A dispute is about one relation, named by its endpoints: the netlist says
|
||||
# A connects to V0, the board says there is no copper. Both edges of the
|
||||
# branch can be disputed at once, in which case neither world decides.
|
||||
conflicts = []
|
||||
if conflict:
|
||||
# 1 = one branch edge, 2 = both branch edges, 3 = the trunk. A disputed
|
||||
# branch is survivable while another branch exists; a disputed trunk is
|
||||
# not, because every path uses it.
|
||||
disputed = {1: ["c0a"], 2: ["c0a", "c0b"], 3: ["trunk"]}[int(conflict)]
|
||||
by_id = {e.eid: e for e in edges}
|
||||
for eid in disputed:
|
||||
e = by_id.get(eid)
|
||||
if e is not None:
|
||||
conflicts.append({"kind": e.kind, "a": e.a, "b": e.b,
|
||||
"against": "board", "with": "netlist"})
|
||||
return (ents, edges, query, visible, vis_ents, layers, ["top"],
|
||||
{"length": "mm", "per_unit": 1}, conflicts)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# stability: stacked blocks, optional hidden pedestal
|
||||
|
||||
|
||||
def _build_stability(rng, n_blocks: int, hidden: int, free: int = 0, notch: int = 0,
|
||||
clearance: int = 0, near: int = 0):
|
||||
if free:
|
||||
# the minimal pair against area.sup2h: here T has exactly one contact and
|
||||
# that contact leads to a block which itself hangs in the air. Nothing
|
||||
# dangles and nothing is hidden, so "no support" is a fact rather than a
|
||||
# gap -- the answer is legitimately false and abstaining would be wrong.
|
||||
ents = [Entity("G", "ground", attrs={"plane": 0}),
|
||||
Entity("T", "block", attrs={"box": [42, 42, 20, 58, 58, 36]}),
|
||||
Entity("Q", "block", attrs={"box": [44, 44, 8, 56, 56, 20]}),
|
||||
Entity("D", "block", attrs={"box": [80, 40, 0, 100, 60, 16]})]
|
||||
edges = [Edge("kTQ", "contact", "Q", "T"), Edge("kDG", "contact", "D", "G")]
|
||||
query = Query(kind="stability", a="T")
|
||||
if rng.random() < 0.6:
|
||||
query.edit = {"op": "remove_entity", "entity": "Q"}
|
||||
return (ents, edges, query, {e.eid for e in edges}, {e.eid for e in ents},
|
||||
set(), ["front", "iso"], {"length": "mm", "per_unit": 1})
|
||||
|
||||
# D is a decoy: it rests on the ground next to the stack and carries
|
||||
# nothing. Without it "something was removed" and "the target lost support"
|
||||
# are the same event on every sample, and a one-bit rule fits the whole
|
||||
# family -- measured: that rule scores 1.000 here while knowing no physics.
|
||||
# the causal variable is drawn, not fixed. Until it was, "there is a contact"
|
||||
# and "the contact carries load" were the same event inside the family, so a
|
||||
# constant answer fit it and the model never had to look at geometry -- which
|
||||
# is exactly what the report kept showing.
|
||||
dx = rng.choice((-13, -6, 0, 3, 6, 13))
|
||||
dy = rng.choice((-9, 0, 0, 0, 9))
|
||||
# clearance lifts the upper block off its pedestal by a few grid units (one
|
||||
# grid unit is 0.25mm). At 0 the two surfaces touch exactly; at 1 they are
|
||||
# 0.25mm apart, which is the regime real assemblies live in and the regime a
|
||||
# distance tolerance actually has to decide.
|
||||
# ``near`` draws the clearance inside one family: 0 sometimes, 1-2 units
|
||||
# otherwise. That is the whole point -- with a fixed clearance the family is
|
||||
# single-answer (constant rules score 1.000) and with a per-family fixed
|
||||
# clearance the model can key on the family instead of on contact. Here the
|
||||
# same question, same scene, same edge count differ only in whether the two
|
||||
# faces coincide, so the only thing that can separate them is contact.
|
||||
cl = int(clearance) if not near else int(rng.choice((0, 0, 0, 1, 2)))
|
||||
ents = [Entity("G", "ground", attrs={"plane": 0}),
|
||||
Entity("P", "block", attrs={"box": [40, 40, 0, 60, 60, 20]}),
|
||||
Entity("T", "block", attrs={"box": [42 + dx, 42 + dy, 20 + cl,
|
||||
58 + dx, 58 + dy, 36 + cl]}),
|
||||
Entity("D", "block", attrs={"box": [80, 40, 0, 100, 60, 16]})]
|
||||
edges = [Edge("kPG", "contact", "P", "G"), Edge("kDG", "contact", "D", "G")]
|
||||
if cl == 0:
|
||||
edges.append(Edge("kPT", "contact", "T", "P"))
|
||||
# With a clearance there is no contact, so the fixture must not declare one:
|
||||
# a kPT edge over a 1-unit gap would be the schema contradicting its own
|
||||
# geometry. Dropping it is what makes the near-fit families sharp -- any
|
||||
# spurious T-P edge now flips the answer false -> true instead of merely
|
||||
# adding a redundant edge.
|
||||
top = None
|
||||
if n_blocks >= 3:
|
||||
ents.append(Entity("U", "block",
|
||||
attrs={"box": [44 + dx, 44 + dy, 36 + cl, 56 + dx, 56 + dy, 48 + cl]}))
|
||||
edges.append(Edge("kTU", "contact", "U", "T"))
|
||||
top = "U"
|
||||
vis_edges = {e.eid for e in edges}
|
||||
vis_ents = {e.eid for e in ents}
|
||||
layers = set()
|
||||
|
||||
if hidden:
|
||||
# the pedestal sits behind the front face: its contacts are unseen, and
|
||||
# the pedestal itself is not in view
|
||||
for e in list(edges):
|
||||
if "P" in (e.a, e.b):
|
||||
vis_edges.discard(e.eid)
|
||||
vis_ents.discard("P")
|
||||
|
||||
if notch:
|
||||
# a decoy that is *itself* withheld, hanging off the ground and never off
|
||||
# the target: the visible structure still proves the target stands. This
|
||||
# is the case that makes "something is hidden" and "I cannot tell" two
|
||||
# different facts inside one family. Without it every hidden family is
|
||||
# all-unknown and keying on the hidden flag is a perfect answer.
|
||||
ents.append(Entity("H", "block", attrs={"box": [80, 70, -16, 100, 90, 0]}))
|
||||
edges.append(Edge("kHG", "contact", "H", "G"))
|
||||
vis_edges.discard("kHG")
|
||||
vis_ents.discard("H")
|
||||
|
||||
# the target is T on purpose: it survives every legal edit except the one
|
||||
# that removes P, so "removed something" no longer implies "answer false"
|
||||
query = Query(kind="stability", a="T")
|
||||
r = rng.random()
|
||||
if clearance or near:
|
||||
return ents, edges, query, vis_edges, vis_ents, layers, ["front", "iso"], {"length": "mm", "per_unit": 1}
|
||||
if not hidden:
|
||||
harmless = top or "D"
|
||||
if r < 0.4:
|
||||
query.edit = {"op": "remove_entity", "entity": "P"} # collapses
|
||||
elif r < 0.75:
|
||||
query.edit = {"op": "remove_entity", "entity": harmless} # no effect
|
||||
elif notch:
|
||||
# removing P takes the only visible proof away; the hidden decoy cannot
|
||||
# stand in for it, so the verdict becomes unknown rather than false
|
||||
if r < 0.5:
|
||||
query.edit = {"op": "remove_entity", "entity": "P"}
|
||||
return ents, edges, query, vis_edges, vis_ents, layers, ["front", "iso"], {"length": "mm", "per_unit": 1}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# freedom: constraint sets, optionally redundant on one axis
|
||||
|
||||
|
||||
def _build_freedom(rng, n_cons: int, hidden: int, no_edit: int = 0, notch: int = 0):
|
||||
# the axes are drawn, so a family spans both verdicts with the same entity
|
||||
# count: six mates that cover every axis lock the part, six that cover five
|
||||
# do not, and the difference is invisible from the shape of the scene
|
||||
axes = list(DOF_AXES)
|
||||
if n_cons == 7:
|
||||
rng.shuffle(axes)
|
||||
axes = axes + [rng.choice(axes)] # a redundant 7th mate, last
|
||||
else:
|
||||
if rng.random() < 0.5: # drop one, repeat another
|
||||
drop = rng.randrange(len(axes))
|
||||
dup = rng.choice([a for i, a in enumerate(axes) if i != drop])
|
||||
axes = [a for i, a in enumerate(axes) if i != drop] + [dup]
|
||||
rng.shuffle(axes)
|
||||
ents = [Entity("P", "part", attrs={"x": 0, "y": 0, "z": 0})]
|
||||
edges, visible = [], set()
|
||||
for i in range(n_cons):
|
||||
fid = f"F{i}"
|
||||
ents.append(Entity(fid, "ground", attrs={"x": 0, "y": 0, "z": 0}))
|
||||
e = Edge(f"k{i}", "constraint", "P", fid, attrs={"axis": axes[i]})
|
||||
edges.append(e)
|
||||
visible.add(e.eid)
|
||||
|
||||
vis_ents = {e.eid for e in ents}
|
||||
layers = set()
|
||||
if hidden:
|
||||
visible.discard("k5") # one mate lives in the part definition
|
||||
vis_ents.discard("F5")
|
||||
if notch:
|
||||
# a redundant mate kept outside the view: it dangles on the part, but the
|
||||
# visible mates already cover every axis, so the proof stands
|
||||
ents.append(Entity(f"F{n_cons}", "ground", attrs={"x": 0, "y": 0, "z": 0}))
|
||||
edges.append(Edge(f"k{n_cons}", "constraint", "P", f"F{n_cons}",
|
||||
attrs={"axis": rng.choice(list(DOF_AXES))}))
|
||||
visible.discard(f"k{n_cons}")
|
||||
vis_ents.discard(f"F{n_cons}")
|
||||
|
||||
query = Query(kind="freedom", a="P")
|
||||
if no_edit:
|
||||
return ents, edges, query, visible, vis_ents, layers, ["iso"], {"length": "mm", "per_unit": 1}
|
||||
if n_cons == 7:
|
||||
# removing the duplicate must not change the verdict; that is the point
|
||||
query.edit = {"op": "remove_edge", "edge": "k6"}
|
||||
elif rng.random() < 0.6:
|
||||
query.edit = {"op": "remove_edge", "edge": "k0"}
|
||||
return ents, edges, query, visible, vis_ents, layers, ["iso"], {"length": "mm", "per_unit": 1}
|
||||
|
||||
|
||||
_BUILDERS = {
|
||||
"connection": lambda rng, spec: _build_connection(rng, spec["n_paths"], spec["hidden"],
|
||||
spec.get("conflict", 0),
|
||||
spec.get("no_edit", 0)),
|
||||
"stability": lambda rng, spec: _build_stability(rng, spec["n_blocks"], spec["hidden"],
|
||||
spec.get("free", 0), spec.get("notch", 0),
|
||||
spec.get("clearance", 0),
|
||||
spec.get("near", 0)),
|
||||
"freedom": lambda rng, spec: _build_freedom(rng, spec["n_cons"], spec["hidden"],
|
||||
spec.get("no_edit", 0), spec.get("notch", 0)),
|
||||
}
|
||||
|
||||
|
||||
def make(family: str, seed: int, index: int = 0) -> Scenario:
|
||||
rng = random.Random(f"{family}:{seed}:{index}")
|
||||
spec = dict(FAMILIES[family])
|
||||
# a spec may say "draw this instead of fixing it": the draw happens per
|
||||
# sample, which is what makes the family two-label rather than one.
|
||||
for key in ("n_paths", "conflict"):
|
||||
pick = spec.pop(key + "_pick", None)
|
||||
if pick:
|
||||
spec[key] = rng.choice(list(pick))
|
||||
built = _BUILDERS[spec["domain"]](rng, spec)
|
||||
ents, edges, query, vis_edges, vis_ents, layers, cameras, units = built[:8]
|
||||
conflicts = built[8] if len(built) > 8 else []
|
||||
|
||||
full = FullState(entities=ents, edges=edges)
|
||||
obs = _observe(ents, edges, vis_edges, vis_ents, layers, cameras, units, conflicts)
|
||||
# the world the observation alone describes: anything not visible is gone
|
||||
restricted = FullState(entities=list(obs.entities), edges=list(obs.edges))
|
||||
|
||||
sc = Scenario(key=f"{family}-{seed}-{index:04d}", domain=spec["domain"],
|
||||
family=family, seed=seed, obs=obs, query=query, full=full,
|
||||
tags={"n_hidden": spec["hidden"], "edit": query.edit is not None})
|
||||
sc.label = checker.label(obs, full, query, alternatives=[restricted])
|
||||
return sc
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# invariances: camera and units must not change the answer
|
||||
|
||||
|
||||
def with_camera(sc: Scenario, camera: str) -> Scenario:
|
||||
out = replace(sc, obs=replace(sc.obs, cameras=[camera]))
|
||||
out.tags = dict(sc.tags, camera=camera)
|
||||
return out
|
||||
|
||||
|
||||
def rescale(sc: Scenario, factor: int, unit: str) -> Scenario:
|
||||
"""Multiply integer geometry by ``factor`` and relabel the unit. The answer
|
||||
must be invariant; the fixture checks that it actually is."""
|
||||
def scale_ent(e: Entity) -> Entity:
|
||||
attrs = dict(e.attrs)
|
||||
for k in ("x", "y", "z"):
|
||||
if k in attrs:
|
||||
attrs[k] = attrs[k] * factor
|
||||
if "box" in attrs:
|
||||
attrs["box"] = [v * factor for v in attrs["box"]]
|
||||
return replace(e, attrs=attrs, unit=unit)
|
||||
|
||||
full = FullState(entities=[scale_ent(e) for e in sc.full.entities], edges=list(sc.full.edges))
|
||||
obs = replace(sc.obs, entities=[scale_ent(e) for e in sc.obs.entities],
|
||||
edges=list(sc.obs.edges),
|
||||
units={"length": unit, "per_unit": factor})
|
||||
out = replace(sc, obs=obs, full=full, tags=dict(sc.tags, unit=unit, scale=factor))
|
||||
return out
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
"""Geometry primitives: points, boxes, faces, gaps.
|
||||
|
||||
No third-party dependencies on purpose. Everything here is a few dots and norms
|
||||
on hand-written tuples, because these modules have to run on machines where pip
|
||||
cannot install numpy, and the inputs are four boxes, not a mesh.
|
||||
|
||||
The one idea worth keeping straight: a *box* is not enough to talk about
|
||||
contact, because contact is a statement about **surfaces**. ``box_faces`` turns
|
||||
a box into six (axis, sign, plane, rect) records, which is the poor man's B-rep
|
||||
and the object every rule below is written against.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def _sub(u, v):
|
||||
return (u[0] - v[0], u[1] - v[1], u[2] - v[2])
|
||||
|
||||
|
||||
def _add(u, v):
|
||||
return (u[0] + v[0], u[1] + v[1], u[2] + v[2])
|
||||
|
||||
|
||||
def _mul(u, s):
|
||||
return (u[0] * s, u[1] * s, u[2] * s)
|
||||
|
||||
|
||||
def _dot(u, v):
|
||||
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]
|
||||
|
||||
|
||||
def _len(u):
|
||||
return _dot(u, u) ** 0.5
|
||||
|
||||
|
||||
def box_triangles(box) -> list:
|
||||
"""12 triangles for an axis-aligned box. Surface only, no interior.
|
||||
|
||||
Plain tuples on purpose: this module has to run on a machine that has no
|
||||
third-party packages at all, and the arithmetic here is a few dots and
|
||||
norms on four boxes. numpy would be the only dependency in the file.
|
||||
"""
|
||||
x0, y0, z0, x1, y1, z1 = (float(v) for v in box)
|
||||
c = [(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0),
|
||||
(x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)]
|
||||
faces = [(0, 2, 1), (0, 3, 2), (4, 5, 6), (4, 6, 7), (0, 1, 5), (0, 5, 4),
|
||||
(1, 2, 6), (1, 6, 5), (2, 3, 7), (2, 7, 6), (3, 0, 4), (3, 4, 7)]
|
||||
return [tuple(c[i] for i in f) for f in faces]
|
||||
|
||||
|
||||
def _pt_tri(p, tri) -> float:
|
||||
"""Distance from a point to a triangle (Ericson, clamped barycentric)."""
|
||||
a, b, c = tri
|
||||
ab, ac, ap = _sub(b, a), _sub(c, a), _sub(p, a)
|
||||
d1, d2 = _dot(ab, ap), _dot(ac, ap)
|
||||
if d1 <= 0 and d2 <= 0:
|
||||
return _len(ap)
|
||||
bp = _sub(p, b)
|
||||
d3, d4 = _dot(ab, bp), _dot(ac, bp)
|
||||
if d3 >= 0 and d4 <= d3:
|
||||
return _len(bp)
|
||||
vc = d1 * d4 - d3 * d2
|
||||
if vc <= 0 <= d1 and d3 <= 0:
|
||||
return _len(_sub(p, _add(a, _mul(ab, d1 / (d1 - d3)))))
|
||||
cp = _sub(p, c)
|
||||
d5, d6 = _dot(ab, cp), _dot(ac, cp)
|
||||
if d6 >= 0 and d5 <= d6:
|
||||
return _len(cp)
|
||||
vb = d5 * d2 - d1 * d6
|
||||
if vb <= 0 <= d2 and d6 <= 0:
|
||||
return _len(_sub(p, _add(a, _mul(ac, d2 / (d2 - d6)))))
|
||||
va = d3 * d6 - d5 * d4
|
||||
if va <= 0 and (d4 - d3) >= 0 and (d5 - d6) >= 0:
|
||||
w = (d4 - d3) / ((d4 - d3) + (d5 - d6))
|
||||
return _len(_sub(p, _add(b, _mul(_sub(c, b), w))))
|
||||
denom = 1.0 / (va + vb + vc)
|
||||
return _len(_sub(p, _add(a, _add(_mul(ab, vb * denom), _mul(ac, vc * denom)))))
|
||||
|
||||
|
||||
def _aabb_gap(a, b) -> float:
|
||||
"""Lower bound on the surface distance -- used only as a cheap prefilter."""
|
||||
dx = max(0.0, max(a[0] - b[3], b[0] - a[3]))
|
||||
dy = max(0.0, max(a[1] - b[4], b[1] - a[4]))
|
||||
dz = max(0.0, max(a[2] - b[5], b[2] - a[5]))
|
||||
return (dx * dx + dy * dy + dz * dz) ** 0.5
|
||||
|
||||
|
||||
def box_faces(box) -> list:
|
||||
"""The six faces of an axis-aligned box as (axis, sign, plane, rect2d).
|
||||
|
||||
``rect2d`` is the face's extent in the two axes it spans, in ascending order.
|
||||
This is the poor man's B-rep: faces are stored as *surfaces*, not as vertex
|
||||
triples, because contact is a statement about surfaces.
|
||||
"""
|
||||
x0, y0, z0, x1, y1, z1 = (float(v) for v in box)
|
||||
lo, hi = (x0, y0, z0), (x1, y1, z1)
|
||||
out = []
|
||||
for ax in range(3):
|
||||
u, v = [i for i in range(3) if i != ax]
|
||||
rect = (lo[u], lo[v], hi[u], hi[v])
|
||||
out.append((ax, -1, lo[ax], rect))
|
||||
out.append((ax, +1, hi[ax], rect))
|
||||
return out
|
||||
|
||||
|
||||
def contact_area(fa, fb, eps: float = 0.0) -> float:
|
||||
"""Overlap area of two faces if they are coincident, else 0.
|
||||
|
||||
Coincident means: same plane orientation (same axis, opposite outward
|
||||
normals -- two faces pointing the same way are facing each other, not
|
||||
touching) and the same offset along that axis, up to ``eps``, which only
|
||||
has to absorb floating-point noise from transforms. Line and point contacts
|
||||
(zero overlap area) are deliberately *not* contacts: in a B-rep they are a
|
||||
separate topological case and pretending a rectangle of zero width is a
|
||||
surface would be the same mistake as the distance threshold.
|
||||
"""
|
||||
ax, sa, pa, ra = fa
|
||||
bx, sb, pb, rb = fb
|
||||
if ax != bx or sa == sb or abs(pa - pb) > eps:
|
||||
return 0.0
|
||||
ou = min(ra[2], rb[2]) - max(ra[0], rb[0])
|
||||
ov = min(ra[3], rb[3]) - max(ra[1], rb[1])
|
||||
if ou <= 0 or ov <= 0:
|
||||
return 0.0
|
||||
return ou * ov
|
||||
|
||||
|
||||
def box_contact_area(box_a, box_b, eps: float = 0.0) -> float:
|
||||
best = 0.0
|
||||
for fa in box_faces(box_a):
|
||||
for fb in box_faces(box_b):
|
||||
a = contact_area(fa, fb, eps)
|
||||
if a > best:
|
||||
best = a
|
||||
return best
|
||||
|
||||
|
||||
def surface_gap(box_a, box_b) -> float:
|
||||
"""Minimum distance between two box surfaces, measured on triangles.
|
||||
|
||||
Vertex-to-triangle only: edge-to-edge minima are missed, which can overestimate
|
||||
the gap when two edges cross without a vertex near the contact. For the
|
||||
separation this benchmark actually has (>=16 grid units) it never matters --
|
||||
and that "never matters" is itself one of the findings.
|
||||
|
||||
Kept for the clearance column only. Contact is decided by ``contact_area``,
|
||||
which needs no distance at all.
|
||||
"""
|
||||
ta, tb = box_triangles(box_a), box_triangles(box_b)
|
||||
va, vb = _vertices(ta), _vertices(tb)
|
||||
best = float("inf")
|
||||
for tri in ta:
|
||||
for p in vb:
|
||||
best = min(best, _pt_tri(p, tri))
|
||||
for tri in tb:
|
||||
for p in va:
|
||||
best = min(best, _pt_tri(p, tri))
|
||||
return best
|
||||
|
||||
|
||||
def _vertices(tris) -> list:
|
||||
seen, out = set(), []
|
||||
for tri in tris:
|
||||
for p in tri:
|
||||
if p not in seen:
|
||||
seen.add(p)
|
||||
out.append(p)
|
||||
return out
|
||||
@@ -0,0 +1,414 @@
|
||||
"""Bidirectional relation backbone (deliberately small).
|
||||
|
||||
Differences from ``mm/model.py``, and why they are not negotiable here:
|
||||
|
||||
* **no causal mask** -- a query may sit on any entity and relations are
|
||||
symmetric; an autoregressive mask would make the answer depend on an
|
||||
arbitrary serialisation order.
|
||||
* **no positional encoding** -- entity order in a scene carries no meaning, so
|
||||
the only ordering signal is structural: a learned bias indexed by graph
|
||||
hop distance. Renumbering the scene must not move the output.
|
||||
* **edge types are attention biases *and* values** -- a bias alone says "look
|
||||
this way" but never tells the token *what* the relation is (layer, contact
|
||||
area, which axis a mate locks). Edge content is folded into the value stream
|
||||
so an entity actually receives its incident relations.
|
||||
* **one query token, not a token per entity** -- the output is about a query,
|
||||
not about the next token.
|
||||
* **one unknown slot** -- a dangling relation (one end visible, one end not)
|
||||
points at a single dedicated token instead of at an entity. A chain that ends
|
||||
there is a chain that ends in a question, which is what "I cannot decide this"
|
||||
has to look like in the input.
|
||||
* **two rounds of read-out** -- round 1 selects a few edges as a candidate
|
||||
certificate, round 2 lets every entity attend to those edges. This is the
|
||||
cheap version of "grab evidence, then decide"; without it the evidence head
|
||||
and the answer head never see the same object.
|
||||
* **a learned temperature** -- the answer/change/evidence logits are divided by
|
||||
``exp(log_temp)``, so "unknown" is a decision made on a calibrated scale
|
||||
rather than the argmax of an over-confident 3-way classifier.
|
||||
|
||||
The size is a smoke-test size (2 layers, 64 wide). The plan's 6/384 is a
|
||||
config change; nothing in this file assumes 64.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from .schema import DOF_AXES, EDGE_KINDS, ENTITY_KINDS
|
||||
|
||||
N_KIND = len(ENTITY_KINDS)
|
||||
N_EDGE = len(EDGE_KINDS)
|
||||
N_AXIS = len(DOF_AXES)
|
||||
FEAT_DIM = N_KIND + 2 + 3 + 7 # kind, source, unit, (x,y,z,layer,w,h,d)
|
||||
# type one-hot, axis one-hot, removed flag, layer, contact area, dangling flag,
|
||||
# then the three local predicates a contact needs before it can carry load:
|
||||
# do the faces meet in z, is the upper block's centroid inside the overlap, and
|
||||
# how much of the upper footprint is covered. They are measurements, not
|
||||
# answers -- the same numbers a caliper and a straight edge would give.
|
||||
# The last slot is the disputed flag: two sources name this relation and
|
||||
# disagree. Without it a disputed edge and an agreed edge are the same input, and
|
||||
# "the proof goes through the disputed wire" is unlearnable.
|
||||
EDGE_FEAT_DIM = N_EDGE + N_AXIS + 4 + 3 + 1
|
||||
QUERY_KINDS = ("connection", "stability", "freedom")
|
||||
|
||||
HOP_MAX = 4 # longer paths collapse into one bucket
|
||||
FAR = HOP_MAX + 1 # unreachable, or "involves the query token"
|
||||
# what the observation admits it is missing: hidden layer markers, unseen faces,
|
||||
# one count per entity kind and per edge kind, an "anything withheld" bit, and
|
||||
# the scene size. Without this the two worlds "no hidden branch exists" and "a
|
||||
# hidden branch exists off-view" are literally the same tensor, and no amount of
|
||||
# reasoning can separate them.
|
||||
SCENE_DIM = 4 + N_KIND + N_EDGE + 2 + 4
|
||||
# the first block is derived from the full state (what is hidden by kind);
|
||||
# the last four are derived from the declared inventory (scope), which a real
|
||||
# provider can state without endpoints. They live in separate slices so an
|
||||
# ablation can remove one without touching the other.
|
||||
SCENE_HIDDEN = slice(0, 4 + N_KIND + N_EDGE + 2)
|
||||
|
||||
UNK = 1 # position of the unknown slot
|
||||
ENT0 = 2 # first entity position
|
||||
|
||||
|
||||
def hop_distance(edge_index, edge_mask, edge_removed, n_ent: int) -> torch.Tensor:
|
||||
"""Truncated all-pairs shortest path over the *post-intervention* graph.
|
||||
|
||||
A removed edge is not traversed: the question "still connected after cutting
|
||||
the trunk" is about the graph after the cut, and a hop count that still
|
||||
walks through the cut edge is a lie the model would have to unlearn.
|
||||
"""
|
||||
device = edge_index.device
|
||||
B = edge_index.size(0)
|
||||
ar = torch.arange(B, device=device)
|
||||
adj = torch.zeros(B, n_ent, n_ent, dtype=torch.bool, device=device)
|
||||
live = edge_mask if edge_removed is None else (edge_mask & (edge_removed < 0.5))
|
||||
for k in range(edge_index.size(1)):
|
||||
m = live[:, k]
|
||||
if not m.any():
|
||||
continue
|
||||
b = ar[m]
|
||||
s = edge_index[m, k, 0].clamp(min=0, max=n_ent - 1)
|
||||
t = edge_index[m, k, 1].clamp(min=0, max=n_ent - 1)
|
||||
adj[b, s, t] = True
|
||||
adj[b, t, s] = True
|
||||
|
||||
dist = torch.full((B, n_ent, n_ent), FAR, dtype=torch.long, device=device)
|
||||
idx = torch.arange(n_ent, device=device)
|
||||
dist[:, idx, idx] = 0
|
||||
dist = torch.where(adj, torch.ones_like(dist), dist)
|
||||
reach = adj.clone()
|
||||
front = adj.clone()
|
||||
for d in range(2, HOP_MAX + 1):
|
||||
front = (torch.bmm(front.float(), adj.float()) > 0) & ~reach
|
||||
reach = reach | front
|
||||
dist = torch.where(front, torch.full_like(dist, d), dist)
|
||||
return dist
|
||||
|
||||
|
||||
class Block(nn.Module):
|
||||
def __init__(self, d: int, n_head: int, dropout: float = 0.0):
|
||||
super().__init__()
|
||||
self.n_head = n_head
|
||||
self.ln1 = nn.LayerNorm(d)
|
||||
self.qkv = nn.Linear(d, 3 * d, bias=False)
|
||||
self.proj = nn.Linear(d, d, bias=False)
|
||||
self.ln2 = nn.LayerNorm(d)
|
||||
self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
|
||||
self.drop = nn.Dropout(dropout)
|
||||
|
||||
def forward(self, x, bias, pad_mask, v_extra=None):
|
||||
B, T, d = x.shape
|
||||
h = self.ln1(x)
|
||||
q, k, v = self.qkv(h).view(B, T, 3, self.n_head, d // self.n_head).permute(2, 0, 3, 1, 4)
|
||||
if v_extra is not None:
|
||||
# the relations an entity touches, injected straight into its value:
|
||||
# edge type as attention bias only says "look there", not "it is a
|
||||
# 0.8 mm2 contact on layer 2"
|
||||
v = v + v_extra.view(B, T, self.n_head, d // self.n_head).permute(0, 2, 1, 3)
|
||||
att = (q @ k.transpose(-2, -1)) / math.sqrt(d // self.n_head)
|
||||
att = att + bias
|
||||
att = att.masked_fill(pad_mask[:, None, None, :], float("-inf"))
|
||||
att = self.drop(att.softmax(dim=-1))
|
||||
y = (att @ v).transpose(1, 2).reshape(B, T, d)
|
||||
x = x + self.drop(self.proj(y))
|
||||
x = x + self.drop(self.mlp(self.ln2(x)))
|
||||
return x
|
||||
|
||||
|
||||
class RelationBackbone(nn.Module):
|
||||
def __init__(self, d: int = 64, n_layer: int = 2, n_head: int = 4,
|
||||
dropout: float = 0.0, max_entities: int = 32,
|
||||
rounds: int = 2, n_evidence: int = 4):
|
||||
super().__init__()
|
||||
self.d = d
|
||||
self.n_head = n_head
|
||||
self.max_entities = max_entities
|
||||
self.rounds = max(1, rounds)
|
||||
self.n_evidence = max(0, n_evidence)
|
||||
|
||||
self.ent_proj = nn.Sequential(nn.Linear(FEAT_DIM, d), nn.GELU(), nn.Linear(d, d))
|
||||
self.edge_proj = nn.Sequential(nn.Linear(EDGE_FEAT_DIM, d), nn.GELU(), nn.Linear(d, d))
|
||||
# a linear path for edge content, alongside the nonlinear one. "Are all
|
||||
# six axes locked" is a statement about the cardinality of a set, and the
|
||||
# sum of a *nonlinear* projection of one-hots is no longer a count --
|
||||
# GELU mixes the axes and the bag loses which of them it saw. The linear
|
||||
# skip keeps the sum an exact count vector, so a threshold can read it.
|
||||
self.edge_lin = nn.Linear(EDGE_FEAT_DIM, d, bias=False)
|
||||
self.scene_proj = nn.Sequential(nn.Linear(SCENE_DIM, d), nn.GELU(), nn.Linear(d, d))
|
||||
self.unk_tok = nn.Parameter(torch.zeros(d))
|
||||
self.query_emb = nn.Embedding(len(QUERY_KINDS), d)
|
||||
# the relations attached to the entity the question names, delivered to
|
||||
# the question directly. Letting the query pick them up through attention
|
||||
# means averaging them with a dozen unrelated positions, and "are all six
|
||||
# axes locked" is a conjunction of six per-axis thresholds -- measured: at
|
||||
# chance (0.49) even on a single family, with the training loss stuck at
|
||||
# ln 2. The bag of incident relations is the evidence the question asks
|
||||
# for; it should not have to survive a softmax to arrive.
|
||||
self.q_inc = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, d))
|
||||
self.edit_op_emb = nn.Embedding(3, d) # none / remove_edge / remove_entity
|
||||
# direction matters: a constraint points from the part to the fixture, a
|
||||
# conduct edge from source to sink. Two tables, not one symmetric table.
|
||||
self.edge_bias = nn.Parameter(torch.zeros(N_EDGE, n_head))
|
||||
self.edge_bias_inv = nn.Parameter(torch.zeros(N_EDGE, n_head))
|
||||
self.none_bias = nn.Parameter(torch.zeros(n_head))
|
||||
# the intervention as an edge flag: a global token tells the model that
|
||||
# something was removed, not which edge, and the evidence head needs the
|
||||
# latter to exclude the removed edge from its certificate
|
||||
self.removed_bias = nn.Parameter(torch.zeros(n_head))
|
||||
self.dangling_bias = nn.Parameter(torch.zeros(n_head))
|
||||
# structural order, not positional order: one bias per hop bucket
|
||||
self.hop_bias = nn.Parameter(torch.zeros(HOP_MAX + 2, n_head))
|
||||
|
||||
self.blocks = nn.ModuleList([Block(d, n_head, dropout) for _ in range(n_layer)])
|
||||
self.ln_f = nn.LayerNorm(d)
|
||||
|
||||
self.answer_head = nn.Linear(d, 3)
|
||||
self.change_head = nn.Linear(d, 3)
|
||||
self.answer_round = nn.Embedding(self.rounds, d)
|
||||
self.evidence_head = nn.Sequential(nn.Linear(2 * d, d), nn.GELU(), nn.Linear(d, 1))
|
||||
# the evidence head used to see only the two endpoint embeddings, so it
|
||||
# could not tell a removed edge from a live one. Edge identity has to be
|
||||
# part of the score, not just part of the attention bias.
|
||||
self.edge_emb = nn.Embedding(N_EDGE, d)
|
||||
self.removed_emb = nn.Embedding(2, d)
|
||||
self.ev_proj = nn.Linear(EDGE_FEAT_DIM, d)
|
||||
self.round_emb = nn.Embedding(max(1, self.rounds - 1), d)
|
||||
|
||||
# calibration: logits / exp(log_temp). Learned, not tuned on a split, so
|
||||
# the temperature is supervised by the same labels as the heads.
|
||||
self.log_temp = nn.Parameter(torch.zeros(1))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
def _hop_matrix(self, dist_ent, anchor, top, edge_index, n_ent: int, K: int) -> torch.Tensor:
|
||||
"""(B, T, T) hop buckets over *positions*, not entity indices.
|
||||
|
||||
The unknown slot sits one hop from every entity that has a dangling
|
||||
relation anchored on it, and is far from everything else. That is the
|
||||
whole point of the slot: "the chain continues, but not visibly".
|
||||
"""
|
||||
B = dist_ent.size(0)
|
||||
device = dist_ent.device
|
||||
T = ENT0 + n_ent + K
|
||||
hop = torch.full((B, T, T), FAR, dtype=torch.long, device=device)
|
||||
hop[:, ENT0:ENT0 + n_ent, ENT0:ENT0 + n_ent] = dist_ent
|
||||
hop[:, 0, 0] = 0
|
||||
hop[:, UNK, UNK] = 0
|
||||
one = torch.ones(B, n_ent, dtype=torch.long, device=device)
|
||||
d_unk = torch.where(anchor, one, torch.full_like(one, FAR))
|
||||
hop[:, UNK, ENT0:ENT0 + n_ent] = d_unk
|
||||
hop[:, ENT0:ENT0 + n_ent, UNK] = d_unk
|
||||
if K == 0:
|
||||
return hop
|
||||
slots = torch.arange(ENT0 + n_ent, T, device=device)
|
||||
hop[:, slots, slots] = 0
|
||||
if top is not None:
|
||||
ar = torch.arange(B, device=device)
|
||||
sel = edge_index[ar.unsqueeze(1), top.clamp(min=0)] # (B, K, 2), entity space
|
||||
ok = sel < n_ent # false for the unknown end
|
||||
safe = sel.clamp(min=0, max=n_ent - 1)
|
||||
far = torch.full((B, K, n_ent), FAR, dtype=torch.long, device=device)
|
||||
da = dist_ent.gather(2, safe[..., 0].unsqueeze(-1).expand(B, K, n_ent))
|
||||
db = dist_ent.gather(2, safe[..., 1].unsqueeze(-1).expand(B, K, n_ent))
|
||||
d = torch.minimum(torch.where(ok[..., 0:1], da, far), torch.where(ok[..., 1:2], db, far))
|
||||
d = torch.where(d >= FAR, far, d + 1).clamp(max=FAR)
|
||||
hop[:, slots, ENT0:ENT0 + n_ent] = d
|
||||
hop[:, ENT0:ENT0 + n_ent, slots] = d.transpose(1, 2)
|
||||
return hop
|
||||
|
||||
def _bias(self, pos, edge_type, edge_mask, edge_removed, dangling, hop):
|
||||
"""(B, n_head, T, T) additive attention bias, built in (B,T,T,H) so the
|
||||
advanced indexing below is unambiguous."""
|
||||
B, T, _ = hop.shape
|
||||
H = self.n_head
|
||||
bias = self.none_bias.view(1, 1, 1, H).expand(B, T, T, H).clone()
|
||||
bias = bias + self.hop_bias[hop]
|
||||
|
||||
src, dst = pos[..., 0], pos[..., 1]
|
||||
bidx = torch.arange(B, device=pos.device).unsqueeze(1).expand_as(src)
|
||||
|
||||
# accumulate through a flat linear index: parallel edges between the same
|
||||
# pair of nodes hit the same cell, and fancy-index assignment would keep
|
||||
# only the last of them
|
||||
flat = bias.view(-1, H)
|
||||
|
||||
def add(mask, vec, flip=False):
|
||||
if not mask.any():
|
||||
return
|
||||
b_, s_, d_ = bidx[mask], src[mask], dst[mask]
|
||||
if flip:
|
||||
s_, d_ = d_, s_
|
||||
lin = b_ * (T * T) + s_ * T + d_
|
||||
flat.index_put_((lin,), vec.expand(lin.size(0), H), accumulate=True)
|
||||
|
||||
for t in range(N_EDGE):
|
||||
m = (edge_type == t) & edge_mask
|
||||
add(m, self.edge_bias[t])
|
||||
add(m, self.edge_bias_inv[t], flip=True)
|
||||
if edge_removed is not None:
|
||||
rm = (edge_removed > 0) & edge_mask
|
||||
add(rm, self.removed_bias)
|
||||
add(rm, self.removed_bias, flip=True)
|
||||
if dangling is not None:
|
||||
add((dangling > 0) & edge_mask, self.dangling_bias)
|
||||
return bias.permute(0, 3, 1, 2)
|
||||
|
||||
def _evidence(self, x, pos, edge_type, edge_removed, edge_feat_emb, q_out):
|
||||
B, T, _ = x.shape
|
||||
ar = torch.arange(B, device=x.device).unsqueeze(1)
|
||||
ea = x[ar, pos[..., 0].clamp(min=0, max=T - 1)]
|
||||
eb = x[ar, pos[..., 1].clamp(min=0, max=T - 1)]
|
||||
e_feat = self.edge_emb(edge_type)
|
||||
if edge_removed is not None:
|
||||
e_feat = e_feat + self.removed_emb((edge_removed > 0).long())
|
||||
# endpoints + query + the edge's own content: without the last term the
|
||||
# head cannot exclude a removed edge from its own certificate, and
|
||||
# without the dangling flag it cannot tell a support from a question
|
||||
pair = torch.cat([ea + eb + e_feat + edge_feat_emb,
|
||||
q_out.unsqueeze(1).expand(-1, ea.size(1), -1)], dim=-1)
|
||||
return self.evidence_head(pair).squeeze(-1)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
def forward(self, feat, pad_mask, edge_index, edge_type, edge_mask, q_ents, q_kind,
|
||||
edit_op=None, edit_idx=None, edge_removed=None, edge_feat=None, scene=None,
|
||||
dangling=None):
|
||||
B, n_ent, _ = feat.shape
|
||||
E = edge_index.size(1)
|
||||
device = feat.device
|
||||
K = min(self.n_evidence, E) if self.rounds > 1 else 0
|
||||
ar = torch.arange(B, device=device)
|
||||
|
||||
if edge_feat is None:
|
||||
edge_feat = torch.zeros(B, E, EDGE_FEAT_DIM, device=device)
|
||||
if dangling is None:
|
||||
dangling = torch.zeros(B, E, device=device)
|
||||
|
||||
# an edge endpoint is either an entity (entity index < n_ent) or the
|
||||
# unknown slot; mapping to positions once keeps every downstream use --
|
||||
# bias, hop, evidence -- reading the same coordinates
|
||||
pos = torch.where(edge_index < n_ent, edge_index + ENT0,
|
||||
torch.full_like(edge_index, UNK))
|
||||
has_unk = (dangling > 0) & edge_mask
|
||||
anchor = torch.zeros(B, n_ent, dtype=torch.bool, device=device)
|
||||
if has_unk.any():
|
||||
b_ = ar.unsqueeze(1).expand(B, E)[has_unk]
|
||||
e_ = edge_index[..., 0][has_unk].clamp(min=0, max=n_ent - 1)
|
||||
anchor.index_put_((b_, e_), torch.ones(b_.size(0), dtype=torch.bool, device=device))
|
||||
unk_absent = ~anchor.any(dim=1) # no mouth: the slot is not shown
|
||||
|
||||
h = self.ent_proj(feat)
|
||||
ef = self.edge_proj(edge_feat) # edge content, (B, E, d)
|
||||
|
||||
# fold incident edge content into each entity's value. Incidence is built
|
||||
# as a dense (B,N,E) matrix and applied as one matmul: it keeps the
|
||||
# backward pass simple and it makes "an entity receiving three edges sums
|
||||
# three vectors" obvious. Dangling edges are excluded: their far end is
|
||||
# not an entity, and pretending otherwise would credit an arbitrary node
|
||||
# with a relation it does not have. Removed edges are excluded too, for
|
||||
# the same reason the hop distance excludes them: the question is about
|
||||
# the graph after the cut, and an entity whose value still sums a cut
|
||||
# constraint has to un-learn it before it can answer.
|
||||
inc = torch.zeros(B, n_ent, E, device=device)
|
||||
cols = torch.arange(E, device=device).view(1, E).expand(B, E)
|
||||
ones = torch.ones_like(cols, dtype=inc.dtype)
|
||||
inc.index_put_((ar.unsqueeze(1).expand(B, E),
|
||||
edge_index[..., 0].clamp(min=0, max=n_ent - 1), cols), ones)
|
||||
inc.index_put_((ar.unsqueeze(1).expand(B, E),
|
||||
edge_index[..., 1].clamp(min=0, max=n_ent - 1), cols), ones)
|
||||
live = edge_mask & ~has_unk
|
||||
if edge_removed is not None:
|
||||
live = live & ~(edge_removed > 0)
|
||||
inc = inc * live.unsqueeze(1).to(inc.dtype)
|
||||
msg = torch.bmm(inc, ef) + torch.bmm(inc, self.edge_lin(edge_feat))
|
||||
|
||||
# query token is read out of the two entities it names
|
||||
q = self.query_emb(q_kind).unsqueeze(1).expand(B, 1, self.d).clone()
|
||||
valid_a = (q_ents[:, 0] >= 0).unsqueeze(-1)
|
||||
valid_b = (q_ents[:, 1] >= 0).unsqueeze(-1)
|
||||
a_idx = q_ents[:, 0].clamp(min=0)
|
||||
b_idx = q_ents[:, 1].clamp(min=0)
|
||||
q = q + torch.where(valid_a.unsqueeze(-1), h[ar, a_idx].unsqueeze(1), torch.zeros_like(q))
|
||||
q = q + torch.where(valid_b.unsqueeze(-1), h[ar, b_idx].unsqueeze(1), torch.zeros_like(q))
|
||||
# and the relations hanging off those entities, without the detour
|
||||
q = q + torch.where(valid_a.unsqueeze(-1),
|
||||
self.q_inc(msg[ar, a_idx]).unsqueeze(1), torch.zeros_like(q))
|
||||
q = q + torch.where(valid_b.unsqueeze(-1),
|
||||
self.q_inc(msg[ar, b_idx]).unsqueeze(1), torch.zeros_like(q))
|
||||
|
||||
# the intervention itself: which edge or entity the question removes
|
||||
if edit_op is not None and edit_idx is not None:
|
||||
# separate clamps: an entity index can exceed the padded edge count
|
||||
tgt_ent = h[ar, edit_idx.clamp(min=0, max=n_ent - 1)]
|
||||
pair = edge_index[ar, edit_idx.clamp(min=0, max=E - 1)]
|
||||
tgt_edge = h[ar, pair[:, 0].clamp(min=0, max=n_ent - 1)] + \
|
||||
h[ar, pair[:, 1].clamp(min=0, max=n_ent - 1)]
|
||||
tgt = torch.where((edit_op == 1).unsqueeze(-1), tgt_edge, tgt_ent)
|
||||
has = (edit_op > 0).unsqueeze(-1).to(q.dtype)
|
||||
q = q + self.edit_op_emb(edit_op).unsqueeze(1) + (tgt * has).unsqueeze(1)
|
||||
|
||||
# what the observation says it cannot see is part of the question, not a
|
||||
# property of any entity, so it rides on the query token where every
|
||||
# entity can attend to it
|
||||
if scene is not None:
|
||||
q = q + self.scene_proj(scene).unsqueeze(1)
|
||||
|
||||
unk = self.unk_tok.view(1, 1, self.d).expand(B, 1, self.d)
|
||||
zeros_ev = torch.zeros(B, K, self.d, device=device)
|
||||
x_tok = torch.cat([q, unk, h, zeros_ev], dim=1) # (B, 2+N+K, d)
|
||||
v_extra = torch.cat([torch.zeros(B, 2, self.d, device=device), msg, zeros_ev], dim=1)
|
||||
pad = torch.cat([torch.zeros(B, 2, dtype=torch.bool, device=device),
|
||||
pad_mask, torch.ones(B, K, dtype=torch.bool, device=device)], dim=1)
|
||||
pad[:, UNK] = unk_absent # no dangling relation: no unknown slot
|
||||
|
||||
dist = hop_distance(edge_index, edge_mask & ~has_unk, edge_removed, n_ent)
|
||||
top = None
|
||||
ev_logits = None
|
||||
q_out = None
|
||||
temp = torch.exp(-self.log_temp)
|
||||
|
||||
for r in range(self.rounds):
|
||||
hop = self._hop_matrix(dist, anchor, top, edge_index, n_ent, K)
|
||||
bias = self._bias(pos, edge_type, edge_mask, edge_removed, dangling, hop)
|
||||
x = x_tok
|
||||
for blk in self.blocks:
|
||||
x = blk(x, bias, pad, v_extra)
|
||||
x = self.ln_f(x)
|
||||
q_out = x[:, 0] + self.answer_round.weight[r]
|
||||
ev_logits = self._evidence(x, pos, edge_type, edge_removed, ef, q_out)
|
||||
if r + 1 < self.rounds and K > 0:
|
||||
# round 1 hands back the strongest candidate edges as tokens, so
|
||||
# every entity can attend to the certificate it is part of
|
||||
top = ev_logits.detach().masked_fill(~edge_mask, float("-inf")).topk(K, -1).indices
|
||||
filled = torch.cat([edge_mask.gather(1, top[:, kk:kk + 1]) for kk in range(K)], 1)
|
||||
x_tok = torch.cat([x_tok[:, :ENT0 + n_ent],
|
||||
self.ev_proj(edge_feat[ar.unsqueeze(1), top.clamp(min=0)])
|
||||
+ self.round_emb.weight[r]], dim=1)
|
||||
pad = torch.cat([pad[:, :ENT0 + n_ent], ~filled], dim=1)
|
||||
|
||||
return {
|
||||
"answer": self.answer_head(q_out) * temp,
|
||||
"change": self.change_head(q_out) * temp,
|
||||
"evidence": ev_logits * temp,
|
||||
"temp": temp.detach(),
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
"""输入 provider:把真实来源翻译成 ``Observation``。
|
||||
|
||||
几何一类在 ``spatial/extract.py``(从盒子/面推接触),元数据一类在这里。
|
||||
两者的产物形状相同,所以主干不需要知道数据是从相机来的还是从网表来的 ——
|
||||
这正是 ``docs/M2_INPUT_SOURCE.md`` 说的"接口不用改,缺的是 provider"。
|
||||
"""
|
||||
@@ -0,0 +1,69 @@
|
||||
(export
|
||||
(version "E")
|
||||
(design
|
||||
(source "fixtures/tiny.kicad_sch")
|
||||
(tool "synthetic")
|
||||
)
|
||||
(components
|
||||
(comp
|
||||
(ref "R1")
|
||||
(value "10k")
|
||||
(footprint "Resistor_SMD:R_0805_2012Metric")
|
||||
)
|
||||
(comp
|
||||
(ref "C1")
|
||||
(value "100n")
|
||||
(footprint "Capacitor_SMD:C_0805_2012Metric")
|
||||
)
|
||||
(comp
|
||||
(ref "U1")
|
||||
(value "NE555")
|
||||
(footprint "Package_DIP:DIP-8_W7.62mm")
|
||||
)
|
||||
)
|
||||
(nets
|
||||
(net
|
||||
(code "1")
|
||||
(name "GND")
|
||||
(node
|
||||
(ref "R1")
|
||||
(pin "2")
|
||||
(pintype "passive")
|
||||
)
|
||||
(node
|
||||
(ref "C1")
|
||||
(pin "2")
|
||||
(pintype "passive")
|
||||
)
|
||||
(node
|
||||
(ref "U1")
|
||||
(pin "1")
|
||||
(pinfunction "GND")
|
||||
(pintype "power_in")
|
||||
)
|
||||
)
|
||||
(net
|
||||
(code "2")
|
||||
(name "OUT")
|
||||
(node
|
||||
(ref "R1")
|
||||
(pin "1")
|
||||
(pintype "passive")
|
||||
)
|
||||
(node
|
||||
(ref "C1")
|
||||
(pin "1")
|
||||
(pintype "passive")
|
||||
)
|
||||
)
|
||||
(net
|
||||
(code "3")
|
||||
(name "unconnected-(U1-Pad7)")
|
||||
(node
|
||||
(ref "U1")
|
||||
(pin "7")
|
||||
(pintype "no_connect")
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,166 @@
|
||||
"""板子一侧:铜箔上到底连没连。只能在装了 KiCad 的机器上跑。
|
||||
|
||||
这个模块存在的理由不是"再多一个 provider",而是**让两份来源互相作证**。
|
||||
|
||||
* 网表说的是**意图**:原理图上这两个脚属于同一条网。
|
||||
* 板子说的是**现实**:铜箔、焊盘、过孔是不是真的把它们接通了。
|
||||
|
||||
成品板上两者一致,半布线的板上不一致。这个不一致不是 bug,是这类系统必须能表达
|
||||
的东西:一份来源说"连上了",另一份说"没连上",正确结论是**不知道**,除非有第三方
|
||||
信息(哪份更新、这块板本来就是半成品)。
|
||||
|
||||
``spatial/checker.py`` 目前没有"两份来源冲突"这个概念,只有"缺了东西"。所以这里先
|
||||
只做测量,把冲突数数出来,再决定要不要、以及怎么把它接进契约。
|
||||
|
||||
用法(服务器)::
|
||||
|
||||
python3 -m spatial.providers.kicad_board <a.kicad_pcb> ...
|
||||
python3 -m spatial.providers.kicad_board <a.kicad_pcb> <a.net> # 覆盖度
|
||||
python3 -m spatial.providers.kicad_board control <a.kicad_pcb> # 阳性对照
|
||||
|
||||
关于"按网统计":``GetRatsnestForNet`` 在这个绑定里返回不透明对象(取不到长度),
|
||||
``RunOnUnconnectedEdges`` 要的是 C++ 的 ``std::function``,传不了 Python 回调
|
||||
(都在 KiCad 10.0.6 上实测过)。所以只报板级总数,不报"哪条网断了"——要那个就得
|
||||
自己重写一遍连通性,不值得。
|
||||
|
||||
一条硬规矩:**这里没有 ``except`` 兜底**。第一版写了 ``try/except`` 返回 -1,而调用
|
||||
方用 ``> 0`` 判断,于是所有失败都变成了"0 条未连通",报告上看起来完美。阳性对照
|
||||
(删掉一条网的铜,看数字动不动)把这个洞捅了出来,见 :func:`control`。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
def _pcbnew():
|
||||
try:
|
||||
import pcbnew
|
||||
except Exception as exc: # noqa: BLE001 - reported, not hidden
|
||||
raise SystemExit(
|
||||
"this module needs pcbnew (KiCad's Python bindings); "
|
||||
f"import failed with {type(exc).__name__}: {exc}")
|
||||
return pcbnew
|
||||
|
||||
|
||||
def _pads(board):
|
||||
return list(board.GetPads())
|
||||
|
||||
|
||||
def _ref(pad) -> str:
|
||||
"""Footprint reference. ``GetParent()`` returns a container, not a footprint
|
||||
(measured on KiCad 10.0.6), so the accessor is ``GetParentFootprint``."""
|
||||
return pad.GetParentFootprint().GetReference()
|
||||
|
||||
|
||||
def _missing(board) -> int:
|
||||
"""Copper connections the board still owes. No swallowing: if this raises,
|
||||
the measurement failed and must not be printed as zero."""
|
||||
return int(board.GetConnectivity().GetUnconnectedCount(False))
|
||||
|
||||
|
||||
def report(paths) -> None:
|
||||
pcbnew = _pcbnew()
|
||||
print(f"{'board':26s} {'焊盘':>5s} {'有网':>5s} {'无网':>5s} {'网数':>4s} {'缺连接':>6s}")
|
||||
print("-" * 56)
|
||||
for path in paths:
|
||||
board = pcbnew.LoadBoard(path)
|
||||
board.BuildConnectivity()
|
||||
pads = _pads(board)
|
||||
with_net = [p for p in pads if p.GetNetCode() != 0]
|
||||
codes = {p.GetNetCode() for p in with_net}
|
||||
print(f"{path.rsplit('/', 1)[-1]:26s} {len(pads):5d} {len(with_net):5d} "
|
||||
f"{len(pads) - len(with_net):5d} {len(codes):4d} {_missing(board):6d}")
|
||||
print()
|
||||
print("焊盘 = 板上所有封装焊盘;有网 = 归属某条网的;无网 = netcode 0(无编号机械焊盘)")
|
||||
print("缺连接 = 铜箔还没连上的连接数。0 表示这份板子与网表在连通性上没有冲突。")
|
||||
|
||||
|
||||
def coverage(board_path: str, netlist_path: str) -> None:
|
||||
"""How big the netlist provider's blind spot actually is.
|
||||
|
||||
Measured, not assumed. The first guess was "a netlist never mentions NC pins
|
||||
or mechanical pads". Half wrong: KiCad gives every no-connect pin its own
|
||||
single-node net, so NC pins *are* covered. What falls through are pads with
|
||||
an empty pad number -- mounting holes and shield pads -- 0 to 0.7% of a board.
|
||||
"""
|
||||
pcbnew = _pcbnew()
|
||||
from . import kicad_netlist
|
||||
|
||||
nl = kicad_netlist.load(netlist_path)
|
||||
named = {(r, p) for r, p in nl.nodes()}
|
||||
board = pcbnew.LoadBoard(board_path)
|
||||
pads = _pads(board)
|
||||
pad_keys = {(_ref(p), p.GetNumber()) for p in pads}
|
||||
missing = pad_keys - named
|
||||
extra = named - pad_keys
|
||||
print(f"board {board_path.rsplit('/', 1)[-1]}: {len(pads)} pads, "
|
||||
f"{len({_ref(p) for p in pads})} footprints")
|
||||
print(f"netlist {netlist_path.rsplit('/', 1)[-1]}: {len(named)} named pads, "
|
||||
f"{len(nl.comps)} parts")
|
||||
print(f"板上有、网表没提:{len(missing)} "
|
||||
f"({len(missing) / max(1, len(pad_keys)):.1%} of pads)")
|
||||
print(f"网表提了、板上没有:{len(extra)} (非零 = 网表与板子版本不一致)")
|
||||
if missing:
|
||||
print(f" 举例:{sorted(missing)[:8]}")
|
||||
print()
|
||||
print("这就是 netlist provider 的盲区,而且只能由知道封装的一侧算出来。")
|
||||
|
||||
|
||||
def control(board_path: str) -> None:
|
||||
"""Positive control: cut one net's copper, require the detector to notice.
|
||||
|
||||
Every demo board is fully routed, so the disagreement count is zero -- and a
|
||||
metric that only ever returns zero has not been tested. This removes the
|
||||
tracks of one small net and demands the count go up.
|
||||
"""
|
||||
pcbnew = _pcbnew()
|
||||
board = pcbnew.LoadBoard(board_path)
|
||||
board.BuildConnectivity()
|
||||
before = _missing(board)
|
||||
|
||||
per_net = {}
|
||||
for track in board.GetTracks():
|
||||
if track.GetNetCode():
|
||||
per_net.setdefault(track.GetNetCode(), []).append(track)
|
||||
if not per_net:
|
||||
print("no tracks on this board")
|
||||
return
|
||||
code = min(per_net, key=lambda c: (len(per_net[c]), c))
|
||||
net = board.FindNet(code)
|
||||
name = net.GetNetname() if net else str(code)
|
||||
cut = len(per_net[code])
|
||||
for track in per_net[code]:
|
||||
board.Remove(track)
|
||||
board.BuildConnectivity()
|
||||
after = _missing(board)
|
||||
|
||||
print(f"control on {board_path.rsplit('/', 1)[-1]}")
|
||||
print(f" cut net {name!r}: removed {cut} track(s), "
|
||||
f"{len([p for p in _pads(board) if p.GetNetCode() == code])} pads on it")
|
||||
print(f" missing before: {before}")
|
||||
print(f" missing after : {after}")
|
||||
ok = after > before
|
||||
print(f" {'PASS' if ok else 'FAIL'} the detector "
|
||||
f"{'notices' if ok else 'did NOT notice'} the cut")
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
if argv and argv[0] == "control":
|
||||
if len(argv) < 2:
|
||||
print("usage: kicad_board control <a.kicad_pcb>")
|
||||
return 2
|
||||
control(argv[1])
|
||||
elif len(argv) == 2:
|
||||
coverage(argv[0], argv[1])
|
||||
elif argv:
|
||||
report(argv)
|
||||
else:
|
||||
print("usage: kicad_board <pcb>... | kicad_board <pcb> <net> | "
|
||||
"kicad_board control <pcb>")
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,162 @@
|
||||
"""KiCad 网表 → Observation:第一个真实的元数据 provider。
|
||||
|
||||
M2 的契约说得很清楚:`conduct` 这类关系在几何里没有签名,只能来自元数据。
|
||||
这个模块就是那份元数据——KiCad 导出的网表——到 `Observation` 的翻译层。
|
||||
|
||||
三件事要在这里说清楚,因为它们决定了这个 provider 能回答什么、不能回答什么:
|
||||
|
||||
**一、网表只有拓扑,没有几何。** 文件里没有坐标,所以翻译出来的实体没有
|
||||
``box``,接触关系一条也提不出来。这不是缺陷,是分工:几何来自另一台相机/另一份
|
||||
导出,两者在 ``Observation`` 这一层汇合。
|
||||
|
||||
**二、同一条网 = 两两连通。** 一个网里有 k 个节点就生成 k(k-1)/2 条 conduct
|
||||
边。用生成树也能让可达性一样,但那样"这两个脚是同一张铜"这个事实就没了,
|
||||
而模型的边特征正是靠它。
|
||||
|
||||
**三、网表对它自己的覆盖程度是沉默的。** 一开始的猜测是"网表不提 NC 脚和机械脚",
|
||||
在 KiCad 10.0.6 上实测**只对了一半**:KiCad 给每个 NC 脚单独建一条单点网
|
||||
(名字形如 ``unconnected-(U1-Pad7)``),所以 NC 脚是覆盖的;真正漏掉的是**没有
|
||||
焊盘编号的机械焊盘**(安装孔、晶振屏蔽脚),占一块板的 0–0.7%。
|
||||
|
||||
这个空白有多大,只能拿板子那一侧来量(``kicad_board.coverage``),网表自己算不出来。
|
||||
所以 ``scope`` 在这里只能声明"这份网表描述的就是全部",缺口留给另一份来源。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from ..schema import Edge, Entity, Observation
|
||||
from . import sexpr
|
||||
|
||||
GENERATED_BY = "kicad-netlist"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Net:
|
||||
code: str
|
||||
name: str
|
||||
nodes: list = field(default_factory=list) # [(ref, pin), ...]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Netlist:
|
||||
comps: dict = field(default_factory=dict) # ref -> {value, footprint}
|
||||
nets: list = field(default_factory=list)
|
||||
|
||||
def nodes(self) -> list:
|
||||
seen, out = set(), []
|
||||
for net in self.nets:
|
||||
for ref, pin in net.nodes:
|
||||
key = (ref, pin)
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
out.append(key)
|
||||
return out
|
||||
|
||||
|
||||
def load(path: str) -> Netlist:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
tree = sexpr.parse(f.read())
|
||||
root = tree[0] if tree else []
|
||||
if not isinstance(root, list) or root[0] != "export":
|
||||
raise ValueError(f"{path}: not a KiCad netlist export")
|
||||
|
||||
comps = {}
|
||||
for comp in sexpr.find_all(sexpr.find(root, "components"), "comp"):
|
||||
ref = sexpr.value(comp, "ref")
|
||||
if ref is None:
|
||||
continue
|
||||
comps[ref] = {"value": sexpr.value(comp, "value", ""),
|
||||
"footprint": sexpr.value(comp, "footprint", "")}
|
||||
|
||||
nets = []
|
||||
for net in sexpr.find_all(sexpr.find(root, "nets"), "net"):
|
||||
nodes = []
|
||||
for node in sexpr.find_all(net, "node"):
|
||||
ref, pin = sexpr.value(node, "ref"), sexpr.value(node, "pin")
|
||||
if ref is not None and pin is not None:
|
||||
nodes.append((ref, pin))
|
||||
nets.append(Net(code=sexpr.value(net, "code", "0"),
|
||||
name=sexpr.value(net, "name", ""), nodes=nodes))
|
||||
return Netlist(comps=comps, nets=nets)
|
||||
|
||||
|
||||
def _eid(ref: str, pin: str) -> str:
|
||||
return f"{ref}.{pin}"
|
||||
|
||||
|
||||
def to_observation(nl: Netlist) -> Observation:
|
||||
"""The netlist as an observation: pads plus pairwise conduct edges."""
|
||||
entities, edges = [], []
|
||||
for ref, pin in nl.nodes():
|
||||
entities.append(Entity(_eid(ref, pin), "pad", source=GENERATED_BY,
|
||||
attrs={"ref": ref, "pin": pin}))
|
||||
# nothing else: a netlist carries no coordinates, and inventing them
|
||||
# would make the geometry provider's disagreement invisible
|
||||
for net in nl.nets:
|
||||
for i in range(len(net.nodes)):
|
||||
for j in range(i + 1, len(net.nodes)):
|
||||
a = _eid(*net.nodes[i])
|
||||
b = _eid(*net.nodes[j])
|
||||
edges.append(Edge(f"n{net.code}_{i}_{j}", "conduct", a, b,
|
||||
source=GENERATED_BY, attrs={"net": net.name}))
|
||||
scope = {
|
||||
"parts": {"part": len(nl.comps)} if nl.comps else {},
|
||||
"rendered": {"part": len(nl.comps)} if nl.comps else {},
|
||||
"relations": {"conduct": len(edges)},
|
||||
"rendered_relations": {"conduct": len(edges)},
|
||||
"layers": [],
|
||||
"rendered_layers": [],
|
||||
}
|
||||
return Observation(entities=entities, edges=edges, scope=scope,
|
||||
units={"length": "mm", "per_unit": 1})
|
||||
|
||||
|
||||
def report(paths) -> None:
|
||||
"""What a netlist can and cannot say, per file.
|
||||
|
||||
The interesting numbers are not "did the translation work" -- the edges are
|
||||
built from the same membership they are checked against, so that part is a
|
||||
construction. What is worth measuring is what the file leaves out:
|
||||
|
||||
``单点网`` are nets with exactly one node: the pin exists and connects to
|
||||
nothing. A system that treats "not in any pair" as "unknown" would abstain
|
||||
on them; one that treats it as "false" is right here. Only the netlist
|
||||
distinguishes those two cases, so this count is the one that has to be
|
||||
carried into the observation.
|
||||
"""
|
||||
print(f"{'file':28s} {'器件':>4s} {'节点':>4s} {'网':>4s} {'单点网':>5s} "
|
||||
f"{'最大网':>5s} {'边':>6s} {'无器件节点':>6s}")
|
||||
print("-" * 74)
|
||||
for path in paths:
|
||||
nl = load(path)
|
||||
nodes = len(nl.nodes())
|
||||
singles = sum(1 for n in nl.nets if len(n.nodes) == 1)
|
||||
biggest = max((len(n.nodes) for n in nl.nets), default=0)
|
||||
obs = to_observation(nl)
|
||||
orphans = sum(1 for e in obs.entities if e.attrs["ref"] not in nl.comps)
|
||||
print(f"{path.rsplit('/', 1)[-1]:28s} {len(nl.comps):4d} {nodes:4d} "
|
||||
f"{len(nl.nets):4d} {singles:5d} {biggest:5d} {len(obs.edges):6d} "
|
||||
f"{orphans:6d}")
|
||||
print()
|
||||
print("器件 = 网表列出的器件数;节点 = 出现过的 (器件,脚) 对数")
|
||||
print("单点网 = 只有一个节点的网:脚存在,但什么也没连 —— 这是'假'而不是'不知道'")
|
||||
print("最大网 = 节点最多的那条网的节点数")
|
||||
print("无器件节点 = 出现在网里、但没有器件条目的节点(网表自相矛盾)")
|
||||
print()
|
||||
print("单点网不是缺陷:KiCad 给每个 NC 脚单独建一条网,正是'这个脚什么也没连'的")
|
||||
print("显式说法。真正漏掉的是无编号机械焊盘,实测占 0-0.7%(见 kicad_board 覆盖度)。")
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
if not argv:
|
||||
print("usage: python3 -m spatial.providers.kicad_netlist <file.net> ...")
|
||||
return 2
|
||||
report(argv)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,80 @@
|
||||
"""s-表达式:KiCad 的网表、工程文件、封装库都是这个形状。
|
||||
|
||||
只做一件小事——把 ``(a (b "c") d)`` 变成嵌套列表 ``["a", ["b", "c"], "d"]``。
|
||||
不做 schema 校验,不做单位换算,也不试图理解语义:上层自己按路径取值。
|
||||
|
||||
写它的理由不是"不想用第三方库",而是这里必须零依赖:provider 要能在只有
|
||||
Python 的机器上跑,否则每换一台机器就要先把环境装一遍,而装环境这件事
|
||||
正在 M2 的验收路径上(服务器连不上时整条链路就断了)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def parse(text: str) -> list:
|
||||
"""Parse one s-expression into nested lists of strings."""
|
||||
out, stack, i, n = [], [], 0, len(text)
|
||||
token = []
|
||||
while i < n:
|
||||
ch = text[i]
|
||||
if ch == '"':
|
||||
i += 1
|
||||
buf = []
|
||||
while i < n and text[i] != '"':
|
||||
if text[i] == "\\" and i + 1 < n:
|
||||
i += 1
|
||||
buf.append({"n": "\n", "t": "\t", '"': '"', "\\": "\\"}.get(text[i], text[i]))
|
||||
else:
|
||||
buf.append(text[i])
|
||||
i += 1
|
||||
token.append("".join(buf))
|
||||
i += 1
|
||||
continue
|
||||
if ch == "(":
|
||||
stack.append([])
|
||||
token = []
|
||||
elif ch == ")":
|
||||
if token:
|
||||
stack[-1].append("".join(token))
|
||||
token = []
|
||||
if not stack:
|
||||
raise ValueError(f"unbalanced ')' at {i}")
|
||||
done = stack.pop()
|
||||
(stack[-1] if stack else out).append(done)
|
||||
elif ch in " \t\r\n":
|
||||
if token:
|
||||
stack[-1].append("".join(token))
|
||||
token = []
|
||||
else:
|
||||
token.append(ch)
|
||||
i += 1
|
||||
if token:
|
||||
out.append("".join(token))
|
||||
if stack:
|
||||
raise ValueError("unbalanced '('")
|
||||
return out
|
||||
|
||||
|
||||
def find(node, name: str):
|
||||
"""First child list whose head is ``name``, or None."""
|
||||
if isinstance(node, list):
|
||||
for child in node:
|
||||
if isinstance(child, list) and child and child[0] == name:
|
||||
return child
|
||||
return None
|
||||
|
||||
|
||||
def find_all(node, name: str) -> list:
|
||||
if not isinstance(node, list):
|
||||
return []
|
||||
return [c for c in node if isinstance(c, list) and c and c[0] == name]
|
||||
|
||||
|
||||
def value(node, name: str, default=None):
|
||||
"""The first atom of ``(name atom)``, or ``default``."""
|
||||
child = find(node, name)
|
||||
if child is None:
|
||||
return default
|
||||
for item in child[1:]:
|
||||
if not isinstance(item, list):
|
||||
return item
|
||||
return default
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Per-family report.
|
||||
|
||||
The aggregate metrics in ``train.evaluate`` hide the only comparison that
|
||||
matters: a model can score 1.000 answer accuracy on a held-out family while
|
||||
never once abstaining and while its certificates are wrong four times out of
|
||||
five. Answer accuracy alone cannot tell "learned the rule" from "learned the
|
||||
label distribution of this family".
|
||||
|
||||
So each row here reports the four things separately:
|
||||
|
||||
* ``acc`` -- accuracy on rows the observation can decide
|
||||
* ``abst`` -- fraction of undecidable rows the model actually refuses
|
||||
* ``cert`` -- certificate validity among the rows it calls "true"
|
||||
* ``conf`` -- mean top-1 confidence, which is what ``cert`` and ``abst`` are
|
||||
fighting against
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import torch
|
||||
|
||||
from . import checker, generator
|
||||
from .data import collate
|
||||
from .model import N_AXIS, N_EDGE, SCENE_HIDDEN
|
||||
from .train import load
|
||||
|
||||
DANGLING_BIT = N_EDGE + N_AXIS + 3
|
||||
DISPUTED_BIT = N_EDGE + N_AXIS + 7
|
||||
|
||||
ANSWERS = ("true", "false", "unknown")
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def family_row(model, family: str, seed: int, n: int, max_entities: int = 32,
|
||||
ablate: str = None, availability: str = "leaked") -> dict:
|
||||
batch = [generator.make(family, seed=seed, index=i) for i in range(n)]
|
||||
device = next(model.parameters()).device
|
||||
t = collate(batch, max_entities, availability)
|
||||
t = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in t.items()}
|
||||
if ablate:
|
||||
# a mechanism that survives its own removal was never used. The dangling
|
||||
# signal lives in two places -- the structural unknown slot and a flag on
|
||||
# the edge itself -- so zeroing only one of them tests the other, not the
|
||||
# mechanism.
|
||||
for key in ablate.split(","):
|
||||
if key == "dangling":
|
||||
t["dangling"] = torch.zeros_like(t["dangling"])
|
||||
t["edge_feat"][..., DANGLING_BIT] = 0.0
|
||||
elif key == "disputed":
|
||||
# the disputed flag lives in one slot of the edge features; zeroing
|
||||
# it asks whether the model read the dispute or inferred the answer
|
||||
# from something that correlates with it.
|
||||
t["edge_feat"][..., DISPUTED_BIT] = 0.0
|
||||
elif key == "hidden":
|
||||
# the full-state-derived block only: what is withheld *by kind*.
|
||||
# The scope block at the end stays, so this measures exactly the
|
||||
# leak's contribution rather than "any availability signal".
|
||||
t["scene"][:, SCENE_HIDDEN] = 0.0
|
||||
else:
|
||||
t[key] = torch.zeros_like(t[key])
|
||||
out = model(t["feat"], t["pad_mask"], t["edge_index"], t["edge_type"], t["edge_mask"],
|
||||
t["q_ents"], t["q_kind"], t["edit_op"], t["edit_idx"], t["edge_removed"],
|
||||
t["edge_feat"], t["scene"], t["dangling"])
|
||||
pred = out["answer"].argmax(-1).tolist()
|
||||
conf = torch.softmax(out["answer"], -1).max(-1).values.tolist()
|
||||
probs = torch.sigmoid(out["evidence"])
|
||||
|
||||
ans_rows = [i for i, sc in enumerate(batch) if sc.label.answer != "unknown"]
|
||||
unk_rows = [i for i, sc in enumerate(batch) if sc.label.answer == "unknown"]
|
||||
hit = sum(1 for i in ans_rows if pred[i] == ANSWERS.index(batch[i].label.answer))
|
||||
abst = sum(1 for i in unk_rows if pred[i] == 2)
|
||||
|
||||
# a certificate is only asked of rows the model is willing to assert
|
||||
|
||||
valid = total = 0
|
||||
for i, sc in enumerate(batch):
|
||||
if pred[i] != 0:
|
||||
continue
|
||||
ids = [e.eid for e in sc.obs.edges]
|
||||
picked = [ids[k] for k in range(len(ids)) if probs[i, k] > 0.5]
|
||||
total += 1
|
||||
valid += int(bool(picked) and checker.validate_evidence(sc.full, sc.query, picked))
|
||||
|
||||
return {
|
||||
"family": family,
|
||||
"n": len(batch),
|
||||
"decidable": len(ans_rows),
|
||||
"unknown": len(unk_rows),
|
||||
"acc": round(hit / max(1, len(ans_rows)), 3),
|
||||
"abst": round(abst / max(1, len(unk_rows)), 3),
|
||||
"cert": round(valid / max(1, total), 3),
|
||||
"n_true": total,
|
||||
"conf": round(sum(conf) / len(conf), 3),
|
||||
}
|
||||
|
||||
|
||||
def report(config_path: str, n: int = 128, ablate: str = None, seed: int = None) -> None:
|
||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
tag = os.path.basename(config_path).replace(".json", "")
|
||||
if seed is not None:
|
||||
tag = f"{tag}_s{seed}"
|
||||
ckpt = os.path.join(root, "out_spatial", tag, "ckpt.pt")
|
||||
model, _, step, cfg = load(ckpt, "cuda" if torch.cuda.is_available() else "cpu")
|
||||
model.eval()
|
||||
if seed is not None:
|
||||
cfg["seed"] = seed
|
||||
print(f"step {step} families: train={cfg['data']['train_families']} "
|
||||
f"val={cfg['data']['val_families']}")
|
||||
if ablate:
|
||||
print(f"ABLATION: {ablate} zeroed at eval time")
|
||||
head = f"{'family':11s} {'n':>3s} {'dec':>4s} {'unk':>4s} {'dang':>4s} {'acc':>5s} " \
|
||||
f"{'abst':>5s} {'cert':>5s} {'#true':>5s} {'conf':>5s}"
|
||||
print(head)
|
||||
print("-" * len(head))
|
||||
for fam in generator.FAMILIES:
|
||||
ndang = sum(len(generator.make(fam, cfg["seed"], i).obs.dangling) for i in range(8)) / 8
|
||||
r = family_row(model, fam, cfg["seed"], n, cfg["model"]["max_entities"], ablate,
|
||||
cfg["data"].get("availability", "leaked"))
|
||||
print(f"{r['family']:11s} {r['n']:3d} {r['decidable']:4d} {r['unknown']:4d} "
|
||||
f"{ndang:4.1f} "
|
||||
f"{r['acc']:5.3f} {r['abst']:5.3f} {r['cert']:5.3f} {r['n_true']:5d} "
|
||||
f"{r['conf']:5.3f}")
|
||||
@@ -0,0 +1,238 @@
|
||||
"""Data contract for the spatial-structure task.
|
||||
|
||||
Two records per sample, and the split between them is the whole point:
|
||||
|
||||
``Observation``
|
||||
Everything the model may read. Visible entities and edges only. A hidden
|
||||
inner-layer trace, a contact on the back face, or a constraint that lives in
|
||||
a mate definition is simply absent here -- not masked, absent.
|
||||
|
||||
``FullState``
|
||||
Everything the checker and the generator know. Never reaches the model.
|
||||
|
||||
If a generator bug leaks a hidden edge into the observation the fixture
|
||||
``hidden_pair`` catches it, because that fixture builds two samples with
|
||||
identical observation digests and opposite full-state answers.
|
||||
|
||||
Everything is integer geometry on a 0.25 mm grid, so a digest is reproducible
|
||||
across machines and a "same seed rebuilds the same digest" check means
|
||||
something.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
EDGE_KINDS = ("contain", "adjacent", "contact", "constraint", "conduct")
|
||||
ENTITY_KINDS = ("pad", "via", "trace", "block", "part", "ground")
|
||||
ANSWERS = ("true", "false", "unknown")
|
||||
CHANGES = ("changed", "same", "unknown")
|
||||
DOF_AXES = ("tx", "ty", "tz", "rx", "ry", "rz")
|
||||
|
||||
|
||||
def canonical(obj) -> str:
|
||||
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
||||
|
||||
|
||||
def digest(obj) -> str:
|
||||
return hashlib.sha256(canonical(obj).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _canonical_scope(scope: dict) -> dict:
|
||||
out = {}
|
||||
for k, v in sorted((scope or {}).items()):
|
||||
out[k] = dict(sorted(v.items())) if isinstance(v, dict) else sorted(v)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class Entity:
|
||||
eid: str
|
||||
kind: str
|
||||
frame: str = "world"
|
||||
unit: str = "mm"
|
||||
source: str = "given"
|
||||
attrs: dict = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"eid": self.eid,
|
||||
"kind": self.kind,
|
||||
"frame": self.frame,
|
||||
"unit": self.unit,
|
||||
"source": self.source,
|
||||
"attrs": dict(sorted(self.attrs.items())),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Edge:
|
||||
eid: str
|
||||
kind: str
|
||||
a: str
|
||||
b: str
|
||||
layer: int = 0
|
||||
source: str = "given"
|
||||
attrs: dict = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"eid": self.eid,
|
||||
"kind": self.kind,
|
||||
"a": self.a,
|
||||
"b": self.b,
|
||||
"layer": self.layer,
|
||||
"source": self.source,
|
||||
"attrs": dict(sorted(self.attrs.items())),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Observation:
|
||||
"""What the model sees. Only visible items are stored here.
|
||||
|
||||
``hidden`` and ``dangling`` are the two things here that are not visible, and
|
||||
they are deliberate.
|
||||
|
||||
``hidden`` counts by kind what the full state contains and this view does
|
||||
not. Without it "nothing is there" and "it is behind the part" are the same
|
||||
input, and the two have different answers -- no reasoning can recover a
|
||||
distinction the input never carried.
|
||||
|
||||
``dangling`` is the sharper form of the same idea: a relation whose one end
|
||||
is visible and whose other end is not. It carries no identity -- the anchor
|
||||
is the entity you can already see, never the one you cannot -- so it says
|
||||
*where* the unknown attaches, not *what* the answer is. A support that
|
||||
dangles still does not decide anything, which is why a chain that ends in a
|
||||
dangling edge is evidence of ignorance rather than evidence of support.
|
||||
"""
|
||||
|
||||
entities: list = field(default_factory=list)
|
||||
edges: list = field(default_factory=list)
|
||||
cameras: list = field(default_factory=list)
|
||||
units: dict = field(default_factory=lambda: {"length": "mm", "per_unit": 1})
|
||||
hidden_layers: list = field(default_factory=list)
|
||||
hidden_faces: list = field(default_factory=list)
|
||||
hidden: dict = field(default_factory=lambda: {"entity": {}, "edge": {}})
|
||||
dangling: list = field(default_factory=list)
|
||||
# What the source says it has, versus what it actually handed over. Counts
|
||||
# and layer names only: no endpoints, no "who supports whom". This is the
|
||||
# part of "I did not see everything" that a real provider can state without
|
||||
# leaking the answer -- a BOM knows how many parts exist, a netlist knows
|
||||
# how many conductors exist and on which layers, and neither of them knows
|
||||
# which part ends up holding the load.
|
||||
# Relations one source asserts and another denies. Not "missing" -- both
|
||||
# sources are talking about the same pair and disagree, which is a different
|
||||
# epistemic state from "nobody told me". Carries no vote and no priority:
|
||||
# deciding which source wins is exactly the thing the system must not do on
|
||||
# its own, so a disputed relation can only ever suspend an answer.
|
||||
conflicts: list = field(default_factory=list)
|
||||
scope: dict = field(default_factory=lambda: {
|
||||
"parts": {}, "rendered": {},
|
||||
"relations": {}, "rendered_relations": {},
|
||||
"layers": [], "rendered_layers": [],
|
||||
"conflicts": {},
|
||||
})
|
||||
|
||||
def entity_ids(self) -> set:
|
||||
return {e.eid for e in self.entities}
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"entities": [e.to_dict() for e in sorted(self.entities, key=lambda x: x.eid)],
|
||||
"edges": [e.to_dict() for e in sorted(self.edges, key=lambda x: x.eid)],
|
||||
"cameras": list(self.cameras),
|
||||
"units": dict(self.units),
|
||||
"hidden_layers": sorted(self.hidden_layers),
|
||||
"hidden_faces": sorted(self.hidden_faces),
|
||||
"hidden": {k: dict(sorted(v.items())) for k, v in sorted(self.hidden.items())},
|
||||
"dangling": [e.to_dict() for e in sorted(self.dangling, key=lambda x: x.eid)],
|
||||
"conflicts": [dict(sorted(c.items())) for c in
|
||||
sorted(self.conflicts, key=lambda c: (c.get("kind", ""),
|
||||
c.get("a", ""),
|
||||
c.get("b", "")))],
|
||||
"scope": _canonical_scope(self.scope),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class FullState:
|
||||
"""Everything, including what the observation omits."""
|
||||
|
||||
entities: list = field(default_factory=list)
|
||||
edges: list = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"entities": [e.to_dict() for e in sorted(self.entities, key=lambda x: x.eid)],
|
||||
"edges": [e.to_dict() for e in sorted(self.edges, key=lambda x: x.eid)],
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Query:
|
||||
kind: str # "connection" | "stability" | "freedom"
|
||||
a: str = ""
|
||||
b: str = ""
|
||||
edit: Optional[dict] = None # {"op": "remove_edge", "edge": "<eid>"}
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"kind": self.kind, "a": self.a, "b": self.b, "edit": self.edit}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Label:
|
||||
answer: str = "unknown" # one of ANSWERS
|
||||
change: str = "unknown" # one of CHANGES
|
||||
evidence: list = field(default_factory=list) # edge ids
|
||||
sufficient: bool = False # observation alone decides the answer
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"answer": self.answer,
|
||||
"change": self.change,
|
||||
"evidence": sorted(self.evidence),
|
||||
"sufficient": self.sufficient,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Scenario:
|
||||
key: str
|
||||
domain: str
|
||||
family: str
|
||||
seed: int
|
||||
obs: Observation
|
||||
query: Query
|
||||
full: FullState
|
||||
label: Label = field(default_factory=Label)
|
||||
tags: dict = field(default_factory=dict)
|
||||
|
||||
# ---- digests -------------------------------------------------------
|
||||
def input_dict(self) -> dict:
|
||||
"""Exactly what the model may read. Two samples with the same digest
|
||||
must be indistinguishable to the model, whatever their labels are."""
|
||||
return {"obs": self.obs.to_dict(), "query": self.query.to_dict()}
|
||||
|
||||
def input_digest(self) -> str:
|
||||
return digest(self.input_dict())
|
||||
|
||||
def full_digest(self) -> str:
|
||||
return digest({"full": self.full.to_dict(), "query": self.query.to_dict(),
|
||||
"obs": self.obs.to_dict()})
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"key": self.key,
|
||||
"domain": self.domain,
|
||||
"family": self.family,
|
||||
"seed": self.seed,
|
||||
"obs": self.obs.to_dict(),
|
||||
"query": self.query.to_dict(),
|
||||
"label": self.label.to_dict(),
|
||||
"full": self.full.to_dict(),
|
||||
"tags": dict(sorted(self.tags.items())),
|
||||
"input_digest": self.input_digest(),
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Train / resume / eval on the relational task.
|
||||
|
||||
Two contract points from the plan that the old ``mm/train.py`` could not meet:
|
||||
|
||||
* checkpoints are replaced atomically and carry optimizer, step and RNG state,
|
||||
so an interrupted run continues into the same next batch;
|
||||
* evaluation reports over-confidence on insufficient-evidence samples and
|
||||
certificate validity, not just accuracy -- a model that answers "true"
|
||||
everywhere would look fine on accuracy alone.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from . import checker, generator
|
||||
from .data import collate
|
||||
from .model import RelationBackbone, QUERY_KINDS
|
||||
|
||||
|
||||
def make_batch(families, seed: int, step: int, batch_size: int):
|
||||
rng = random.Random(f"batch:{seed}:{step}")
|
||||
out = []
|
||||
for _ in range(batch_size):
|
||||
fam = rng.choice(families)
|
||||
out.append(generator.make(fam, seed=seed, index=rng.randrange(10 ** 6)))
|
||||
return out
|
||||
|
||||
|
||||
def batch_loss(model, tensors):
|
||||
out = model(tensors["feat"], tensors["pad_mask"], tensors["edge_index"],
|
||||
tensors["edge_type"], tensors["edge_mask"], tensors["q_ents"], tensors["q_kind"],
|
||||
tensors.get("edit_op"), tensors.get("edit_idx"), tensors.get("edge_removed"),
|
||||
tensors.get("edge_feat"), tensors.get("scene"), tensors.get("dangling"))
|
||||
l_ans = F.cross_entropy(out["answer"], tensors["answer"])
|
||||
l_chg = F.cross_entropy(out["change"], tensors["change"])
|
||||
ev_logits = out["evidence"][tensors["edge_mask"]]
|
||||
ev_target = tensors["evidence"][tensors["edge_mask"]]
|
||||
l_ev = F.binary_cross_entropy_with_logits(ev_logits, ev_target) if ev_logits.numel() else l_ans * 0
|
||||
total = l_ans + 0.5 * l_chg + 0.5 * l_ev
|
||||
return total, {"answer": float(l_ans.detach()), "change": float(l_chg.detach()),
|
||||
"evidence": float(l_ev.detach()),
|
||||
"temp": float(out["temp"])}, out
|
||||
|
||||
|
||||
def _ece(probs, correct, n_bin: int = 5) -> float:
|
||||
"""Top-label expected calibration error.
|
||||
|
||||
Accuracy alone cannot show a miscalibrated head: a model that answers every
|
||||
row with confidence 0.99 and is right 72% of the time scores the same
|
||||
accuracy as one that says 0.72. The temperature is only meaningful if this
|
||||
number is reported next to it.
|
||||
"""
|
||||
conf = probs.max(-1).values
|
||||
hit = (probs.argmax(-1) == correct).float()
|
||||
total = 0.0
|
||||
for b in range(n_bin):
|
||||
lo, hi = b / n_bin, (b + 1) / n_bin
|
||||
m = (conf > lo) & (conf <= hi) if b else (conf <= hi)
|
||||
n = int(m.sum())
|
||||
if n:
|
||||
total += n * abs(float(hit[m].mean()) - float(conf[m].mean()))
|
||||
return total / max(1, probs.size(0))
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def evaluate(model, families, seed: int, n: int, max_entities: int = 32,
|
||||
availability: str = "leaked") -> dict:
|
||||
model.eval()
|
||||
batch = make_batch(families, seed + 1, 0, n)[:n]
|
||||
device = next(model.parameters()).device
|
||||
tensors = collate(batch, max_entities, availability)
|
||||
tensors = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in tensors.items()}
|
||||
_, losses, out = batch_loss(model, tensors)
|
||||
pred = out["answer"].argmax(-1).tolist()
|
||||
pred_chg = out["change"].argmax(-1).tolist()
|
||||
|
||||
answerable = [i for i, sc in enumerate(batch) if sc.label.answer != "unknown"]
|
||||
unknown = [i for i, sc in enumerate(batch) if sc.label.answer == "unknown"]
|
||||
correct = sum(1 for i in answerable if pred[i] == ["true", "false", "unknown"].index(batch[i].label.answer))
|
||||
|
||||
overconfident = sum(1 for i in unknown if pred[i] != 2)
|
||||
chg_rows = [i for i, sc in enumerate(batch) if sc.label.change != "unknown"]
|
||||
chg_correct = sum(1 for i in chg_rows
|
||||
if pred_chg[i] == ["changed", "same", "unknown"].index(batch[i].label.change))
|
||||
|
||||
# certificate check on rows the model calls "true"
|
||||
probs = torch.sigmoid(out["evidence"])
|
||||
valid = total = 0
|
||||
for i, sc in enumerate(batch):
|
||||
if pred[i] != 0:
|
||||
continue
|
||||
ids = [e.eid for e in sc.obs.edges]
|
||||
picked = [ids[k] for k in range(len(ids)) if probs[i, k] > 0.5]
|
||||
total += 1
|
||||
valid += int(bool(picked) and checker.validate_evidence(sc.full, sc.query, picked))
|
||||
|
||||
model.train()
|
||||
ece = _ece(torch.softmax(out["answer"], -1), tensors["answer"])
|
||||
return {
|
||||
"answer_acc": correct / max(1, len(answerable)),
|
||||
"answerable": len(answerable),
|
||||
"overconf": overconfident / max(1, len(unknown)),
|
||||
"n_unknown": len(unknown),
|
||||
"change_acc": chg_correct / max(1, len(chg_rows)),
|
||||
"evidence_valid": valid / max(1, total),
|
||||
"n_true_pred": total,
|
||||
"ece": ece,
|
||||
"temp": float(out["temp"]),
|
||||
"loss": losses,
|
||||
}
|
||||
|
||||
|
||||
def save(path: str, model, opt, step: int, config: dict):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
tmp = path + ".tmp"
|
||||
torch.save({
|
||||
"model": model.state_dict(),
|
||||
"opt": opt.state_dict() if opt is not None else None,
|
||||
"step": step,
|
||||
"config": config,
|
||||
"torch_rng": torch.get_rng_state(),
|
||||
"py_rng": random.getstate(),
|
||||
}, tmp)
|
||||
os.replace(tmp, path) # atomic: a crash leaves the old file intact
|
||||
|
||||
|
||||
def _build(m: dict) -> RelationBackbone:
|
||||
return RelationBackbone(d=m["d"], n_layer=m["n_layer"], n_head=m["n_head"],
|
||||
dropout=m["dropout"], max_entities=m["max_entities"],
|
||||
rounds=m.get("rounds", 2), n_evidence=m.get("n_evidence", 4))
|
||||
|
||||
|
||||
def load(path: str, device="cpu"):
|
||||
# always restore on CPU: map_location=device would drag the RNG state (a
|
||||
# ByteTensor) onto the GPU, and set_rng_state only accepts a CPU one
|
||||
ck = torch.load(path, map_location="cpu", weights_only=False)
|
||||
cfg = ck["config"]["model"]
|
||||
model = _build(cfg)
|
||||
model.load_state_dict(ck["model"])
|
||||
opt = torch.optim.AdamW(model.parameters(), lr=ck["config"]["optim"]["lr"],
|
||||
weight_decay=ck["config"]["optim"]["weight_decay"])
|
||||
if ck.get("opt"):
|
||||
opt.load_state_dict(ck["opt"])
|
||||
torch.set_rng_state(ck["torch_rng"].to(torch.uint8))
|
||||
random.setstate(ck["py_rng"])
|
||||
if ck.get("opt"):
|
||||
# the checkpoint is restored on CPU, so the moment and variance buffers
|
||||
# have to follow the parameters onto the device
|
||||
for state in opt.state.values():
|
||||
for key, val in state.items():
|
||||
if torch.is_tensor(val):
|
||||
state[key] = val.to(device)
|
||||
model.to(device)
|
||||
return model, opt, ck["step"], ck["config"]
|
||||
|
||||
|
||||
def run(config: dict, resume: bool = False, steps: int = None, verbose: bool = True) -> dict:
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
torch.manual_seed(config["seed"])
|
||||
out_dir = config["out_dir"]
|
||||
ckpt = os.path.join(out_dir, "ckpt.pt")
|
||||
|
||||
if resume and os.path.exists(ckpt):
|
||||
model, opt, start, config = load(ckpt, device)
|
||||
if verbose:
|
||||
print(f"resume from step {start}")
|
||||
else:
|
||||
m = config["model"]
|
||||
model = _build(m)
|
||||
opt = torch.optim.AdamW(model.parameters(), lr=config["optim"]["lr"],
|
||||
weight_decay=config["optim"]["weight_decay"])
|
||||
start = 0
|
||||
model.to(device).train()
|
||||
|
||||
total_steps = start + (steps if steps is not None else config["optim"]["steps"])
|
||||
base_lr = config["optim"]["lr"]
|
||||
# 100 was a footgun: at lr 3e-3 the first updates are a 10x jump and the
|
||||
# freedom set task never recovered from the basin it landed in. Same lr,
|
||||
# same steps, only this number changed: dof.set 0.203 -> 1.000 on seed 0,
|
||||
# and 3/3 seeds green across all 14 families.
|
||||
warmup = config["optim"].get("warmup", 300)
|
||||
min_frac = config["optim"].get("min_lr_frac", 0.1)
|
||||
t0 = time.time()
|
||||
for step in range(start, total_steps):
|
||||
# a flat 3e-3 ran 0.085 at step 1200 and 1.126 at step 2000: the loss
|
||||
# oscillated by two orders of magnitude, so the "which family is weak"
|
||||
# question was really "which family happened to be sampled at a peak".
|
||||
# Warm up, then decay, so the curve means something.
|
||||
if step < warmup:
|
||||
lr = base_lr * (step + 1) / warmup
|
||||
else:
|
||||
frac = (step - warmup) / max(1, total_steps - warmup)
|
||||
lr = base_lr * (min_frac + (1 - min_frac) * 0.5 * (1 + math.cos(math.pi * frac)))
|
||||
for g in opt.param_groups:
|
||||
g["lr"] = lr
|
||||
|
||||
batch = make_batch(config["data"]["train_families"], config["seed"], step,
|
||||
config["optim"]["batch"])
|
||||
tensors = collate(batch, config["model"]["max_entities"],
|
||||
config["data"].get("availability", "leaked"))
|
||||
tensors = {k: v.to(device) if torch.is_tensor(v) else v for k, v in tensors.items()}
|
||||
loss, parts, _ = batch_loss(model, tensors)
|
||||
opt.zero_grad(set_to_none=True)
|
||||
loss.backward()
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
||||
opt.step()
|
||||
if verbose and (step % max(1, config["optim"]["log_every"]) == 0):
|
||||
print(f"step {step:4d} loss {float(loss.detach()):.4f} lr {lr:.4f} "
|
||||
f"(ans {parts['answer']:.3f} chg {parts['change']:.3f} ev {parts['evidence']:.3f})")
|
||||
save(ckpt, model, opt, total_steps, config)
|
||||
|
||||
metrics = evaluate(model, config["data"]["val_families"], config["seed"], config["eval"]["n"],
|
||||
config["model"]["max_entities"],
|
||||
config["data"].get("availability", "leaked"))
|
||||
if verbose:
|
||||
print(f"val {json.dumps({k: (round(v, 3) if isinstance(v, float) else v) for k, v in metrics.items() if k != 'loss'})}")
|
||||
print(f"done in {time.time() - t0:.1f}s device={device}")
|
||||
metrics["secs"] = round(time.time() - t0, 2)
|
||||
return metrics
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
"""视野边界:可见性能不能算出 hidden 和 dangling。
|
||||
|
||||
M2 的输入契约卡在一个循环上:``Observation.hidden`` 和 ``Observation.dangling``
|
||||
说"有东西我没看到",而现在的夹具是拿**完整状态减去可见集合**算出来的。真实场景
|
||||
里没有完整状态可用,否则就不用谈不确定了。
|
||||
|
||||
出路只有一条:把"我没看到"换成某个能从**观测本身**算出来的量。最容易想到的是
|
||||
表面可见性——拿几个正交视角,一个面如果背朝所有相机、或被别的零件挡住,就是
|
||||
"没看到的面",而没看到的面正是关系可能附着的地方。
|
||||
|
||||
这个模块就是为了把这条路走到底并给出判决,而不是为了得到一个好用的特征:
|
||||
|
||||
* :func:`unobserved_faces` 只吃可见实体和相机方向,不碰完整状态;
|
||||
* :func:`report` 把它和 ``dangling`` 的锚点逐实体对账。
|
||||
|
||||
结论写在 ``docs/M2_VIEW_CONTRACT.md``:这条路走不通,而且是两头都不通。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from . import generator
|
||||
from .geom import box_faces
|
||||
|
||||
# An inspection rig: five orthographic views. Not a rendering camera -- the point
|
||||
# is only that "seen" has to mean something computable from geometry alone.
|
||||
VIEWS = ((1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0),
|
||||
(0.0, -1.0, 0.0), (0.0, 0.0, 1.0))
|
||||
|
||||
|
||||
def _box(entity):
|
||||
b = entity.attrs.get("box")
|
||||
return tuple(float(v) for v in b) if b else None
|
||||
|
||||
|
||||
def _face_center(box, axis, sign):
|
||||
x0, y0, z0, x1, y1, z1 = box
|
||||
c = [(x0 + x1) / 2.0, (y0 + y1) / 2.0, (z0 + z1) / 2.0]
|
||||
c[axis] = x1 if sign > 0 else x0
|
||||
return c
|
||||
|
||||
|
||||
def _ray_hits_box(box, p, d, eps: float = 1e-9) -> bool:
|
||||
"""Slab test for the ray p + t*d, t > eps. Used for occlusion only."""
|
||||
tmin, tmax = 0.0, float("inf")
|
||||
for k in range(3):
|
||||
lo, hi = box[k], box[k + 3]
|
||||
if abs(d[k]) < 1e-12:
|
||||
if p[k] <= lo or p[k] >= hi:
|
||||
return False
|
||||
else:
|
||||
t1, t2 = (lo - p[k]) / d[k], (hi - p[k]) / d[k]
|
||||
if t1 > t2:
|
||||
t1, t2 = t2, t1
|
||||
if t1 > tmin:
|
||||
tmin = t1
|
||||
if t2 < tmax:
|
||||
tmax = t2
|
||||
if tmin > tmax:
|
||||
return False
|
||||
return tmax > eps
|
||||
|
||||
|
||||
def face_seen(box, face, others, eps: float = 1e-9) -> bool:
|
||||
"""Is this face visible from at least one view, with nothing in the way.
|
||||
|
||||
``others`` are the boxes that may occlude it. The ray starts just off the
|
||||
surface so a face flush against another part does not test against itself,
|
||||
and it is a single ray from the face centre -- an approximation that only
|
||||
ever over-reports occlusion for concave parts, which these fixtures do not
|
||||
have.
|
||||
"""
|
||||
axis, sign, _, _ = face
|
||||
n = [0.0, 0.0, 0.0]
|
||||
n[axis] = float(sign)
|
||||
p = _face_center(box, axis, sign)
|
||||
for d in VIEWS:
|
||||
if sum(n[k] * d[k] for k in range(3)) <= 0:
|
||||
continue # back-facing under this view
|
||||
start = [p[k] + n[k] * eps for k in range(3)]
|
||||
if not any(_ray_hits_box(o, start, d, eps) for o in others):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def unobserved_faces(entities) -> dict:
|
||||
"""eid -> number of its six faces no view can see. Box entities only."""
|
||||
boxes = {e.eid: _box(e) for e in entities if _box(e) is not None}
|
||||
out = {}
|
||||
for eid, box in boxes.items():
|
||||
others = [b for k, b in boxes.items() if k != eid]
|
||||
out[eid] = sum(1 for f in box_faces(box) if not face_seen(box, f, others))
|
||||
return out
|
||||
|
||||
|
||||
def dangling_anchors(obs) -> set:
|
||||
return {e.a for e in obs.dangling}
|
||||
|
||||
|
||||
def report(n: int = 24) -> None:
|
||||
"""Per family: do "a relation I cannot see the far end of" and "a surface no
|
||||
view can see" pick out the same entities.
|
||||
|
||||
Two ways to be wrong, and both matter:
|
||||
|
||||
* ``d-only`` -- an entity carrying a dangling relation that every view sees
|
||||
completely. Geometry has no way to say "something attaches here", so the
|
||||
fact can only be *declared*. Inner-layer conductors in a PCB are exactly
|
||||
this: the conductor is not occluded, it is inside another material.
|
||||
* ``u-only`` -- an entity with unseen surfaces and no dangling relation. A
|
||||
part resting on a pedestal has an unseeable bottom face every time, so the
|
||||
signal is on for nearly everything and stops distinguishing anything.
|
||||
"""
|
||||
print(f"{'family':11s} {'可见':>4s} {'有盒':>4s} {'悬空锚':>5s} {'有未见面':>6s} "
|
||||
f"{'两者':>4s} {'仅悬空':>5s} {'仅见面':>5s} {'平均未见面':>8s}")
|
||||
print("-" * 66)
|
||||
for fam in generator.FAMILIES:
|
||||
vis = boxed = both = u_only = dang = unobs = 0
|
||||
tot_faces = 0
|
||||
for i in range(n):
|
||||
sc = generator.make(fam, seed=5, index=i)
|
||||
ents = list(sc.obs.entities)
|
||||
vis += len(ents)
|
||||
un = unobserved_faces(ents)
|
||||
boxed += len(un)
|
||||
tot_faces += sum(un.values())
|
||||
anchors = dangling_anchors(sc.obs)
|
||||
dang += len(anchors)
|
||||
unobs += sum(1 for v in un.values() if v > 0)
|
||||
both += sum(1 for eid in anchors if un.get(eid, 0) > 0)
|
||||
u_only += sum(1 for eid, v in un.items() if v > 0 and eid not in anchors)
|
||||
per = max(1, n)
|
||||
avg = (tot_faces / boxed) if boxed else 0.0
|
||||
print(f"{fam:11s} {vis / per:4.1f} {boxed / per:4.1f} {dang / per:5.1f} "
|
||||
f"{unobs / per:6.1f} {both / per:4.1f} {(dang - both) / per:7.1f} "
|
||||
f"{u_only / per:5.1f} {avg:8.2f}")
|
||||
print()
|
||||
print("可见 = 观测里的实体数(含无几何的地面/焊盘)")
|
||||
print("有盒 = 能用表面可见性说话的实体数;连接域恒为 0,那类的隐藏不是遮挡")
|
||||
print("悬空锚 = 挂着悬空关系的实体数(悬空关系 = 一端不可见,只剩锚点)")
|
||||
print("有未见面 = 至少有一张面任何视角都看不到的实体数")
|
||||
print("仅悬空 = 有悬空关系但六张面全可见 —— 表面可见性对它无话可说,只能靠声明")
|
||||
print("仅见面 = 有未见面但没有悬空关系 —— 坐着的东西底面永远看不到,信号恒亮")
|
||||
print("平均未见面 = 有盒实体平均有多少张面看不到(0-6)")
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
report(int(argv[0]) if argv else 24)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
File renamed without changes.
Reference in new issue
Block a user