teul 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- teul-0.2.0/LICENSE +7 -0
- teul-0.2.0/PKG-INFO +115 -0
- teul-0.2.0/README.md +99 -0
- teul-0.2.0/pyproject.toml +22 -0
- teul-0.2.0/setup.cfg +4 -0
- teul-0.2.0/tests/test_teul.py +123 -0
- teul-0.2.0/tests/test_walk.py +142 -0
- teul-0.2.0/teul/__init__.py +29 -0
- teul-0.2.0/teul/check.py +196 -0
- teul-0.2.0/teul/controller.py +115 -0
- teul-0.2.0/teul/export.py +57 -0
- teul-0.2.0/teul/ops.py +165 -0
- teul-0.2.0/teul/safety.py +88 -0
- teul-0.2.0/teul/types.py +102 -0
- teul-0.2.0/teul.egg-info/PKG-INFO +115 -0
- teul-0.2.0/teul.egg-info/SOURCES.txt +17 -0
- teul-0.2.0/teul.egg-info/dependency_links.txt +1 -0
- teul-0.2.0/teul.egg-info/requires.txt +8 -0
- teul-0.2.0/teul.egg-info/top_level.txt +1 -0
teul-0.2.0/LICENSE
ADDED
teul-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: teul
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: PyTorch-embedded unit/frame checking and safety-graph DSL for Physical AI controllers
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: torch>=2.5.0
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
12
|
+
Provides-Extra: onnx
|
|
13
|
+
Requires-Dist: onnx>=1.17; extra == "onnx"
|
|
14
|
+
Requires-Dist: onnxscript>=0.1; extra == "onnx"
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# Teul (틀)
|
|
18
|
+
|
|
19
|
+
Physical AI 제어 프로그램을 위한 PyTorch 내장 언어 골격.
|
|
20
|
+
**"틀"** 은 좌표계의 *frame* 과 골격·거푸집을 동시에 뜻한다.
|
|
21
|
+
|
|
22
|
+
## 설계 명제
|
|
23
|
+
|
|
24
|
+
1. **단위와 좌표계는 값에 붙어 있다.** `rad` 자리에 `deg` 가, `base` 프레임 자리에 `camera` 프레임이 들어오면 로봇을 켜기 전에 컴파일이 거부한다.
|
|
25
|
+
2. **안전 제약은 런타임 감시가 아니라 그래프 안에 있다.** 내보낼 연산 그래프에 제약 노드를 심으므로, 정책 가중치를 교체해도 제약은 남는다.
|
|
26
|
+
3. **학습된 정책의 내부는 신뢰하지 않는다.** 정책은 말단 노드로 두고 경계 규격만 본다.
|
|
27
|
+
|
|
28
|
+
고전 로보틱스 DSL(URML, EzSkiROS, DeROS 등)은 ROS 2 와 고전 제어 스택 위에서 같은 일을 한다. Teul 의 자리는 **학습된 정책의 내보낸 그래프** 다.
|
|
29
|
+
|
|
30
|
+
## 빠른 시작
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install -e ".[dev]"
|
|
34
|
+
python examples/demo.py
|
|
35
|
+
python examples/sim2real_walk.py
|
|
36
|
+
python -m pytest tests/ -q # 21 passed
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import teul
|
|
41
|
+
from teul import Joint, Image, controller, convert, op
|
|
42
|
+
|
|
43
|
+
IMG, J6, J6_DEG = Image(224, 224, 3), Joint(6, "rad"), Joint(6, "deg")
|
|
44
|
+
|
|
45
|
+
@op(out=J6) # 학습된 정책은 말단 노드
|
|
46
|
+
def policy(image: IMG, state: J6): ...
|
|
47
|
+
|
|
48
|
+
@controller(rate=30, latency_budget_ms=20.0,
|
|
49
|
+
limits=SO101_LIMITS, max_joint_vel=3.0)
|
|
50
|
+
def pick(image: IMG, state: J6, prev_q: J6, offset: J6_DEG) -> J6:
|
|
51
|
+
return policy(image, state) + offset
|
|
52
|
+
# TeulTypeError: 연산에서 단위가 다름: rad vs deg
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`convert(offset, "rad")` 을 거치면 통과하고, 환산 계수가 그래프에 상수로 내려간다.
|
|
56
|
+
|
|
57
|
+
## 구현된 것
|
|
58
|
+
|
|
59
|
+
| 모듈 | 역할 |
|
|
60
|
+
| --- | --- |
|
|
61
|
+
| `teul/types.py` | 규격(`Joint`, `Pose`, `Scalar`, `Image`)과 물리량군 단위 환산 |
|
|
62
|
+
| `teul/ops.py` | `convert` / `reorder` / `reframe` / `@op` — 규격을 바꾸는 유일한 경로 |
|
|
63
|
+
| `teul/check.py` | fx 그래프에 규격을 전파·검증하고 마커를 실제 연산으로 내리는(lowering) 패스 |
|
|
64
|
+
| `teul/safety.py` | 변화율 제약·관절 한계를 `clamp` 노드로 삽입 |
|
|
65
|
+
| `teul/controller.py` | `@controller` — 추적, 검사, lowering, 제약 삽입, 지연 측정 |
|
|
66
|
+
| `teul/export.py` | `torch.export` → ONNX / ExecuTorch 경로 |
|
|
67
|
+
|
|
68
|
+
구체적으로 다음이 **실행으로 확인된** 상태다.
|
|
69
|
+
|
|
70
|
+
- 단위 불일치, 물리량군 교차 환산(`rad`→`m`), 관절 순서 불일치, 좌표 프레임 불일치, 반환 규격 불일치, 주석 누락 — 모두 컴파일 시점 `TeulTypeError`
|
|
71
|
+
- `reorder` 가 표기만 바꾸지 않고 `index_select` + 상수 버퍼로 그래프에 내려간다
|
|
72
|
+
- `reframe` 은 등록된 변환 행렬이 있어야만 통과한다(표기만 바꾸는 reframe 은 거부)
|
|
73
|
+
- 변화율 제약 + 관절 한계가 `clamp` 노드로 박히고, `torch.export` 와 ONNX 를 모두 통과해 남는다
|
|
74
|
+
- 정책 가중치를 바꿔도 제약이 유지된다
|
|
75
|
+
|
|
76
|
+
## 설계상 주의점
|
|
77
|
+
|
|
78
|
+
- **`prev_q` 는 제어기 입력이다.** 내보낸 그래프는 상태를 가질 수 없으므로 이전 스텝 명령을 바깥에서 넣어야 한다. 첫 스텝의 `prev_q` 는 0 이 아니라 **측정값 `q_meas`** 로 초기화해야 한다. 0 으로 두면 변화율 제약이 모든 관절을 0 쪽으로 끌어당긴다.
|
|
79
|
+
- **변화율은 `max_joint_vel`(rad/s)로 준다.** 스텝당 한계를 직접 주면 `rate` 를 50→100Hz 로 바꿀 때 안전 범위가 조용히 두 배로 느슨해진다. Teul 은 `max_joint_vel / rate` 로 계산한다.
|
|
80
|
+
- **물리 한계 clamp 가 항상 마지막이다.** 변화율 → 물리 한계 순서가 그래프에 고정된다.
|
|
81
|
+
- **ONNX 에서 `clamp` 은 `Clip` 이 아니라 `Max`+`Min` 으로 내려간다.** `Clip` 노드를 세어 제약 생존을 확인하면 0 이 나온다. `teul.count_onnx_clamps()` 를 쓸 것.
|
|
82
|
+
- **지연 예산은 측정값이지 보증이 아니다.** `measure()` 는 이 머신에서의 p99 를 재며, 실기체 제어 주기 보증은 2단계 Rust 런타임의 몫이다.
|
|
83
|
+
- **학습된 부분은 반드시 `@op` 로 감싼다.** 제어기 안에서 `nn.Module` 을 직접 호출하면 fx 가 추적하지 못한다(Teul 이 그 이유를 알려주는 오류로 바꿔 던진다).
|
|
84
|
+
|
|
85
|
+
## 아직 안 된 것
|
|
86
|
+
|
|
87
|
+
- 작업공간·토크 제약 (관절 위치·변화율만 구현)
|
|
88
|
+
- FSM·스킬 합성 문법
|
|
89
|
+
- 다축 회전이 섞인 Pose 변환의 일반형(현재는 등록된 선형 변환 행렬)
|
|
90
|
+
- 지연 예산을 타입으로 보장하는 Rust 런타임 (2단계)
|
|
91
|
+
- ExecuTorch 경로는 코드만 있고 `executorch` 미설치 환경에서 미검증
|
|
92
|
+
|
|
93
|
+
## 검증 환경
|
|
94
|
+
|
|
95
|
+
Python 3.13, PyTorch 2.15.0 (CPU), onnx / onnxscript. `tests/` 21개 통과.
|
|
96
|
+
CI 는 Python 3.11 / 3.12 / 3.13 에서 테스트와 두 예제를 모두 실행한다.
|
|
97
|
+
|
|
98
|
+
## 라이선스
|
|
99
|
+
|
|
100
|
+
Apache-2.0
|
|
101
|
+
|
|
102
|
+
## 노트북에서 확인
|
|
103
|
+
|
|
104
|
+
```powershell
|
|
105
|
+
# Windows
|
|
106
|
+
.\scripts\verify.ps1
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
# macOS / Linux
|
|
111
|
+
./scripts/verify.sh
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
가상환경을 만들어 설치하고 테스트와 두 예제를 차례로 실행한다.
|
|
115
|
+
`onnx` 가 없으면 ONNX 테스트 1건은 자동으로 skip 된다(설치하려면 `pip install -e ".[onnx]"`).
|
teul-0.2.0/README.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# Teul (틀)
|
|
2
|
+
|
|
3
|
+
Physical AI 제어 프로그램을 위한 PyTorch 내장 언어 골격.
|
|
4
|
+
**"틀"** 은 좌표계의 *frame* 과 골격·거푸집을 동시에 뜻한다.
|
|
5
|
+
|
|
6
|
+
## 설계 명제
|
|
7
|
+
|
|
8
|
+
1. **단위와 좌표계는 값에 붙어 있다.** `rad` 자리에 `deg` 가, `base` 프레임 자리에 `camera` 프레임이 들어오면 로봇을 켜기 전에 컴파일이 거부한다.
|
|
9
|
+
2. **안전 제약은 런타임 감시가 아니라 그래프 안에 있다.** 내보낼 연산 그래프에 제약 노드를 심으므로, 정책 가중치를 교체해도 제약은 남는다.
|
|
10
|
+
3. **학습된 정책의 내부는 신뢰하지 않는다.** 정책은 말단 노드로 두고 경계 규격만 본다.
|
|
11
|
+
|
|
12
|
+
고전 로보틱스 DSL(URML, EzSkiROS, DeROS 등)은 ROS 2 와 고전 제어 스택 위에서 같은 일을 한다. Teul 의 자리는 **학습된 정책의 내보낸 그래프** 다.
|
|
13
|
+
|
|
14
|
+
## 빠른 시작
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install -e ".[dev]"
|
|
18
|
+
python examples/demo.py
|
|
19
|
+
python examples/sim2real_walk.py
|
|
20
|
+
python -m pytest tests/ -q # 21 passed
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import teul
|
|
25
|
+
from teul import Joint, Image, controller, convert, op
|
|
26
|
+
|
|
27
|
+
IMG, J6, J6_DEG = Image(224, 224, 3), Joint(6, "rad"), Joint(6, "deg")
|
|
28
|
+
|
|
29
|
+
@op(out=J6) # 학습된 정책은 말단 노드
|
|
30
|
+
def policy(image: IMG, state: J6): ...
|
|
31
|
+
|
|
32
|
+
@controller(rate=30, latency_budget_ms=20.0,
|
|
33
|
+
limits=SO101_LIMITS, max_joint_vel=3.0)
|
|
34
|
+
def pick(image: IMG, state: J6, prev_q: J6, offset: J6_DEG) -> J6:
|
|
35
|
+
return policy(image, state) + offset
|
|
36
|
+
# TeulTypeError: 연산에서 단위가 다름: rad vs deg
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`convert(offset, "rad")` 을 거치면 통과하고, 환산 계수가 그래프에 상수로 내려간다.
|
|
40
|
+
|
|
41
|
+
## 구현된 것
|
|
42
|
+
|
|
43
|
+
| 모듈 | 역할 |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| `teul/types.py` | 규격(`Joint`, `Pose`, `Scalar`, `Image`)과 물리량군 단위 환산 |
|
|
46
|
+
| `teul/ops.py` | `convert` / `reorder` / `reframe` / `@op` — 규격을 바꾸는 유일한 경로 |
|
|
47
|
+
| `teul/check.py` | fx 그래프에 규격을 전파·검증하고 마커를 실제 연산으로 내리는(lowering) 패스 |
|
|
48
|
+
| `teul/safety.py` | 변화율 제약·관절 한계를 `clamp` 노드로 삽입 |
|
|
49
|
+
| `teul/controller.py` | `@controller` — 추적, 검사, lowering, 제약 삽입, 지연 측정 |
|
|
50
|
+
| `teul/export.py` | `torch.export` → ONNX / ExecuTorch 경로 |
|
|
51
|
+
|
|
52
|
+
구체적으로 다음이 **실행으로 확인된** 상태다.
|
|
53
|
+
|
|
54
|
+
- 단위 불일치, 물리량군 교차 환산(`rad`→`m`), 관절 순서 불일치, 좌표 프레임 불일치, 반환 규격 불일치, 주석 누락 — 모두 컴파일 시점 `TeulTypeError`
|
|
55
|
+
- `reorder` 가 표기만 바꾸지 않고 `index_select` + 상수 버퍼로 그래프에 내려간다
|
|
56
|
+
- `reframe` 은 등록된 변환 행렬이 있어야만 통과한다(표기만 바꾸는 reframe 은 거부)
|
|
57
|
+
- 변화율 제약 + 관절 한계가 `clamp` 노드로 박히고, `torch.export` 와 ONNX 를 모두 통과해 남는다
|
|
58
|
+
- 정책 가중치를 바꿔도 제약이 유지된다
|
|
59
|
+
|
|
60
|
+
## 설계상 주의점
|
|
61
|
+
|
|
62
|
+
- **`prev_q` 는 제어기 입력이다.** 내보낸 그래프는 상태를 가질 수 없으므로 이전 스텝 명령을 바깥에서 넣어야 한다. 첫 스텝의 `prev_q` 는 0 이 아니라 **측정값 `q_meas`** 로 초기화해야 한다. 0 으로 두면 변화율 제약이 모든 관절을 0 쪽으로 끌어당긴다.
|
|
63
|
+
- **변화율은 `max_joint_vel`(rad/s)로 준다.** 스텝당 한계를 직접 주면 `rate` 를 50→100Hz 로 바꿀 때 안전 범위가 조용히 두 배로 느슨해진다. Teul 은 `max_joint_vel / rate` 로 계산한다.
|
|
64
|
+
- **물리 한계 clamp 가 항상 마지막이다.** 변화율 → 물리 한계 순서가 그래프에 고정된다.
|
|
65
|
+
- **ONNX 에서 `clamp` 은 `Clip` 이 아니라 `Max`+`Min` 으로 내려간다.** `Clip` 노드를 세어 제약 생존을 확인하면 0 이 나온다. `teul.count_onnx_clamps()` 를 쓸 것.
|
|
66
|
+
- **지연 예산은 측정값이지 보증이 아니다.** `measure()` 는 이 머신에서의 p99 를 재며, 실기체 제어 주기 보증은 2단계 Rust 런타임의 몫이다.
|
|
67
|
+
- **학습된 부분은 반드시 `@op` 로 감싼다.** 제어기 안에서 `nn.Module` 을 직접 호출하면 fx 가 추적하지 못한다(Teul 이 그 이유를 알려주는 오류로 바꿔 던진다).
|
|
68
|
+
|
|
69
|
+
## 아직 안 된 것
|
|
70
|
+
|
|
71
|
+
- 작업공간·토크 제약 (관절 위치·변화율만 구현)
|
|
72
|
+
- FSM·스킬 합성 문법
|
|
73
|
+
- 다축 회전이 섞인 Pose 변환의 일반형(현재는 등록된 선형 변환 행렬)
|
|
74
|
+
- 지연 예산을 타입으로 보장하는 Rust 런타임 (2단계)
|
|
75
|
+
- ExecuTorch 경로는 코드만 있고 `executorch` 미설치 환경에서 미검증
|
|
76
|
+
|
|
77
|
+
## 검증 환경
|
|
78
|
+
|
|
79
|
+
Python 3.13, PyTorch 2.15.0 (CPU), onnx / onnxscript. `tests/` 21개 통과.
|
|
80
|
+
CI 는 Python 3.11 / 3.12 / 3.13 에서 테스트와 두 예제를 모두 실행한다.
|
|
81
|
+
|
|
82
|
+
## 라이선스
|
|
83
|
+
|
|
84
|
+
Apache-2.0
|
|
85
|
+
|
|
86
|
+
## 노트북에서 확인
|
|
87
|
+
|
|
88
|
+
```powershell
|
|
89
|
+
# Windows
|
|
90
|
+
.\scripts\verify.ps1
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
# macOS / Linux
|
|
95
|
+
./scripts/verify.sh
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
가상환경을 만들어 설치하고 테스트와 두 예제를 차례로 실행한다.
|
|
99
|
+
`onnx` 가 없으면 ONNX 테스트 1건은 자동으로 skip 된다(설치하려면 `pip install -e ".[onnx]"`).
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "teul"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "PyTorch-embedded unit/frame checking and safety-graph DSL for Physical AI controllers"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
dependencies = ["torch>=2.5.0"]
|
|
13
|
+
|
|
14
|
+
[project.optional-dependencies]
|
|
15
|
+
dev = ["pytest>=8.0"]
|
|
16
|
+
onnx = ["onnx>=1.17", "onnxscript>=0.1"]
|
|
17
|
+
|
|
18
|
+
[tool.setuptools.packages.find]
|
|
19
|
+
include = ["teul*"]
|
|
20
|
+
|
|
21
|
+
[tool.pytest.ini_options]
|
|
22
|
+
testpaths = ["tests"]
|
teul-0.2.0/setup.cfg
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import torch
|
|
3
|
+
|
|
4
|
+
import teul
|
|
5
|
+
from teul import Joint, Pose, Scalar, TeulTypeError, controller, convert, op, reorder
|
|
6
|
+
|
|
7
|
+
J6 = Joint(6, "rad")
|
|
8
|
+
J6_DEG = Joint(6, "deg")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@op(out=J6)
|
|
12
|
+
def policy(state):
|
|
13
|
+
return state * 2.0
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_unit_mismatch_is_rejected_at_compile_time():
|
|
17
|
+
with pytest.raises(TeulTypeError, match="단위가 다름"):
|
|
18
|
+
|
|
19
|
+
@controller(rate=30)
|
|
20
|
+
def pick(state: J6, offset: J6_DEG) -> J6:
|
|
21
|
+
return policy(state) + offset
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_convert_lowers_factor_into_graph():
|
|
25
|
+
@controller(rate=30)
|
|
26
|
+
def pick(state: J6, offset: J6_DEG) -> J6:
|
|
27
|
+
return policy(state) + convert(offset, "rad")
|
|
28
|
+
|
|
29
|
+
code = pick.graph_module.code
|
|
30
|
+
assert "0.0174532" in code, "환산 계수가 그래프 상수로 내려가지 않았습니다"
|
|
31
|
+
out = pick(torch.ones(6), torch.full((6,), 180.0))
|
|
32
|
+
assert torch.allclose(out, torch.full((6,), 2.0 + torch.pi), atol=1e-5)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_cross_quantity_conversion_is_rejected():
|
|
36
|
+
with pytest.raises(TeulTypeError, match="물리량군"):
|
|
37
|
+
|
|
38
|
+
@controller(rate=30)
|
|
39
|
+
def pick(state: J6, d: Joint(6, "m")) -> J6:
|
|
40
|
+
return policy(state) + convert(d, "rad")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_missing_annotation_is_rejected():
|
|
44
|
+
with pytest.raises(TeulTypeError, match="규격 주석이 없습니다"):
|
|
45
|
+
|
|
46
|
+
@controller(rate=30)
|
|
47
|
+
def pick(state) -> J6:
|
|
48
|
+
return policy(state)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_return_spec_mismatch_is_rejected():
|
|
52
|
+
with pytest.raises(TeulTypeError, match="반환"):
|
|
53
|
+
|
|
54
|
+
@controller(rate=30)
|
|
55
|
+
def pick(state: J6) -> J6_DEG:
|
|
56
|
+
return policy(state)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_unwrapped_module_output_has_no_spec():
|
|
60
|
+
"""학습된 부분을 @op 로 감싸지 않으면 규격을 추적할 수 없으므로 거부한다."""
|
|
61
|
+
net = torch.nn.Linear(6, 6)
|
|
62
|
+
|
|
63
|
+
with pytest.raises(TeulTypeError, match="@op"):
|
|
64
|
+
|
|
65
|
+
@controller(rate=30)
|
|
66
|
+
def pick(state: J6) -> J6:
|
|
67
|
+
return net(state)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_reorder_requires_registration():
|
|
71
|
+
with pytest.raises(TeulTypeError, match="등록되지 않은 관절 순서"):
|
|
72
|
+
|
|
73
|
+
@controller(rate=30)
|
|
74
|
+
def pick(q: Joint(6, "rad", order="a")) -> Joint(6, "rad", order="b"):
|
|
75
|
+
return reorder(q, "b")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_reframe_requires_a_real_transform():
|
|
79
|
+
"""표기만 바꾸는 reframe 은 허용하지 않는다."""
|
|
80
|
+
with pytest.raises(TeulTypeError, match="등록되지 않은 프레임 변환"):
|
|
81
|
+
|
|
82
|
+
@controller(rate=30)
|
|
83
|
+
def pick(p: Pose(frame="world")) -> Pose(frame="base_link"):
|
|
84
|
+
return teul.reframe(p, "base_link")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_reorder_is_a_real_permutation_in_the_graph():
|
|
88
|
+
teul.register_joint_order("real", "isaac", [2, 0, 1])
|
|
89
|
+
A = Joint(3, "rad", order="real")
|
|
90
|
+
B = Joint(3, "rad", order="isaac")
|
|
91
|
+
|
|
92
|
+
@op(out=B)
|
|
93
|
+
def pol(q):
|
|
94
|
+
return q
|
|
95
|
+
|
|
96
|
+
@controller(rate=30)
|
|
97
|
+
def f(q: A) -> B:
|
|
98
|
+
return pol(reorder(q, "isaac"))
|
|
99
|
+
|
|
100
|
+
assert "index_select" in f.graph_module.code
|
|
101
|
+
assert torch.equal(f(torch.tensor([10.0, 20.0, 30.0])), torch.tensor([30.0, 10.0, 20.0]))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_invalid_permutation_is_rejected():
|
|
105
|
+
with pytest.raises(ValueError, match="치환이 아닙니다"):
|
|
106
|
+
teul.register_joint_order("a", "b", [0, 0, 1])
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_specs_are_visible_for_inspection():
|
|
110
|
+
@controller(rate=30)
|
|
111
|
+
def pick(state: J6) -> J6:
|
|
112
|
+
return policy(state)
|
|
113
|
+
|
|
114
|
+
assert "Joint(6, 'rad'" in " ".join(pick.specs().values())
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_latency_budget_is_enforced():
|
|
118
|
+
@controller(rate=1000, latency_budget_ms=0.0)
|
|
119
|
+
def pick(state: J6) -> J6:
|
|
120
|
+
return policy(state)
|
|
121
|
+
|
|
122
|
+
with pytest.raises(teul.LatencyBudgetError, match="지연 예산 초과"):
|
|
123
|
+
pick.measure((torch.ones(6),), iters=20)
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Sim2Real 보행 로봇 적용 경로 검증."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
import torch
|
|
5
|
+
|
|
6
|
+
import teul
|
|
7
|
+
from teul import Joint, Pose, Scalar, controller, export_program, op, reframe, reorder
|
|
8
|
+
from teul.safety import count_clamps
|
|
9
|
+
|
|
10
|
+
PERM = [3, 4, 5, 0, 1, 2, 9, 10, 11, 6, 7, 8]
|
|
11
|
+
Q_REAL = Joint(12, "rad", order="real")
|
|
12
|
+
Q_SIM = Joint(12, "rad", order="isaac")
|
|
13
|
+
IMU_W = Pose(frame="world", dim=6)
|
|
14
|
+
IMU_B = Pose(frame="base_link", dim=6)
|
|
15
|
+
CMD = Scalar("m/s")
|
|
16
|
+
LIMITS = ([-1.0] * 12, [1.0] * 12)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _build(spike: float = 5.0, rate: float = 50, max_joint_vel: float = 7.5):
|
|
20
|
+
teul.register_joint_order("real", "isaac", PERM)
|
|
21
|
+
teul.register_frame_transform("world", "base_link", torch.eye(6))
|
|
22
|
+
|
|
23
|
+
net = torch.nn.Linear(12, 12, bias=False)
|
|
24
|
+
torch.nn.init.eye_(net.weight)
|
|
25
|
+
|
|
26
|
+
@op(out=Q_SIM)
|
|
27
|
+
def walk_policy(q: Q_SIM, imu: IMU_B, cmd: CMD):
|
|
28
|
+
return net(q) + spike # 학습 초기 발산 상황
|
|
29
|
+
|
|
30
|
+
@controller(rate=rate, limits=LIMITS, max_joint_vel=max_joint_vel)
|
|
31
|
+
def step_walk(
|
|
32
|
+
q_meas: Q_REAL,
|
|
33
|
+
q_default: Q_REAL,
|
|
34
|
+
prev_q: Q_REAL,
|
|
35
|
+
imu_world: IMU_W,
|
|
36
|
+
cmd: CMD,
|
|
37
|
+
) -> Q_REAL:
|
|
38
|
+
imu = reframe(imu_world, "base_link")
|
|
39
|
+
q_sim = reorder(q_meas - q_default, "isaac")
|
|
40
|
+
action = walk_policy(q_sim, imu, cmd)
|
|
41
|
+
return reorder(action, "real") + q_default
|
|
42
|
+
|
|
43
|
+
return step_walk
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _args(q=0.3):
|
|
47
|
+
return (
|
|
48
|
+
torch.full((12,), q),
|
|
49
|
+
torch.zeros(12),
|
|
50
|
+
torch.zeros(12),
|
|
51
|
+
torch.zeros(6),
|
|
52
|
+
torch.zeros(1),
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_joint_order_roundtrip():
|
|
57
|
+
teul.register_joint_order("real", "isaac", PERM)
|
|
58
|
+
q = torch.arange(12, dtype=torch.float32)
|
|
59
|
+
q_sim = teul.reorder_tensor(q, "real", "isaac")
|
|
60
|
+
assert torch.equal(q_sim, torch.tensor(PERM, dtype=torch.float32))
|
|
61
|
+
assert torch.equal(teul.reorder_tensor(q_sim, "isaac", "real"), q)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_sim_and_real_order_cannot_be_added():
|
|
65
|
+
teul.register_joint_order("real", "isaac", PERM)
|
|
66
|
+
|
|
67
|
+
@op(out=Q_SIM)
|
|
68
|
+
def pol(q):
|
|
69
|
+
return q
|
|
70
|
+
|
|
71
|
+
with pytest.raises(teul.TeulTypeError, match="관절 순서가 다름"):
|
|
72
|
+
|
|
73
|
+
@controller(rate=50)
|
|
74
|
+
def bad(q_meas: Q_REAL) -> Q_REAL:
|
|
75
|
+
return pol(reorder(q_meas, "isaac")) + q_meas
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_rate_clamp_limits_spike():
|
|
79
|
+
ctrl = _build(spike=5.0)
|
|
80
|
+
assert ctrl.step_delta == pytest.approx(0.15)
|
|
81
|
+
out = ctrl(*_args())
|
|
82
|
+
assert torch.allclose(out, torch.full((12,), 0.15), atol=1e-6)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_rate_clamp_scales_with_control_rate():
|
|
86
|
+
"""rate 를 바꾸면 스텝당 한계도 같이 바뀐다(안전 범위가 조용히 변하지 않는다)."""
|
|
87
|
+
assert _build(rate=50, max_joint_vel=7.5).step_delta == pytest.approx(0.15)
|
|
88
|
+
assert _build(rate=100, max_joint_vel=7.5).step_delta == pytest.approx(0.075)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_rate_clamp_requires_prev_q_input():
|
|
92
|
+
teul.register_joint_order("real", "isaac", PERM)
|
|
93
|
+
|
|
94
|
+
@op(out=Q_REAL)
|
|
95
|
+
def pol(q):
|
|
96
|
+
return q
|
|
97
|
+
|
|
98
|
+
with pytest.raises(teul.TeulTypeError, match="prev_q"):
|
|
99
|
+
|
|
100
|
+
@controller(rate=50, max_joint_vel=7.5)
|
|
101
|
+
def no_prev(q_meas: Q_REAL) -> Q_REAL:
|
|
102
|
+
return pol(q_meas)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_joint_limit_is_applied_after_rate_clamp():
|
|
106
|
+
"""물리 한계가 마지막에 적용된다."""
|
|
107
|
+
ctrl = _build(spike=5.0, max_joint_vel=1000.0) # 변화율은 사실상 무제한
|
|
108
|
+
out = ctrl(*_args(q=50.0))
|
|
109
|
+
assert torch.allclose(out, torch.ones(12), atol=1e-6)
|
|
110
|
+
assert count_clamps(ctrl.graph_module) == 2
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_export_preserves_both_clamps():
|
|
114
|
+
ctrl = _build(spike=5.0)
|
|
115
|
+
args = _args()
|
|
116
|
+
ep = export_program(ctrl, args)
|
|
117
|
+
n_clamp = sum(1 for n in ep.graph.nodes if "clamp" in str(n.target))
|
|
118
|
+
assert n_clamp >= 2, f"내보낸 그래프에 제약이 남지 않았습니다: {n_clamp}"
|
|
119
|
+
assert torch.allclose(ep.module()(*args), ctrl(*args), atol=1e-6)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def test_swapping_policy_weights_keeps_constraints():
|
|
123
|
+
"""정책 가중치를 바꿔도 제약은 그래프에 남는다."""
|
|
124
|
+
for spike in (5.0, -5.0, 50.0):
|
|
125
|
+
ctrl = _build(spike=spike)
|
|
126
|
+
out = ctrl(*_args())
|
|
127
|
+
assert out.abs().max().item() <= 0.15 + 1e-6
|
|
128
|
+
teul.clear_registries()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_onnx_export_keeps_constraints():
|
|
132
|
+
onnx = pytest.importorskip("onnx")
|
|
133
|
+
import tempfile
|
|
134
|
+
from pathlib import Path
|
|
135
|
+
|
|
136
|
+
ctrl = _build(spike=5.0)
|
|
137
|
+
with tempfile.TemporaryDirectory() as d:
|
|
138
|
+
path = Path(d) / "walk.onnx"
|
|
139
|
+
teul.export_onnx(ctrl, _args(), path)
|
|
140
|
+
assert teul.count_onnx_clamps(path) >= 2, "ONNX 에 안전 제약이 남지 않았습니다"
|
|
141
|
+
ops = [n.op_type for n in onnx.load(str(path)).graph.node]
|
|
142
|
+
assert "Gather" in ops or "GatherElements" in ops, "관절 순서 치환이 사라졌습니다"
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Teul (틀) — Physical AI 제어 프로그램을 위한 PyTorch 내장 언어 골격."""
|
|
2
|
+
|
|
3
|
+
from .check import propagate_and_lower
|
|
4
|
+
from .controller import LatencyBudgetError, TeulController, controller
|
|
5
|
+
from .export import count_onnx_clamps, export_executorch, export_onnx, export_program
|
|
6
|
+
from .ops import (
|
|
7
|
+
clear_registries,
|
|
8
|
+
convert,
|
|
9
|
+
op,
|
|
10
|
+
register_frame_transform,
|
|
11
|
+
register_joint_order,
|
|
12
|
+
reframe,
|
|
13
|
+
reorder,
|
|
14
|
+
reorder_tensor,
|
|
15
|
+
)
|
|
16
|
+
from .safety import insert_joint_limit_clamp, insert_rate_clamp
|
|
17
|
+
from .types import Image, Joint, Pose, Scalar, Spec, TeulTypeError, conversion_factor
|
|
18
|
+
|
|
19
|
+
__version__ = "0.2.0"
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"Joint", "Pose", "Scalar", "Image", "Spec", "TeulTypeError", "conversion_factor",
|
|
23
|
+
"convert", "reorder", "reframe", "op",
|
|
24
|
+
"register_joint_order", "register_frame_transform", "reorder_tensor", "clear_registries",
|
|
25
|
+
"insert_rate_clamp", "insert_joint_limit_clamp", "propagate_and_lower",
|
|
26
|
+
"controller", "TeulController", "LatencyBudgetError",
|
|
27
|
+
"export_program", "export_onnx", "export_executorch", "count_onnx_clamps",
|
|
28
|
+
"__version__",
|
|
29
|
+
]
|