teul 0.2.0__py3-none-any.whl

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/__init__.py ADDED
@@ -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
+ ]
teul/check.py ADDED
@@ -0,0 +1,196 @@
1
+ """fx 그래프에 규격을 전파하고, 불일치를 거부하고, 마커를 실제 연산으로 내린다."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import operator
6
+ from dataclasses import replace
7
+ from typing import Any
8
+
9
+ import torch
10
+ import torch.fx as fx
11
+
12
+ from . import ops as _ops
13
+ from .types import Joint, Pose, Scalar, Spec, TeulTypeError, conversion_factor
14
+
15
+ _ADD_LIKE = {operator.add, operator.sub, torch.add, torch.sub, operator.iadd, operator.isub}
16
+ _SCALE_LIKE = {operator.mul, operator.truediv, torch.mul, torch.div}
17
+
18
+ SPEC_KEY = "teul_spec"
19
+
20
+
21
+ def _spec_of(node: Any) -> Spec | None:
22
+ if isinstance(node, fx.Node):
23
+ return node.meta.get(SPEC_KEY)
24
+ return None # 상수(스칼라)는 규격 없음
25
+
26
+
27
+ def _is_const(a: Any) -> bool:
28
+ return not isinstance(a, fx.Node)
29
+
30
+
31
+ def resolve_annotations(fn) -> tuple[dict[str, Spec], Spec | None]:
32
+ """함수 주석에서 입력/출력 규격을 읽는다. 문자열 주석도 처리한다."""
33
+ raw = dict(getattr(fn, "__annotations__", {}))
34
+ out_spec = raw.pop("return", None)
35
+ g = getattr(fn, "__globals__", {})
36
+
37
+ def _ev(v):
38
+ if isinstance(v, str):
39
+ try:
40
+ v = eval(v, g) # noqa: S307 - 사용자 자신의 모듈 전역에서만 평가
41
+ except Exception as e: # pragma: no cover
42
+ raise TeulTypeError(f"주석을 해석할 수 없습니다: {v!r} ({e})") from None
43
+ if v is not None and not isinstance(v, Spec):
44
+ raise TeulTypeError(f"규격(Spec) 인스턴스가 아닌 주석: {v!r}")
45
+ return v
46
+
47
+ return {k: _ev(v) for k, v in raw.items()}, _ev(out_spec)
48
+
49
+
50
+ def propagate_and_lower(
51
+ gm: fx.GraphModule,
52
+ in_specs: dict[str, Spec],
53
+ out_spec: Spec | None,
54
+ ) -> fx.GraphModule:
55
+ graph = gm.graph
56
+ todo: list[tuple[fx.Node, str, Any]] = []
57
+ buf_count = 0
58
+
59
+ for node in graph.nodes:
60
+ if node.op == "placeholder":
61
+ spec = in_specs.get(node.target)
62
+ if spec is None:
63
+ raise TeulTypeError(
64
+ f"입력 {node.target!r}에 규격 주석이 없습니다. "
65
+ f"예: {node.target}: Joint(12, 'rad', order='real')"
66
+ )
67
+ node.meta[SPEC_KEY] = spec
68
+
69
+ elif node.op == "call_function" and node.target is _ops._convert_marker:
70
+ x, unit = node.args
71
+ src = _spec_of(x)
72
+ if src is None:
73
+ raise TeulTypeError("convert 대상의 규격을 알 수 없습니다 (@op 경계가 필요합니다)")
74
+ factor = conversion_factor(getattr(src, "unit"), unit)
75
+ node.meta[SPEC_KEY] = replace(src, unit=unit)
76
+ todo.append((node, "convert", factor))
77
+
78
+ elif node.op == "call_function" and node.target is _ops._reorder_marker:
79
+ x, order = node.args
80
+ src = _spec_of(x)
81
+ if not isinstance(src, Joint):
82
+ raise TeulTypeError(
83
+ f"reorder 는 Joint 규격에만 쓸 수 있습니다 (받은 규격: "
84
+ f"{src.describe() if src else '미지정'})"
85
+ )
86
+ if src.order == order:
87
+ node.meta[SPEC_KEY] = src
88
+ todo.append((node, "identity", None))
89
+ else:
90
+ perm = _ops.permutation_for(src.order, order)
91
+ if len(perm) != src.n:
92
+ raise TeulTypeError(
93
+ f"치환 길이({len(perm)})와 관절 수({src.n})가 다릅니다"
94
+ )
95
+ node.meta[SPEC_KEY] = replace(src, order=order)
96
+ todo.append((node, "reorder", perm))
97
+
98
+ elif node.op == "call_function" and node.target is _ops._reframe_marker:
99
+ x, frame = node.args
100
+ src = _spec_of(x)
101
+ if not isinstance(src, Pose):
102
+ raise TeulTypeError(
103
+ f"reframe 은 Pose 규격에만 쓸 수 있습니다 (받은 규격: "
104
+ f"{src.describe() if src else '미지정'}). "
105
+ f"관절 순서 변환은 reorder 를 쓰세요."
106
+ )
107
+ if src.frame == frame:
108
+ node.meta[SPEC_KEY] = src
109
+ todo.append((node, "identity", None))
110
+ else:
111
+ mat = _ops.transform_for(src.frame, frame)
112
+ if mat.shape[0] != src.dim:
113
+ raise TeulTypeError(
114
+ f"변환 행렬 크기({mat.shape[0]})와 Pose.dim({src.dim})이 다릅니다"
115
+ )
116
+ node.meta[SPEC_KEY] = replace(src, frame=frame)
117
+ todo.append((node, "reframe", mat))
118
+
119
+ elif node.op == "call_function" and hasattr(node.target, "_teul_out"):
120
+ node.meta[SPEC_KEY] = node.target._teul_out
121
+
122
+ elif node.op == "call_function" and node.target in _ADD_LIKE:
123
+ a, b = node.args[0], node.args[1]
124
+ sa, sb = _spec_of(a), _spec_of(b)
125
+ if _is_const(a) or _is_const(b):
126
+ node.meta[SPEC_KEY] = sa or sb
127
+ elif sa is None or sb is None:
128
+ node.meta[SPEC_KEY] = None
129
+ elif sa != sb:
130
+ raise TeulTypeError(_mismatch_msg(sa, sb))
131
+ else:
132
+ node.meta[SPEC_KEY] = sa
133
+
134
+ elif node.op == "call_function" and node.target in _SCALE_LIKE:
135
+ sa, sb = _spec_of(node.args[0]), _spec_of(node.args[1])
136
+ node.meta[SPEC_KEY] = sa if sa is not None else sb
137
+
138
+ elif node.op == "output":
139
+ got = _spec_of(node.args[0])
140
+ if out_spec is None:
141
+ continue
142
+ if got is None:
143
+ raise TeulTypeError(
144
+ "출력 규격을 추적할 수 없습니다. 학습된 정책을 @op(out=...) 로 "
145
+ "감싸 경계 규격을 선언하세요."
146
+ )
147
+ if got != out_spec:
148
+ raise TeulTypeError(_mismatch_msg(got, out_spec, where="반환"))
149
+
150
+ for node, kind, payload in todo:
151
+ with graph.inserting_before(node):
152
+ x = node.args[0]
153
+ if kind == "identity":
154
+ new = x
155
+ elif kind == "convert":
156
+ new = x if payload == 1.0 else graph.call_function(operator.mul, (x, payload))
157
+ elif kind == "reorder":
158
+ name = f"_teul_perm_{buf_count}"
159
+ buf_count += 1
160
+ gm.register_buffer(name, torch.as_tensor(payload, dtype=torch.long))
161
+ idx = graph.get_attr(name)
162
+ new = graph.call_function(
163
+ torch.index_select, (x,), {"dim": -1, "index": idx}
164
+ )
165
+ elif kind == "reframe":
166
+ name = f"_teul_tf_{buf_count}"
167
+ buf_count += 1
168
+ gm.register_buffer(name, payload.clone())
169
+ mat = graph.get_attr(name)
170
+ new = graph.call_function(torch.nn.functional.linear, (x, mat))
171
+ else: # pragma: no cover
172
+ raise AssertionError(kind)
173
+ if isinstance(new, fx.Node):
174
+ new.meta[SPEC_KEY] = node.meta.get(SPEC_KEY)
175
+ node.replace_all_uses_with(new)
176
+ graph.erase_node(node)
177
+
178
+ graph.lint()
179
+ gm.recompile()
180
+ return gm
181
+
182
+
183
+ def _mismatch_msg(a: Spec, b: Spec, where: str = "연산") -> str:
184
+ if type(a) is not type(b):
185
+ return f"{where} 규격 종류가 다름: {a.describe()} vs {b.describe()}"
186
+ ua, ub = getattr(a, "unit", None), getattr(b, "unit", None)
187
+ if ua != ub:
188
+ return f"{where}에서 단위가 다름: {ua} vs {ub}"
189
+ if isinstance(a, Joint) and isinstance(b, Joint):
190
+ if a.order != b.order:
191
+ return f"{where}에서 관절 순서가 다름: {a.order} vs {b.order}"
192
+ if a.n != b.n:
193
+ return f"{where}에서 관절 수가 다름: {a.n} vs {b.n}"
194
+ if isinstance(a, Pose) and isinstance(b, Pose) and a.frame != b.frame:
195
+ return f"{where}에서 좌표 프레임이 다름: {a.frame} vs {b.frame}"
196
+ return f"{where} 규격이 다름: {a.describe()} vs {b.describe()}"
teul/controller.py ADDED
@@ -0,0 +1,115 @@
1
+ """@controller — 추적, 규격 검사, lowering, 제약 삽입, 지연 예산 측정."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import statistics
7
+ import time
8
+ from typing import Any, Callable, Sequence
9
+
10
+ import torch
11
+ import torch.fx as fx
12
+
13
+ from .check import SPEC_KEY, propagate_and_lower, resolve_annotations
14
+ from .safety import insert_joint_limit_clamp, insert_rate_clamp
15
+ from .types import TeulTypeError
16
+
17
+
18
+ class LatencyBudgetError(RuntimeError):
19
+ """측정된 지연이 예산을 넘었다."""
20
+
21
+
22
+ class TeulController:
23
+ def __init__(self, fn, gm: fx.GraphModule, rate: float, budget_ms: float | None):
24
+ self.fn = fn
25
+ self.graph_module = gm
26
+ self.rate = rate
27
+ self.budget_ms = budget_ms
28
+ self.dt = 1.0 / rate if rate else None
29
+ functools.update_wrapper(self, fn)
30
+
31
+ def __call__(self, *args, **kwargs):
32
+ return self.graph_module(*args, **kwargs)
33
+
34
+ # --- 지연 예산 ---------------------------------------------------------
35
+ def measure(self, example_inputs: Sequence[torch.Tensor], iters: int = 200) -> dict:
36
+ gm = self.graph_module
37
+ with torch.inference_mode():
38
+ for _ in range(max(10, iters // 10)): # warm-up
39
+ gm(*example_inputs)
40
+ samples = []
41
+ for _ in range(iters):
42
+ t0 = time.perf_counter()
43
+ gm(*example_inputs)
44
+ samples.append((time.perf_counter() - t0) * 1e3)
45
+ samples.sort()
46
+ stats = {
47
+ "mean_ms": statistics.fmean(samples),
48
+ "p50_ms": samples[len(samples) // 2],
49
+ "p99_ms": samples[min(len(samples) - 1, int(len(samples) * 0.99))],
50
+ "max_ms": samples[-1],
51
+ }
52
+ if self.budget_ms is not None and stats["p99_ms"] > self.budget_ms:
53
+ raise LatencyBudgetError(
54
+ f"지연 예산 초과: p99 {stats['p99_ms']:.2f}ms > 예산 {self.budget_ms:.2f}ms "
55
+ f"(@{self.rate}Hz). 측정은 이 머신 기준이며 실기체 보증이 아닙니다."
56
+ )
57
+ return stats
58
+
59
+ def specs(self) -> dict[str, str]:
60
+ return {
61
+ n.name: s.describe()
62
+ for n in self.graph_module.graph.nodes
63
+ if (s := n.meta.get(SPEC_KEY)) is not None
64
+ }
65
+
66
+
67
+ def controller(
68
+ *,
69
+ rate: float,
70
+ latency_budget_ms: float | None = None,
71
+ limits: Any = None,
72
+ max_joint_vel: float | None = None,
73
+ max_delta: float | None = None,
74
+ prev_arg: str = "prev_q",
75
+ ) -> Callable[[Callable], TeulController]:
76
+ """제어기 경계를 선언한다.
77
+
78
+ max_joint_vel 은 rad/s 로 주고, 스텝당 한계는 rate 로 나눠 자동 계산한다.
79
+ (max_delta 를 직접 주면 rate 를 바꿀 때 안전 범위가 조용히 달라진다.)
80
+ """
81
+ if max_joint_vel is not None and max_delta is not None:
82
+ raise ValueError("max_joint_vel 과 max_delta 중 하나만 주세요")
83
+ if rate <= 0:
84
+ raise ValueError("rate 는 양수여야 합니다")
85
+
86
+ def deco(fn):
87
+ in_specs, out_spec = resolve_annotations(fn)
88
+ tracer = fx.Tracer()
89
+ try:
90
+ graph = tracer.trace(fn)
91
+ except NameError as e:
92
+ if "submodule" in str(e):
93
+ raise TeulTypeError(
94
+ f"{fn.__name__}: 제어기 안에서 nn.Module 을 직접 호출했습니다. "
95
+ f"학습된 부분은 @op(out=...) 로 감싸 경계 규격을 선언해야 "
96
+ f"추적할 수 있습니다."
97
+ ) from None
98
+ raise
99
+ gm = fx.GraphModule(tracer.root, graph, class_name=f"Teul_{fn.__name__}")
100
+
101
+ propagate_and_lower(gm, in_specs, out_spec)
102
+
103
+ step_delta = max_delta
104
+ if max_joint_vel is not None:
105
+ step_delta = max_joint_vel / rate
106
+ if step_delta is not None:
107
+ insert_rate_clamp(gm, step_delta, prev_arg=prev_arg)
108
+ if limits is not None:
109
+ insert_joint_limit_clamp(gm, limits) # 물리 한계가 항상 마지막
110
+
111
+ ctrl = TeulController(fn, gm, rate, latency_budget_ms)
112
+ ctrl.step_delta = step_delta
113
+ return ctrl
114
+
115
+ return deco
teul/export.py ADDED
@@ -0,0 +1,57 @@
1
+ """내보내기 경로. 제약이 박힌 그래프를 ATen/ONNX/ExecuTorch 로 내린다."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import torch
8
+ import torch.fx as fx
9
+
10
+
11
+ def _as_gm(obj) -> fx.GraphModule:
12
+ gm = getattr(obj, "graph_module", obj)
13
+ if not isinstance(gm, fx.GraphModule):
14
+ raise TypeError(f"fx.GraphModule 또는 TeulController 가 필요합니다: {type(obj).__name__}")
15
+ return gm
16
+
17
+
18
+ def export_program(obj, example_inputs: tuple[torch.Tensor, ...]):
19
+ """torch.export.ExportedProgram 으로 변환한다."""
20
+ gm = _as_gm(obj).eval()
21
+ with torch.inference_mode():
22
+ return torch.export.export(gm, example_inputs)
23
+
24
+
25
+ def export_onnx(obj, example_inputs: tuple[torch.Tensor, ...], output_path: str | Path) -> Path:
26
+ """Jetson/C++ 제어 루프용 ONNX. onnx, onnxscript 가 필요하다."""
27
+ out = Path(output_path)
28
+ out.parent.mkdir(parents=True, exist_ok=True)
29
+ ep = export_program(obj, example_inputs)
30
+ prog = torch.onnx.export(ep, example_inputs, dynamo=True)
31
+ prog.save(str(out))
32
+ return out
33
+
34
+
35
+ def export_executorch(obj, example_inputs: tuple[torch.Tensor, ...], output_path: str | Path) -> Path:
36
+ try:
37
+ from executorch.exir import to_edge
38
+ except ImportError as e: # pragma: no cover
39
+ raise RuntimeError("`pip install executorch` 가 필요합니다") from e
40
+ ep = export_program(obj, example_inputs)
41
+ et = to_edge(ep).to_executorch()
42
+ out = Path(output_path)
43
+ out.parent.mkdir(parents=True, exist_ok=True)
44
+ out.write_bytes(et.buffer)
45
+ return out
46
+
47
+
48
+ def count_onnx_clamps(path: str | Path) -> int:
49
+ """ONNX 에 남은 제약 수. clamp 은 Clip 이 아니라 Max+Min 쌍으로 내려간다.
50
+
51
+ 'Clip' 노드를 세서 제약 생존을 확인하면 0이 나와 잘못된 결론에 이른다.
52
+ """
53
+ import onnx
54
+
55
+ model = onnx.load(str(path))
56
+ ops = [n.op_type for n in model.graph.node]
57
+ return min(ops.count("Max"), ops.count("Min"))
teul/ops.py ADDED
@@ -0,0 +1,165 @@
1
+ """규격을 바꾸는 유일한 경로.
2
+
3
+ fx 추적 중에는 마커 노드만 남기고, 실제 연산은 check 패스가 그래프에 상수로
4
+ 내린다(lowering). torch.fx.Tracer(autowrap_functions=...)에 의존하지 않고
5
+ Proxy를 직접 감지하므로 fx 내부 구현 변화에 덜 민감하다.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import functools
11
+ from typing import Any, Callable
12
+
13
+ import torch
14
+ import torch.fx as fx
15
+
16
+ from .types import Joint, Spec, TeulTypeError, conversion_factor
17
+
18
+ # --- 마커 함수 (그래프에 남는 target) --------------------------------------
19
+
20
+
21
+ def _convert_marker(x: torch.Tensor, unit: str) -> torch.Tensor: # pragma: no cover
22
+ raise RuntimeError("teul: lowering 되지 않은 convert 노드가 실행되었습니다")
23
+
24
+
25
+ def _reorder_marker(x: torch.Tensor, order: str) -> torch.Tensor: # pragma: no cover
26
+ raise RuntimeError("teul: lowering 되지 않은 reorder 노드가 실행되었습니다")
27
+
28
+
29
+ def _reframe_marker(x: torch.Tensor, frame: str) -> torch.Tensor: # pragma: no cover
30
+ raise RuntimeError("teul: lowering 되지 않은 reframe 노드가 실행되었습니다")
31
+
32
+
33
+ MARKERS = (_convert_marker, _reorder_marker, _reframe_marker)
34
+
35
+
36
+ def _proxy_call(x: Any, marker: Callable, arg: str):
37
+ if isinstance(x, fx.Proxy):
38
+ return x.tracer.create_proxy("call_function", marker, (x, arg), {})
39
+ raise TeulTypeError(
40
+ f"{marker.__name__}는 @controller 추적 중에만 쓸 수 있습니다 (받은 값: {type(x).__name__})"
41
+ )
42
+
43
+
44
+ def convert(x, unit: str):
45
+ """단위 변환. 환산 계수는 그래프에 상수로 내려간다."""
46
+ return _proxy_call(x, _convert_marker, unit)
47
+
48
+
49
+ def reorder(x, order: str):
50
+ """관절 순서 변환. 등록된 치환이 index_select 노드로 내려간다."""
51
+ return _proxy_call(x, _reorder_marker, order)
52
+
53
+
54
+ def reframe(x, frame: str):
55
+ """좌표 프레임 변환. 등록된 변환 행렬이 matmul 노드로 내려간다."""
56
+ return _proxy_call(x, _reframe_marker, frame)
57
+
58
+
59
+ # --- 관절 순서 치환 등록 ---------------------------------------------------
60
+
61
+ _PERMUTATIONS: dict[tuple[str, str], list[int]] = {}
62
+
63
+
64
+ def register_joint_order(src: str, dst: str, indices: list[int]) -> None:
65
+ """dst[i] = src[indices[i]] 가 되는 치환과 그 역변환을 등록한다."""
66
+ n = len(indices)
67
+ if sorted(indices) != list(range(n)):
68
+ raise ValueError(f"치환이 아닙니다(0..{n - 1}의 순열이어야 함): {indices}")
69
+ _PERMUTATIONS[(src, dst)] = list(indices)
70
+ inv = [0] * n
71
+ for dst_i, src_i in enumerate(indices):
72
+ inv[src_i] = dst_i
73
+ _PERMUTATIONS[(dst, src)] = inv
74
+
75
+
76
+ def permutation_for(src: str, dst: str) -> list[int]:
77
+ if src == dst:
78
+ raise ValueError("같은 순서끼리는 치환이 없습니다")
79
+ try:
80
+ return _PERMUTATIONS[(src, dst)]
81
+ except KeyError:
82
+ raise TeulTypeError(
83
+ f"등록되지 않은 관절 순서 변환: {src!r} -> {dst!r} "
84
+ f"(register_joint_order 로 먼저 등록하세요)"
85
+ ) from None
86
+
87
+
88
+ def reorder_tensor(x: torch.Tensor, src: str, dst: str) -> torch.Tensor:
89
+ """런타임(비추적) 경로용. 시뮬레이터 쪽 전처리에 쓴다."""
90
+ if src == dst:
91
+ return x
92
+ idx = torch.as_tensor(permutation_for(src, dst), dtype=torch.long, device=x.device)
93
+ return torch.index_select(x, dim=-1, index=idx)
94
+
95
+
96
+ # --- 좌표 프레임 변환 등록 -------------------------------------------------
97
+
98
+ _TRANSFORMS: dict[tuple[str, str], torch.Tensor] = {}
99
+
100
+
101
+ def register_frame_transform(src: str, dst: str, matrix: torch.Tensor) -> None:
102
+ """dst_vec = matrix @ src_vec. 직교행렬이면 역변환도 자동 등록한다."""
103
+ m = torch.as_tensor(matrix, dtype=torch.float32)
104
+ if m.ndim != 2 or m.shape[0] != m.shape[1]:
105
+ raise ValueError(f"정방행렬이어야 합니다: {tuple(m.shape)}")
106
+ _TRANSFORMS[(src, dst)] = m
107
+ inv = torch.linalg.inv(m)
108
+ _TRANSFORMS[(dst, src)] = inv
109
+
110
+
111
+ def transform_for(src: str, dst: str) -> torch.Tensor:
112
+ try:
113
+ return _TRANSFORMS[(src, dst)]
114
+ except KeyError:
115
+ raise TeulTypeError(
116
+ f"등록되지 않은 프레임 변환: {src!r} -> {dst!r} "
117
+ f"(register_frame_transform 로 변환 행렬을 등록하세요. "
118
+ f"표기만 바꾸는 reframe 은 허용하지 않습니다)"
119
+ ) from None
120
+
121
+
122
+ # --- @op: 학습된 정책의 경계 ----------------------------------------------
123
+
124
+
125
+ def op(out: Spec, **in_specs: Spec):
126
+ """학습된 정책 등 내부를 신뢰하지 않는 연산의 경계 규격을 선언한다."""
127
+
128
+ def deco(fn):
129
+ @functools.wraps(fn)
130
+ def wrapper(*args, **kwargs):
131
+ proxies = [a for a in (*args, *kwargs.values()) if isinstance(a, fx.Proxy)]
132
+ if not proxies:
133
+ return fn(*args, **kwargs)
134
+ p = proxies[0].tracer.create_proxy("call_function", wrapper, args, kwargs)
135
+ p.node.meta["teul_spec"] = out
136
+ return p
137
+
138
+ wrapper._teul_out = out
139
+ wrapper._teul_in = in_specs
140
+ wrapper._teul_impl = fn
141
+ return wrapper
142
+
143
+ return deco
144
+
145
+
146
+ def clear_registries() -> None:
147
+ """테스트용."""
148
+ _PERMUTATIONS.clear()
149
+ _TRANSFORMS.clear()
150
+
151
+
152
+ __all__ = [
153
+ "convert",
154
+ "reorder",
155
+ "reframe",
156
+ "op",
157
+ "register_joint_order",
158
+ "register_frame_transform",
159
+ "reorder_tensor",
160
+ "permutation_for",
161
+ "transform_for",
162
+ "clear_registries",
163
+ "Joint",
164
+ "conversion_factor",
165
+ ]
teul/safety.py ADDED
@@ -0,0 +1,88 @@
1
+ """안전 제약을 그래프 안에 심는 패스. 런타임 감시가 아니다."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+ import torch.fx as fx
7
+
8
+ from .types import TeulTypeError
9
+
10
+
11
+ def _find(graph: fx.Graph, target: str) -> fx.Node | None:
12
+ """placeholder 를 name 이 아니라 target(원래 인자 이름)으로 찾는다.
13
+ fx 는 name 을 재명명할 수 있으므로 name 매칭은 깨진다."""
14
+ for n in graph.nodes:
15
+ if n.op == "placeholder" and n.target == target:
16
+ return n
17
+ return None
18
+
19
+
20
+ def _output(graph: fx.Graph) -> fx.Node:
21
+ for n in reversed(graph.nodes):
22
+ if n.op == "output":
23
+ return n
24
+ raise TeulTypeError("output 노드가 없습니다") # pragma: no cover
25
+
26
+
27
+ def insert_rate_clamp(
28
+ gm: fx.GraphModule,
29
+ max_delta: float,
30
+ prev_arg: str = "prev_q",
31
+ ) -> fx.GraphModule:
32
+ """출력이 이전 스텝 명령에서 max_delta 이상 급변하지 못하게 한다.
33
+
34
+ clamp(q_out, prev_q - max_delta, prev_q + max_delta)
35
+ """
36
+ graph = gm.graph
37
+ prev = _find(graph, prev_arg)
38
+ if prev is None:
39
+ raise TeulTypeError(
40
+ f"변화율 제약을 넣을 수 없습니다: 제어기 입력에 {prev_arg!r}가 없습니다. "
41
+ f"이전 스텝 명령을 인자로 받아야 합니다(내보낸 그래프는 상태를 못 가집니다)."
42
+ )
43
+ out = _output(graph)
44
+ raw = out.args[0]
45
+ with graph.inserting_before(out):
46
+ low = graph.call_function(torch.sub, (prev, max_delta))
47
+ high = graph.call_function(torch.add, (prev, max_delta))
48
+ clamped = graph.call_function(torch.clamp, (raw,), {"min": low, "max": high})
49
+ clamped.meta.update(raw.meta if isinstance(raw, fx.Node) else {})
50
+ out.args = (clamped,)
51
+ graph.lint()
52
+ gm.recompile()
53
+ return gm
54
+
55
+
56
+ def insert_joint_limit_clamp(
57
+ gm: fx.GraphModule,
58
+ limits: tuple[list[float], list[float]] | list[tuple[float, float]],
59
+ ) -> fx.GraphModule:
60
+ """관절 물리 한계로 출력을 자른다. 항상 마지막에 적용한다."""
61
+ if isinstance(limits, tuple) and len(limits) == 2 and isinstance(limits[0], (list, tuple)):
62
+ lo_v, hi_v = list(limits[0]), list(limits[1])
63
+ else:
64
+ lo_v = [p[0] for p in limits] # type: ignore[index]
65
+ hi_v = [p[1] for p in limits] # type: ignore[index]
66
+ if len(lo_v) != len(hi_v):
67
+ raise TeulTypeError("관절 한계 하한/상한 길이가 다릅니다")
68
+ if any(l > h for l, h in zip(lo_v, hi_v)):
69
+ raise TeulTypeError("관절 한계에 하한 > 상한인 항목이 있습니다")
70
+
71
+ graph = gm.graph
72
+ gm.register_buffer("_teul_lo", torch.tensor(lo_v, dtype=torch.float32))
73
+ gm.register_buffer("_teul_hi", torch.tensor(hi_v, dtype=torch.float32))
74
+ out = _output(graph)
75
+ raw = out.args[0]
76
+ with graph.inserting_before(out):
77
+ lo = graph.get_attr("_teul_lo")
78
+ hi = graph.get_attr("_teul_hi")
79
+ clamped = graph.call_function(torch.clamp, (raw,), {"min": lo, "max": hi})
80
+ clamped.meta.update(raw.meta if isinstance(raw, fx.Node) else {})
81
+ out.args = (clamped,)
82
+ graph.lint()
83
+ gm.recompile()
84
+ return gm
85
+
86
+
87
+ def count_clamps(gm: fx.GraphModule) -> int:
88
+ return sum(1 for n in gm.graph.nodes if n.op == "call_function" and n.target is torch.clamp)
teul/types.py ADDED
@@ -0,0 +1,102 @@
1
+ """단위·좌표계·관절순서 규격.
2
+
3
+ 설계 요점: 관절 순서(order)와 좌표 프레임(frame)을 하나의 키워드로 섞지 않는다.
4
+ 관절 순서 불일치는 인덱스 치환(permutation)으로 풀리고,
5
+ 좌표 프레임 불일치는 변환 행렬로 풀린다. 수학이 다르므로 타입도 분리한다.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, replace
11
+
12
+
13
+ class TeulTypeError(TypeError):
14
+ """규격 불일치. 로봇을 켜기 전에 던진다."""
15
+
16
+
17
+ class Spec:
18
+ """모든 규격의 상위 타입."""
19
+
20
+ def describe(self) -> str:
21
+ return repr(self)
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Joint(Spec):
26
+ """관절 벡터. n개 관절, 단위, 관절 순서 규격."""
27
+
28
+ n: int
29
+ unit: str = "rad"
30
+ order: str = "canonical"
31
+
32
+ def describe(self) -> str:
33
+ return f"Joint({self.n}, {self.unit!r}, order={self.order!r})"
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Pose(Spec):
38
+ """좌표 프레임에 붙은 위치/자세."""
39
+
40
+ frame: str
41
+ unit: str = "m"
42
+ dim: int = 6
43
+
44
+ def describe(self) -> str:
45
+ return f"Pose(frame={self.frame!r}, {self.unit!r}, dim={self.dim})"
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Scalar(Spec):
50
+ unit: str
51
+
52
+ def describe(self) -> str:
53
+ return f"Scalar({self.unit!r})"
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Image(Spec):
58
+ h: int
59
+ w: int
60
+ c: int = 3
61
+ layout: str = "HWC"
62
+
63
+ def describe(self) -> str:
64
+ return f"Image({self.h}x{self.w}x{self.c}, {self.layout})"
65
+
66
+
67
+ # --- 단위 환산 -------------------------------------------------------------
68
+ # 같은 물리량군(group) 안에서만 환산한다. 군이 다르면 환산이 아니라 오류다.
69
+ _UNIT_GROUPS: dict[str, dict[str, float]] = {
70
+ "angle": {"rad": 1.0, "deg": 3.141592653589793 / 180.0, "mrad": 1e-3},
71
+ "length": {"m": 1.0, "mm": 1e-3, "cm": 1e-2},
72
+ "angular_velocity": {"rad/s": 1.0, "deg/s": 3.141592653589793 / 180.0},
73
+ "velocity": {"m/s": 1.0, "mm/s": 1e-3},
74
+ "torque": {"Nm": 1.0, "mNm": 1e-3},
75
+ }
76
+
77
+
78
+ def _group_of(unit: str) -> str | None:
79
+ for g, table in _UNIT_GROUPS.items():
80
+ if unit in table:
81
+ return g
82
+ return None
83
+
84
+
85
+ def conversion_factor(src: str, dst: str) -> float:
86
+ """src 단위 값에 곱해 dst 단위로 만드는 상수."""
87
+ if src == dst:
88
+ return 1.0
89
+ gs, gd = _group_of(src), _group_of(dst)
90
+ if gs is None:
91
+ raise TeulTypeError(f"모르는 단위: {src!r}")
92
+ if gd is None:
93
+ raise TeulTypeError(f"모르는 단위: {dst!r}")
94
+ if gs != gd:
95
+ raise TeulTypeError(f"환산 불가(물리량군이 다름): {src!r}({gs}) -> {dst!r}({gd})")
96
+ return _UNIT_GROUPS[gs][src] / _UNIT_GROUPS[gd][dst]
97
+
98
+
99
+ def with_unit(spec: Spec, unit: str) -> Spec:
100
+ if not hasattr(spec, "unit"):
101
+ raise TeulTypeError(f"단위가 없는 규격: {spec.describe()}")
102
+ return replace(spec, unit=unit) # type: ignore[arg-type]
@@ -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]"`).
@@ -0,0 +1,12 @@
1
+ teul/__init__.py,sha256=pCPq_pNGzKgtT3QSADt6F17-2XqRplKwNujMlUlXrvU,1099
2
+ teul/check.py,sha256=3LcYqcLDqU958XWGDsb0E-asEBfz83Goxv4dkM11Hbc,8044
3
+ teul/controller.py,sha256=kiX17cID1o-bWHLDajJgpnNeyKSRLhCzfCD3J6LO1_I,4164
4
+ teul/export.py,sha256=qfJ1zsDV5nfnRXqc0l1LrcL_ypR70mUtcurDkrGZujw,1982
5
+ teul/ops.py,sha256=OD-yN05oWv6dooKahborbLmWzopAYUDQlHSHzYY-yz4,5518
6
+ teul/safety.py,sha256=ROezBnt_OTEIUb_lIJHNZmPF7801kiowX7Ea6VQJTZE,3302
7
+ teul/types.py,sha256=rsAsOjYPRkECoBkzq7USTlTM-StNxsbsBXD9_SApwAE,2918
8
+ teul-0.2.0.dist-info/licenses/LICENSE,sha256=n-vaUPBt1LW9KttG1wv4NCs9V0E-0tQMjjG0mffqCXU,304
9
+ teul-0.2.0.dist-info/METADATA,sha256=i0M9TlGeAoCUub0NGy4dn4BTxO6H3kxOkW2YCW1K9cE,5753
10
+ teul-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ teul-0.2.0.dist-info/top_level.txt,sha256=iCmjEpyhk_hHWDCPO3Qi3xxPHemBGF14WMXv0fGSybE,5
12
+ teul-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,7 @@
1
+ Apache License 2.0
2
+
3
+ Teul 은 Apache-2.0 으로 배포됩니다.
4
+ 전문: https://www.apache.org/licenses/LICENSE-2.0
5
+
6
+ GitHub 에서 "Add file > Create new file > LICENSE" 로 들어가면
7
+ Apache-2.0 전문을 템플릿으로 바로 넣을 수 있습니다. 이 파일을 그 전문으로 교체하세요.
@@ -0,0 +1 @@
1
+ teul