human-movement-research 0.1.1__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.
- human_movement_research-0.1.1/CITATION.cff +11 -0
- human_movement_research-0.1.1/CONTRIBUTORS.md +5 -0
- human_movement_research-0.1.1/LICENSE +21 -0
- human_movement_research-0.1.1/PKG-INFO +32 -0
- human_movement_research-0.1.1/README.md +12 -0
- human_movement_research-0.1.1/pyproject.toml +43 -0
- human_movement_research-0.1.1/pyproject.toml.orig +30 -0
- human_movement_research-0.1.1/src/human_movement_research/__init__.py +3 -0
- human_movement_research-0.1.1/src/human_movement_research/cli.py +25 -0
- human_movement_research-0.1.1/src/human_movement_research/data.py +48 -0
- human_movement_research-0.1.1/src/human_movement_research/inference.py +66 -0
- human_movement_research-0.1.1/src/human_movement_research/model.py +41 -0
- human_movement_research-0.1.1/src/human_movement_research/training.py +92 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
cff-version: 1.2.0
|
|
2
|
+
message: "If you use Human Movement, please cite this software."
|
|
3
|
+
type: software
|
|
4
|
+
title: Human Movement Research
|
|
5
|
+
version: 0.1.1
|
|
6
|
+
date-released: 2026-11-06
|
|
7
|
+
authors:
|
|
8
|
+
- family-names: Galal
|
|
9
|
+
given-names: Karim
|
|
10
|
+
license: MIT
|
|
11
|
+
abstract: "Windows-first personalized cursor trajectories and input timing for computer-use applications."
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# Contributor
|
|
2
|
+
|
|
3
|
+
Karim Galal is the sole contributor and maintainer of Human Movement.
|
|
4
|
+
|
|
5
|
+
External libraries, datasets, research papers and engineering baselines retain their original ownership and attribution. They are references or dependencies, rather than contributors to this package.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Karim Galal
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: human-movement-research
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Optional conditional diffusion research for timed cursor trajectories
|
|
5
|
+
Author: Karim Galal
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Dist: numpy>=2.1
|
|
13
|
+
Requires-Dist: torch>=2.6
|
|
14
|
+
Requires-Dist: onnx>=1.17 ; extra == 'onnx'
|
|
15
|
+
Requires-Dist: onnxruntime>=1.20 ; extra == 'onnx'
|
|
16
|
+
Maintainer: Karim Galal
|
|
17
|
+
Requires-Python: >=3.12
|
|
18
|
+
Provides-Extra: onnx
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# Human Movement Research
|
|
22
|
+
|
|
23
|
+
Optional conditional trajectory diffusion training, CPU export and inference tools. Developed and maintained solely by Karim Galal.
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pip install human-movement-research
|
|
27
|
+
human-movement-research --help
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Requires NumPy and PyTorch. No trained, independently validated checkpoint is bundled. Training examples and tests validate the pipeline; they do not establish human behavioral fidelity. The core SDK works without this package and falls back to analytical generation when a neural model is unavailable or invalid.
|
|
31
|
+
|
|
32
|
+
Licensed under MIT. See the included LICENSE file.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Human Movement Research
|
|
2
|
+
|
|
3
|
+
Optional conditional trajectory diffusion training, CPU export and inference tools. Developed and maintained solely by Karim Galal.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install human-movement-research
|
|
7
|
+
human-movement-research --help
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Requires NumPy and PyTorch. No trained, independently validated checkpoint is bundled. Training examples and tests validate the pipeline; they do not establish human behavioral fidelity. The core SDK works without this package and falls back to analytical generation when a neural model is unavailable or invalid.
|
|
11
|
+
|
|
12
|
+
Licensed under MIT. See the included LICENSE file.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "human-movement-research"
|
|
3
|
+
version = "0.1.1"
|
|
4
|
+
readme = "README.md"
|
|
5
|
+
description = "Optional conditional diffusion research for timed cursor trajectories"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"numpy>=2.1",
|
|
9
|
+
"torch>=2.6",
|
|
10
|
+
]
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
16
|
+
"Programming Language :: Python :: 3.12",
|
|
17
|
+
"Typing :: Typed",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[[project.authors]]
|
|
21
|
+
name = "Karim Galal"
|
|
22
|
+
|
|
23
|
+
[[project.maintainers]]
|
|
24
|
+
name = "Karim Galal"
|
|
25
|
+
|
|
26
|
+
[project.scripts]
|
|
27
|
+
human-movement-research = "human_movement_research.cli:main"
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
onnx = [
|
|
31
|
+
"onnx>=1.17",
|
|
32
|
+
"onnxruntime>=1.20",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["uv_build>=0.13.7,<0.14.0"]
|
|
37
|
+
build-backend = "uv_build"
|
|
38
|
+
|
|
39
|
+
[tool.uv.build-backend]
|
|
40
|
+
source-include = [
|
|
41
|
+
"CITATION.cff",
|
|
42
|
+
"CONTRIBUTORS.md",
|
|
43
|
+
]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "human-movement-research"
|
|
3
|
+
version = "0.1.1"
|
|
4
|
+
readme = "README.md"
|
|
5
|
+
description = "Optional conditional diffusion research for timed cursor trajectories"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
dependencies = ["numpy>=2.1", "torch>=2.6"]
|
|
8
|
+
license = "MIT"
|
|
9
|
+
license-files = ["LICENSE"]
|
|
10
|
+
authors = [{name = "Karim Galal"}]
|
|
11
|
+
maintainers = [{name = "Karim Galal"}]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 3 - Alpha",
|
|
14
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
15
|
+
"Programming Language :: Python :: 3.12",
|
|
16
|
+
"Typing :: Typed",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.scripts]
|
|
20
|
+
human-movement-research = "human_movement_research.cli:main"
|
|
21
|
+
|
|
22
|
+
[project.optional-dependencies]
|
|
23
|
+
onnx = ["onnx>=1.17", "onnxruntime>=1.20"]
|
|
24
|
+
|
|
25
|
+
[build-system]
|
|
26
|
+
requires = ["uv_build>=0.13.7,<0.14.0"]
|
|
27
|
+
build-backend = "uv_build"
|
|
28
|
+
|
|
29
|
+
[tool.uv.build-backend]
|
|
30
|
+
source-include = ["CITATION.cff", "CONTRIBUTORS.md"]
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def main(argv=None):
|
|
7
|
+
parser = argparse.ArgumentParser(prog="human-movement-research")
|
|
8
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
9
|
+
train = commands.add_parser("train")
|
|
10
|
+
train.add_argument("input", type=Path)
|
|
11
|
+
train.add_argument("output", type=Path)
|
|
12
|
+
train.add_argument("--epochs", type=int, default=100)
|
|
13
|
+
train.add_argument("--seed", type=int, default=17842)
|
|
14
|
+
export = commands.add_parser("export")
|
|
15
|
+
export.add_argument("checkpoint", type=Path)
|
|
16
|
+
export.add_argument("output", type=Path)
|
|
17
|
+
args = parser.parse_args(argv)
|
|
18
|
+
from . import training
|
|
19
|
+
|
|
20
|
+
if args.command == "train":
|
|
21
|
+
rows = [json.loads(line) for line in args.input.read_text().splitlines() if line.strip()]
|
|
22
|
+
result = training.train(rows, args.output, epochs=args.epochs, seed=args.seed)
|
|
23
|
+
else:
|
|
24
|
+
result = training.export(args.checkpoint, args.output)
|
|
25
|
+
print(json.dumps(result, indent=2))
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Retain event time while resampling positions by event index."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from .model import LENGTH
|
|
8
|
+
|
|
9
|
+
DEFAULT_PROFILE = [0.10, 0.13, 0.15, 0.045, 0.025, 0.18, 0.008, 0.1]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def condition(displacement, width, duration, profile):
|
|
13
|
+
dx, dy = displacement
|
|
14
|
+
return np.asarray(
|
|
15
|
+
[dx / 2000, dy / 2000, math.log1p(width) / 6, math.log(max(duration, 0.01)), *profile],
|
|
16
|
+
dtype=np.float32,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def preprocess(trace: dict) -> tuple[np.ndarray, np.ndarray]:
|
|
21
|
+
if trace.get("split") != "generator_train" or trace.get("label") != "human":
|
|
22
|
+
raise ValueError("Neural fitting accepts only human generator_train recordings")
|
|
23
|
+
events = [e for e in trace["events"] if e.get("kind") == "move"]
|
|
24
|
+
if len(events) < 5:
|
|
25
|
+
raise ValueError("A trajectory needs at least five timed positions")
|
|
26
|
+
values = np.asarray([[e["x"], e["y"], e["t"]] for e in events], dtype=float)
|
|
27
|
+
if not np.isfinite(values).all() or np.any(np.diff(values[:, 2]) <= 0):
|
|
28
|
+
raise ValueError("Trajectory times must be finite and strictly increasing")
|
|
29
|
+
start, goal = values[0, :2], values[-1, :2]
|
|
30
|
+
duration = values[-1, 2] - values[0, 2]
|
|
31
|
+
delta, distance = goal - start, np.linalg.norm(goal - start)
|
|
32
|
+
if distance < 1 or not 0.01 <= duration <= 60:
|
|
33
|
+
raise ValueError("Unsupported displacement/duration")
|
|
34
|
+
positions = np.linspace(0, len(events) - 1, LENGTH)
|
|
35
|
+
samples = np.stack(
|
|
36
|
+
[np.interp(positions, np.arange(len(events)), values[:, i]) for i in range(3)], axis=1
|
|
37
|
+
)
|
|
38
|
+
u = np.linspace(0, 1, LENGTH)
|
|
39
|
+
base = start[None, :] + u[:, None] * delta
|
|
40
|
+
residual = (samples[:, :2] - base) / distance
|
|
41
|
+
increments = np.diff(samples[:, 2]) / duration * (LENGTH - 1)
|
|
42
|
+
log_dt = np.r_[0, np.log(np.maximum(increments, 1e-6))]
|
|
43
|
+
data = np.vstack((residual.T, log_dt))
|
|
44
|
+
width = float(trace.get("target_width", 24))
|
|
45
|
+
profile = trace.get("profile_features", DEFAULT_PROFILE)
|
|
46
|
+
if len(profile) != 8:
|
|
47
|
+
raise ValueError("Expected eight personal conditioning features")
|
|
48
|
+
return data.astype(np.float32), condition(delta, width, duration, profile)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
from .data import condition
|
|
12
|
+
from .model import LENGTH, STEPS, schedule
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@lru_cache(maxsize=2)
|
|
16
|
+
def _load(path: str, modified_ns: int, size: int):
|
|
17
|
+
p = Path(path)
|
|
18
|
+
manifest = json.loads(p.with_suffix(".manifest.json").read_text())
|
|
19
|
+
if manifest.get("architecture") != "hm-diffusion-tcn-1" or not manifest.get(
|
|
20
|
+
"validated", {}
|
|
21
|
+
).get("cpu_parity"):
|
|
22
|
+
raise ValueError("Unsupported or unvalidated checkpoint")
|
|
23
|
+
if manifest["sha256"] != hashlib.sha256(p.read_bytes()).hexdigest():
|
|
24
|
+
raise ValueError("Model checksum mismatch")
|
|
25
|
+
return torch.jit.load(str(p), map_location="cpu").eval()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def generate(
|
|
29
|
+
path: str,
|
|
30
|
+
*,
|
|
31
|
+
start,
|
|
32
|
+
goal,
|
|
33
|
+
duration: float,
|
|
34
|
+
target_width: float,
|
|
35
|
+
profile_features: list[float],
|
|
36
|
+
seed: int = 0,
|
|
37
|
+
) -> list[tuple[float, float, float]]:
|
|
38
|
+
p = Path(path)
|
|
39
|
+
model = _load(str(p.resolve()), p.stat().st_mtime_ns, p.stat().st_size)
|
|
40
|
+
rng = torch.Generator().manual_seed(seed)
|
|
41
|
+
delta = np.asarray(goal, dtype=float) - start
|
|
42
|
+
cond = torch.tensor(condition(delta, target_width, duration, profile_features)[None])
|
|
43
|
+
beta, alpha, cumulative = schedule()
|
|
44
|
+
x = torch.randn((1, 3, LENGTH), generator=rng)
|
|
45
|
+
with torch.inference_mode():
|
|
46
|
+
for i in range(STEPS - 1, -1, -1):
|
|
47
|
+
epsilon = model(x, torch.tensor([i / (STEPS - 1)]), cond)
|
|
48
|
+
x = (x - beta[i] / torch.sqrt(1 - cumulative[i]) * epsilon) / torch.sqrt(alpha[i])
|
|
49
|
+
if i:
|
|
50
|
+
variance = beta[i] * (1 - cumulative[i - 1]) / (1 - cumulative[i])
|
|
51
|
+
x += variance.sqrt() * torch.randn(x.shape, generator=rng)
|
|
52
|
+
values = x[0].numpy()
|
|
53
|
+
if not np.isfinite(values).all():
|
|
54
|
+
raise ValueError("Nonfinite neural generation")
|
|
55
|
+
u = np.linspace(0, 1, LENGTH)
|
|
56
|
+
residual = values[:2].T
|
|
57
|
+
residual -= (1 - u[:, None]) * residual[0] + u[:, None] * residual[-1]
|
|
58
|
+
# Reject implausible untrained outputs instead of silently clipping them into a path.
|
|
59
|
+
if np.max(np.abs(residual)) > 0.5:
|
|
60
|
+
raise ValueError("Neural path failed spatial residual validation")
|
|
61
|
+
xy = np.asarray(start) + u[:, None] * delta + residual * np.linalg.norm(delta)
|
|
62
|
+
increments = np.exp(np.clip(values[2, 1:], -5, 5))
|
|
63
|
+
times = np.r_[0, np.cumsum(increments) / increments.sum() * duration]
|
|
64
|
+
xy[0], xy[-1] = start, goal
|
|
65
|
+
times[-1] = duration
|
|
66
|
+
return [(float(p[0]), float(p[1]), float(t)) for p, t in zip(xy, times, strict=True)]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Compact conditional temporal diffusion; independent of the desktop runtime."""
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from torch import nn
|
|
5
|
+
|
|
6
|
+
LENGTH, CHANNELS, CONDITION_SIZE, STEPS = 64, 32, 12, 32
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Denoiser(nn.Module):
|
|
10
|
+
def __init__(self):
|
|
11
|
+
super().__init__()
|
|
12
|
+
self.input = nn.Conv1d(3, CHANNELS, 3, padding=1)
|
|
13
|
+
self.condition = nn.Sequential(
|
|
14
|
+
nn.Linear(CONDITION_SIZE + 3, CHANNELS), nn.SiLU(), nn.Linear(CHANNELS, CHANNELS)
|
|
15
|
+
)
|
|
16
|
+
self.blocks = nn.ModuleList(
|
|
17
|
+
[
|
|
18
|
+
nn.Sequential(
|
|
19
|
+
nn.Conv1d(CHANNELS, CHANNELS, 3, padding=d, dilation=d),
|
|
20
|
+
nn.SiLU(),
|
|
21
|
+
nn.Conv1d(CHANNELS, CHANNELS, 1),
|
|
22
|
+
)
|
|
23
|
+
for d in (1, 2, 4, 8)
|
|
24
|
+
]
|
|
25
|
+
)
|
|
26
|
+
self.output = nn.Conv1d(CHANNELS, 3, 3, padding=1)
|
|
27
|
+
|
|
28
|
+
def forward(self, x: torch.Tensor, step: torch.Tensor, condition: torch.Tensor) -> torch.Tensor:
|
|
29
|
+
time = torch.stack(
|
|
30
|
+
(step, torch.sin(step * 3.14159265), torch.cos(step * 3.14159265)), dim=1
|
|
31
|
+
)
|
|
32
|
+
h = self.input(x) + self.condition(torch.cat((condition, time), dim=1)).unsqueeze(-1)
|
|
33
|
+
for block in self.blocks:
|
|
34
|
+
h = h + block(h) * 0.25
|
|
35
|
+
return self.output(h)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def schedule():
|
|
39
|
+
beta = torch.linspace(0.0001, 0.05, STEPS)
|
|
40
|
+
alpha = 1 - beta
|
|
41
|
+
return beta, alpha, torch.cumprod(alpha, dim=0)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from .data import preprocess
|
|
11
|
+
from .model import CONDITION_SIZE, LENGTH, STEPS, Denoiser, schedule
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def train(traces: list[dict], output: str | Path, *, epochs: int = 100, seed: int = 17842) -> dict:
|
|
15
|
+
if not traces or epochs < 1:
|
|
16
|
+
raise ValueError("Provide training traces and at least one epoch")
|
|
17
|
+
torch.manual_seed(seed)
|
|
18
|
+
torch.set_num_threads(2)
|
|
19
|
+
torch.use_deterministic_algorithms(True)
|
|
20
|
+
pairs = [preprocess(trace) for trace in traces]
|
|
21
|
+
x = torch.tensor(np.stack([p[0] for p in pairs]))
|
|
22
|
+
conditions = torch.tensor(np.stack([p[1] for p in pairs]))
|
|
23
|
+
model = Denoiser()
|
|
24
|
+
optimizer = torch.optim.AdamW(model.parameters(), lr=0.001)
|
|
25
|
+
_, _, cumulative = schedule()
|
|
26
|
+
losses = []
|
|
27
|
+
for _ in range(epochs):
|
|
28
|
+
total = 0.0
|
|
29
|
+
for indices in torch.randperm(len(x)).split(32):
|
|
30
|
+
batch = x[indices]
|
|
31
|
+
step = torch.randint(STEPS, (len(indices),))
|
|
32
|
+
noise = torch.randn_like(batch)
|
|
33
|
+
a = cumulative[step, None, None]
|
|
34
|
+
corrupted = a.sqrt() * batch + (1 - a).sqrt() * noise
|
|
35
|
+
loss = torch.nn.functional.mse_loss(
|
|
36
|
+
model(corrupted, step.float() / (STEPS - 1), conditions[indices]), noise
|
|
37
|
+
)
|
|
38
|
+
optimizer.zero_grad()
|
|
39
|
+
loss.backward()
|
|
40
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1)
|
|
41
|
+
optimizer.step()
|
|
42
|
+
total += loss.item() * len(indices)
|
|
43
|
+
losses.append(total / len(x))
|
|
44
|
+
output = Path(output)
|
|
45
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
provenance = {
|
|
47
|
+
"architecture": "hm-diffusion-tcn-1",
|
|
48
|
+
"seed": seed,
|
|
49
|
+
"epochs": epochs,
|
|
50
|
+
"samples": len(traces),
|
|
51
|
+
"training_sha256": hashlib.sha256(json.dumps(traces, sort_keys=True).encode()).hexdigest(),
|
|
52
|
+
"participants": sorted({t["participant_id"] for t in traces}),
|
|
53
|
+
"sessions": sorted({t["session_id"] for t in traces}),
|
|
54
|
+
"loss": losses,
|
|
55
|
+
"quality": "research candidate; no behavioral fidelity certification",
|
|
56
|
+
}
|
|
57
|
+
torch.save({"weights": model.state_dict(), "provenance": provenance}, output)
|
|
58
|
+
output.with_suffix(".json").write_text(json.dumps(provenance, indent=2), encoding="utf-8")
|
|
59
|
+
return provenance
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def export(checkpoint: str | Path, output: str | Path) -> dict:
|
|
63
|
+
saved = torch.load(checkpoint, map_location="cpu", weights_only=True)
|
|
64
|
+
model = Denoiser().eval()
|
|
65
|
+
model.load_state_dict(saved["weights"])
|
|
66
|
+
scripted = torch.jit.script(model)
|
|
67
|
+
torch.manual_seed(100)
|
|
68
|
+
with torch.inference_mode():
|
|
69
|
+
for _ in range(4):
|
|
70
|
+
x, t, c = torch.randn(2, 3, LENGTH), torch.rand(2), torch.randn(2, CONDITION_SIZE)
|
|
71
|
+
reference, candidate = model(x, t, c), scripted(x, t, c)
|
|
72
|
+
if not torch.isfinite(candidate).all() or not torch.allclose(
|
|
73
|
+
reference, candidate, atol=1e-5
|
|
74
|
+
):
|
|
75
|
+
raise ValueError("CPU export parity/finite-output validation failed")
|
|
76
|
+
output = Path(output)
|
|
77
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
scripted.save(str(output))
|
|
79
|
+
manifest = {
|
|
80
|
+
"format": "torchscript",
|
|
81
|
+
"architecture": "hm-diffusion-tcn-1",
|
|
82
|
+
"steps": STEPS,
|
|
83
|
+
"length": LENGTH,
|
|
84
|
+
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
|
|
85
|
+
"validated": {"cpu_parity": True, "finite_outputs": True},
|
|
86
|
+
"behavioral_validation": False,
|
|
87
|
+
"provenance": saved["provenance"],
|
|
88
|
+
}
|
|
89
|
+
output.with_suffix(".manifest.json").write_text(
|
|
90
|
+
json.dumps(manifest, indent=2), encoding="utf-8"
|
|
91
|
+
)
|
|
92
|
+
return manifest
|