Upload human-like robot nav model
Browse files- README.md +154 -0
- checkpoint.pt +3 -0
- config.json +21 -0
- model.pt +3 -0
- model_architecture.py +545 -0
- normalization_stats.json +30 -0
README.md
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
tags:
|
| 3 |
+
- robotics
|
| 4 |
+
- trajectory-generation
|
| 5 |
+
- diffusion-model
|
| 6 |
+
- navigation
|
| 7 |
+
- human-like-motion
|
| 8 |
+
- ddpm
|
| 9 |
+
library_name: pytorch
|
| 10 |
+
pipeline_tag: reinforcement-learning
|
| 11 |
+
license: mit
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# ๐ค๐ถ Human-Like Robot Navigation Trajectory Generator
|
| 15 |
+
|
| 16 |
+
A **DDPM (Denoising Diffusion Probabilistic Model)** that generates human-like 2D navigation trajectories for robots.
|
| 17 |
+
|
| 18 |
+
## What It Does
|
| 19 |
+
|
| 20 |
+
Given a robot's current state (position + velocity) and a goal, this model generates future waypoints that mimic human walking โ smooth curves, natural speed changes, and obstacle-aware paths.
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
Input: [x, y, vx, vy] + [goal_x, goal_y]
|
| 24 |
+
โ DDPM Reverse Diffusion (100 steps)
|
| 25 |
+
โ 1D Temporal UNet + FiLM conditioning
|
| 26 |
+
Output: 16 future waypoints [dx, dy]
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## Key Features
|
| 30 |
+
|
| 31 |
+
- ๐ถ **Human-like paths** โ smooth curves, not robotic straight lines
|
| 32 |
+
- โก **Variable speed** โ acceleration, cruising, deceleration like real walking
|
| 33 |
+
- ๐งฑ **Obstacle aware** โ learned from social force model training data
|
| 34 |
+
- ๐ฒ **Multi-modal** โ generates diverse trajectory samples via diffusion
|
| 35 |
+
- ๐ฏ **Goal-directed** โ conditions on target position
|
| 36 |
+
|
| 37 |
+
## Architecture
|
| 38 |
+
|
| 39 |
+
| Component | Details |
|
| 40 |
+
|-----------|---------|
|
| 41 |
+
| Backbone | 1D Temporal UNet ([64, 128, 256]) |
|
| 42 |
+
| Conditioning | FiLM (Feature-wise Linear Modulation) |
|
| 43 |
+
| Noise Schedule | Cosine (Improved DDPM) |
|
| 44 |
+
| Diffusion Steps | 100 |
|
| 45 |
+
| Parameters | 1,801,538 (1.8M) |
|
| 46 |
+
| Prediction | ฮต-prediction (noise) |
|
| 47 |
+
|
| 48 |
+
## Based On
|
| 49 |
+
|
| 50 |
+
- [Diffusion Policy](https://arxiv.org/abs/2303.04137) (Chi et al., RSS 2023)
|
| 51 |
+
- [TRACE](https://arxiv.org/abs/2304.01893) (Rempe et al., CVPR 2023)
|
| 52 |
+
- [Improved DDPM](https://arxiv.org/abs/2102.09672) (Nichol & Dhariwal, 2021)
|
| 53 |
+
|
| 54 |
+
## Training Data
|
| 55 |
+
|
| 56 |
+
2,000 synthetic episodes in a 20m ร 20m environment with 8 obstacles:
|
| 57 |
+
- Social Force Model physics (Helbing & Molnar 1995)
|
| 58 |
+
- ~156K frames at 10 Hz
|
| 59 |
+
- Speed range: 0.3-2.0 m/s (avg ~1.3 m/s, matching human walking)
|
| 60 |
+
|
| 61 |
+
## Quick Start
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
import torch, json, numpy as np
|
| 65 |
+
|
| 66 |
+
# Load
|
| 67 |
+
config = json.load(open('config.json'))
|
| 68 |
+
stats = json.load(open('normalization_stats.json'))
|
| 69 |
+
|
| 70 |
+
# Build model (copy architecture classes from this repo)
|
| 71 |
+
model = HumanTrajDiffusion(ad=2, sd=4, gd=2, H=16, T=100, dims=tuple(config['down_dims']))
|
| 72 |
+
model.load_state_dict(torch.load('model.pt', map_location='cpu'))
|
| 73 |
+
model.eval()
|
| 74 |
+
|
| 75 |
+
# Robot at (5,5) moving NE โ goal (15,15)
|
| 76 |
+
state = np.array([5.0, 5.0, 0.5, 0.3])
|
| 77 |
+
goal = np.array([15.0, 15.0])
|
| 78 |
+
|
| 79 |
+
state_n = torch.tensor((state - stats['state_mean']) / stats['state_std'], dtype=torch.float32)
|
| 80 |
+
goal_n = torch.tensor((goal - stats['goal_mean']) / stats['goal_std'], dtype=torch.float32)
|
| 81 |
+
|
| 82 |
+
# Generate 5 diverse paths
|
| 83 |
+
trajectories = model.generate(state_n, goal_n, n=5)
|
| 84 |
+
|
| 85 |
+
# โ Real coordinates
|
| 86 |
+
traj = trajectories.numpy() * stats['action_std'] + stats['action_mean']
|
| 87 |
+
positions = np.cumsum(traj, axis=1) + state[:2]
|
| 88 |
+
# positions.shape = (5, 16, 2) โ 5 paths, 16 waypoints, (x,y)
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
## Config
|
| 92 |
+
```json
|
| 93 |
+
{
|
| 94 |
+
"horizon": 16,
|
| 95 |
+
"action_dim": 2,
|
| 96 |
+
"state_dim": 4,
|
| 97 |
+
"goal_dim": 2,
|
| 98 |
+
"num_diffusion_steps": 100,
|
| 99 |
+
"down_dims": [
|
| 100 |
+
64,
|
| 101 |
+
128,
|
| 102 |
+
256
|
| 103 |
+
],
|
| 104 |
+
"batch_size": 32,
|
| 105 |
+
"total_steps": 8000,
|
| 106 |
+
"lr": 0.0002,
|
| 107 |
+
"weight_decay": 1e-05,
|
| 108 |
+
"warmup_steps": 200,
|
| 109 |
+
"grad_clip": 10.0,
|
| 110 |
+
"eval_freq": 2000,
|
| 111 |
+
"log_freq": 25,
|
| 112 |
+
"hub_model_id": "precison9/human-like-robot-nav-diffusion"
|
| 113 |
+
}
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
## Normalization Stats
|
| 117 |
+
```json
|
| 118 |
+
{
|
| 119 |
+
"state_mean": [
|
| 120 |
+
9.887735366821289,
|
| 121 |
+
10.40771484375,
|
| 122 |
+
0.02240574173629284,
|
| 123 |
+
-0.010746479965746403
|
| 124 |
+
],
|
| 125 |
+
"state_std": [
|
| 126 |
+
4.021646976470947,
|
| 127 |
+
3.9589571952819824,
|
| 128 |
+
0.7364981174468994,
|
| 129 |
+
0.7464056015014648
|
| 130 |
+
],
|
| 131 |
+
"action_mean": [
|
| 132 |
+
0.0022544937673956156,
|
| 133 |
+
-0.001080495654605329
|
| 134 |
+
],
|
| 135 |
+
"action_std": [
|
| 136 |
+
0.07394769042730331,
|
| 137 |
+
0.07494954019784927
|
| 138 |
+
],
|
| 139 |
+
"goal_mean": [
|
| 140 |
+
10.106578826904297,
|
| 141 |
+
10.3273344039917
|
| 142 |
+
],
|
| 143 |
+
"goal_std": [
|
| 144 |
+
4.950056076049805,
|
| 145 |
+
5.060120582580566
|
| 146 |
+
]
|
| 147 |
+
}
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
## Applications
|
| 151 |
+
- ๐ค Mobile robot navigation
|
| 152 |
+
- ๐ฎ NPC pedestrian AI
|
| 153 |
+
- ๐๏ธ Crowd simulation
|
| 154 |
+
- ๐ Trajectory prediction/planning
|
checkpoint.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4d50f6ce46e3c7fd15d43238d2ee8e166611d29da422f197f2c677951ca4de72
|
| 3 |
+
size 21717737
|
config.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"horizon": 16,
|
| 3 |
+
"action_dim": 2,
|
| 4 |
+
"state_dim": 4,
|
| 5 |
+
"goal_dim": 2,
|
| 6 |
+
"num_diffusion_steps": 100,
|
| 7 |
+
"down_dims": [
|
| 8 |
+
64,
|
| 9 |
+
128,
|
| 10 |
+
256
|
| 11 |
+
],
|
| 12 |
+
"batch_size": 32,
|
| 13 |
+
"total_steps": 8000,
|
| 14 |
+
"lr": 0.0002,
|
| 15 |
+
"weight_decay": 1e-05,
|
| 16 |
+
"warmup_steps": 200,
|
| 17 |
+
"grad_clip": 10.0,
|
| 18 |
+
"eval_freq": 2000,
|
| 19 |
+
"log_freq": 25,
|
| 20 |
+
"hub_model_id": "precison9/human-like-robot-nav-diffusion"
|
| 21 |
+
}
|
model.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:58f73f5200f793fce5cb88b4c4ebcf7b8eea843b5f29b8772b96de55a8082a89
|
| 3 |
+
size 7229289
|
model_architecture.py
ADDED
|
@@ -0,0 +1,545 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CPU-optimized training for Human-Like Robot Navigation Trajectory Generator.
|
| 3 |
+
Adapted for CPU sandbox with smaller UNet dims but same architecture.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import numpy as np
|
| 10 |
+
import math
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import time
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 17 |
+
# DATA GENERATION (same as before)
|
| 18 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 19 |
+
|
| 20 |
+
AREA_SIZE = 20.0
|
| 21 |
+
NUM_EPISODES = 2000
|
| 22 |
+
MIN_STEPS = 40
|
| 23 |
+
MAX_STEPS = 120
|
| 24 |
+
DT = 0.1
|
| 25 |
+
PREFERRED_SPEED = 1.3
|
| 26 |
+
MAX_SPEED = 2.0
|
| 27 |
+
MIN_SPEED = 0.3
|
| 28 |
+
|
| 29 |
+
OBSTACLES = [
|
| 30 |
+
(5, 5, 1.5), (15, 10, 2.0), (10, 15, 1.0), (3, 12, 1.2),
|
| 31 |
+
(17, 4, 1.8), (8, 8, 0.8), (12, 3, 1.0), (6, 17, 1.5),
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
def social_force(pos, vel, goal, obstacles, walls_min=0.0, walls_max=AREA_SIZE):
|
| 35 |
+
force = np.zeros(2)
|
| 36 |
+
goal_dir = goal - pos
|
| 37 |
+
goal_dist = np.linalg.norm(goal_dir)
|
| 38 |
+
if goal_dist > 0.1:
|
| 39 |
+
desired_vel = PREFERRED_SPEED * goal_dir / goal_dist
|
| 40 |
+
force += (desired_vel - vel) / 0.5
|
| 41 |
+
for ox, oy, r in obstacles:
|
| 42 |
+
diff = pos - np.array([ox, oy])
|
| 43 |
+
dist = np.linalg.norm(diff) - r
|
| 44 |
+
if dist < 5.0 and dist > 0.01:
|
| 45 |
+
force += 3.0 * np.exp(-dist / 0.8) * diff / (np.linalg.norm(diff) + 1e-6)
|
| 46 |
+
wall_A, wall_B = 2.0, 0.5
|
| 47 |
+
if pos[0] < 3.0: force[0] += wall_A * np.exp(-(pos[0] - walls_min) / wall_B)
|
| 48 |
+
if pos[0] > AREA_SIZE - 3.0: force[0] -= wall_A * np.exp(-(walls_max - pos[0]) / wall_B)
|
| 49 |
+
if pos[1] < 3.0: force[1] += wall_A * np.exp(-(pos[1] - walls_min) / wall_B)
|
| 50 |
+
if pos[1] > AREA_SIZE - 3.0: force[1] -= wall_A * np.exp(-(walls_max - pos[1]) / wall_B)
|
| 51 |
+
return force
|
| 52 |
+
|
| 53 |
+
def generate_episode():
|
| 54 |
+
for _ in range(100):
|
| 55 |
+
start = np.random.uniform(1.5, AREA_SIZE - 1.5, 2)
|
| 56 |
+
goal = np.random.uniform(1.5, AREA_SIZE - 1.5, 2)
|
| 57 |
+
if np.linalg.norm(goal - start) < 5.0: continue
|
| 58 |
+
valid = all(np.linalg.norm(start - [ox, oy]) >= r + 0.5 and
|
| 59 |
+
np.linalg.norm(goal - [ox, oy]) >= r + 0.5 for ox, oy, r in OBSTACLES)
|
| 60 |
+
if valid: break
|
| 61 |
+
pos = start.copy()
|
| 62 |
+
heading = np.arctan2(goal[1]-start[1], goal[0]-start[0]) + np.random.randn() * 0.3
|
| 63 |
+
vel = np.array([np.cos(heading), np.sin(heading)]) * MIN_SPEED
|
| 64 |
+
positions, velocities, actions = [pos.copy()], [vel.copy()], []
|
| 65 |
+
has_wp = np.random.random() < 0.4
|
| 66 |
+
mid = np.clip((start+goal)/2 + np.random.randn(2)*3, 1.5, AREA_SIZE-1.5) if has_wp else goal
|
| 67 |
+
wp_reached = not has_wp
|
| 68 |
+
cur_goal = mid if not wp_reached else goal
|
| 69 |
+
for step in range(np.random.randint(MIN_STEPS, MAX_STEPS+1)):
|
| 70 |
+
if not wp_reached and np.linalg.norm(pos - mid) < 1.5:
|
| 71 |
+
wp_reached = True; cur_goal = goal
|
| 72 |
+
force = social_force(pos, vel, cur_goal, OBSTACLES)
|
| 73 |
+
spd = np.linalg.norm(vel)
|
| 74 |
+
sway = np.array([-vel[1], vel[0]])/(spd+1e-6) * 0.05 * np.sin(2*np.pi*1.5*step*DT) if spd > 0.01 else np.zeros(2)
|
| 75 |
+
vel = vel + (force + sway + np.random.randn(2)*0.02) * DT
|
| 76 |
+
spd = np.linalg.norm(vel)
|
| 77 |
+
if spd > MAX_SPEED: vel = vel/spd*MAX_SPEED
|
| 78 |
+
elif spd < MIN_SPEED*0.5 and np.linalg.norm(pos-goal)>1: vel = vel/(spd+1e-6)*MIN_SPEED
|
| 79 |
+
gd = np.linalg.norm(pos - goal)
|
| 80 |
+
if gd < 2.0: vel *= max(0.1, gd/2.0)
|
| 81 |
+
new_pos = np.clip(pos + vel*DT, 0.1, AREA_SIZE-0.1)
|
| 82 |
+
actions.append((new_pos - pos).copy())
|
| 83 |
+
pos = new_pos; positions.append(pos.copy()); velocities.append(vel.copy())
|
| 84 |
+
if gd < 0.5: break
|
| 85 |
+
return {'positions': np.array(positions), 'velocities': np.array(velocities),
|
| 86 |
+
'actions': np.array(actions), 'goal': goal, 'num_steps': len(actions)}
|
| 87 |
+
|
| 88 |
+
def build_dataset(data_dir='/app/dataset'):
|
| 89 |
+
np.random.seed(42); os.makedirs(data_dir, exist_ok=True)
|
| 90 |
+
all_s, all_a, all_g, all_ep, all_fr, all_ts, all_d = [], [], [], [], [], [], []
|
| 91 |
+
ve = 0
|
| 92 |
+
print("Generating trajectories...")
|
| 93 |
+
for _ in range(NUM_EPISODES):
|
| 94 |
+
ep = generate_episode()
|
| 95 |
+
if ep['num_steps'] < 10: continue
|
| 96 |
+
for t in range(ep['num_steps']):
|
| 97 |
+
all_s.append(np.concatenate([ep['positions'][t], ep['velocities'][t]]).tolist())
|
| 98 |
+
all_a.append(ep['actions'][t].tolist())
|
| 99 |
+
all_g.append(ep['goal'].tolist())
|
| 100 |
+
all_ep.append(ve); all_fr.append(t); all_ts.append(t*DT)
|
| 101 |
+
all_d.append(t == ep['num_steps']-1)
|
| 102 |
+
ve += 1
|
| 103 |
+
if ve % 500 == 0: print(f" {ve} episodes...")
|
| 104 |
+
for name, arr, dt in [('observation_state', all_s, np.float32), ('action', all_a, np.float32),
|
| 105 |
+
('observation_goal', all_g, np.float32), ('episode_index', all_ep, np.int64),
|
| 106 |
+
('frame_index', all_fr, np.int64), ('timestamp', all_ts, np.float32)]:
|
| 107 |
+
np.save(f'{data_dir}/{name}.npy', np.array(arr, dtype=dt))
|
| 108 |
+
np.save(f'{data_dir}/done.npy', np.array(all_d, dtype=bool))
|
| 109 |
+
print(f"Dataset: {ve} episodes, {len(all_s)} frames")
|
| 110 |
+
|
| 111 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 112 |
+
# MODEL (same architecture, CPU-optimized dims)
|
| 113 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 114 |
+
|
| 115 |
+
class CosineNoiseScheduler:
|
| 116 |
+
def __init__(self, T=100, s=0.008):
|
| 117 |
+
self.T = T
|
| 118 |
+
t = torch.linspace(0, T, T+1)
|
| 119 |
+
ac = torch.cos(((t/T)+s)/(1+s)*math.pi*0.5)**2
|
| 120 |
+
ac = ac/ac[0]
|
| 121 |
+
betas = torch.clamp(1-(ac[1:]/ac[:-1]), 0.0001, 0.999)
|
| 122 |
+
alphas = 1.0-betas
|
| 123 |
+
ac = torch.cumprod(alphas, 0)
|
| 124 |
+
ac_prev = F.pad(ac[:-1], (1,0), value=1.0)
|
| 125 |
+
self.betas = betas
|
| 126 |
+
self.sqrt_ac = torch.sqrt(ac)
|
| 127 |
+
self.sqrt_1mac = torch.sqrt(1.0-ac)
|
| 128 |
+
self.sqrt_ra = torch.sqrt(1.0/alphas)
|
| 129 |
+
self.pv = betas*(1.0-ac_prev)/(1.0-ac)
|
| 130 |
+
|
| 131 |
+
def add_noise(self, x0, noise, t):
|
| 132 |
+
sa = self.sqrt_ac[t].view(-1,1,1)
|
| 133 |
+
sm = self.sqrt_1mac[t].view(-1,1,1)
|
| 134 |
+
return (sa*x0 + sm*noise)
|
| 135 |
+
|
| 136 |
+
def step(self, pred, t, xt):
|
| 137 |
+
b = self.betas[t].view(-1,1,1).to(xt.device)
|
| 138 |
+
sm = self.sqrt_1mac[t].view(-1,1,1).to(xt.device)
|
| 139 |
+
sr = self.sqrt_ra[t].view(-1,1,1).to(xt.device)
|
| 140 |
+
mean = sr*(xt - b*pred/sm)
|
| 141 |
+
if t[0]==0: return mean
|
| 142 |
+
v = self.pv[t].view(-1,1,1).to(xt.device)
|
| 143 |
+
return mean + torch.sqrt(v)*torch.randn_like(xt)
|
| 144 |
+
|
| 145 |
+
class SinEmb(nn.Module):
|
| 146 |
+
def __init__(self, d):
|
| 147 |
+
super().__init__(); self.d = d
|
| 148 |
+
def forward(self, t):
|
| 149 |
+
h = self.d//2
|
| 150 |
+
e = math.log(10000)/(h-1)
|
| 151 |
+
e = torch.exp(torch.arange(h, device=t.device)*-e)
|
| 152 |
+
e = t[:,None].float()*e[None,:]
|
| 153 |
+
return torch.cat([e.sin(), e.cos()], -1)
|
| 154 |
+
|
| 155 |
+
class FiLM(nn.Module):
|
| 156 |
+
def __init__(self, cd, fd):
|
| 157 |
+
super().__init__()
|
| 158 |
+
self.s = nn.Linear(cd, fd); self.b = nn.Linear(cd, fd)
|
| 159 |
+
def forward(self, x, c):
|
| 160 |
+
return x*(1+self.s(c).unsqueeze(-1))+self.b(c).unsqueeze(-1)
|
| 161 |
+
|
| 162 |
+
class ResBlock(nn.Module):
|
| 163 |
+
def __init__(self, ic, oc, cd, ks=5, g=8):
|
| 164 |
+
super().__init__()
|
| 165 |
+
p = ks//2
|
| 166 |
+
self.c1 = nn.Conv1d(ic, oc, ks, padding=p)
|
| 167 |
+
self.c2 = nn.Conv1d(oc, oc, ks, padding=p)
|
| 168 |
+
self.n1 = nn.GroupNorm(min(g,oc), oc)
|
| 169 |
+
self.n2 = nn.GroupNorm(min(g,oc), oc)
|
| 170 |
+
self.film = FiLM(cd, oc)
|
| 171 |
+
self.act = nn.Mish()
|
| 172 |
+
self.skip = nn.Conv1d(ic, oc, 1) if ic!=oc else nn.Identity()
|
| 173 |
+
def forward(self, x, c):
|
| 174 |
+
h = self.act(self.n1(self.c1(x)))
|
| 175 |
+
h = self.film(h, c)
|
| 176 |
+
h = self.act(self.n2(self.c2(h)))
|
| 177 |
+
return h + self.skip(x)
|
| 178 |
+
|
| 179 |
+
class TrajUNet(nn.Module):
|
| 180 |
+
def __init__(self, ad=2, sd=4, gd=2, H=16, dims=(128,256,512), emb_d=64, ks=5, ng=8):
|
| 181 |
+
super().__init__()
|
| 182 |
+
self.cond_enc = nn.Sequential(nn.Linear(sd+gd, 128), nn.Mish(), nn.Linear(128, 128), nn.Mish())
|
| 183 |
+
self.time_enc = nn.Sequential(SinEmb(emb_d), nn.Linear(emb_d, emb_d*2), nn.Mish(), nn.Linear(emb_d*2, emb_d))
|
| 184 |
+
cd = 128+emb_d
|
| 185 |
+
self.inp = nn.Conv1d(ad, dims[0], 1)
|
| 186 |
+
self.down_b = nn.ModuleList([ResBlock(dims[i], dims[i], cd, ks, ng) for i in range(len(dims)-1)])
|
| 187 |
+
self.down_p = nn.ModuleList([nn.Conv1d(dims[i], dims[i+1], 3, 2, 1) for i in range(len(dims)-1)])
|
| 188 |
+
self.mid = ResBlock(dims[-1], dims[-1], cd, ks, ng)
|
| 189 |
+
self.up_c = nn.ModuleList([nn.ConvTranspose1d(dims[i], dims[i-1], 4, 2, 1) for i in range(len(dims)-1, 0, -1)])
|
| 190 |
+
self.up_b = nn.ModuleList([ResBlock(dims[i-1]*2, dims[i-1], cd, ks, ng) for i in range(len(dims)-1, 0, -1)])
|
| 191 |
+
self.out = nn.Sequential(nn.Conv1d(dims[0], dims[0], ks, padding=ks//2), nn.Mish(), nn.Conv1d(dims[0], ad, 1))
|
| 192 |
+
|
| 193 |
+
def forward(self, na, t, s, g):
|
| 194 |
+
c = torch.cat([self.cond_enc(torch.cat([s,g],-1)), self.time_enc(t)], -1)
|
| 195 |
+
x = self.inp(na.permute(0,2,1))
|
| 196 |
+
sk = []
|
| 197 |
+
for b, p in zip(self.down_b, self.down_p):
|
| 198 |
+
x = b(x, c); sk.append(x); x = p(x)
|
| 199 |
+
x = self.mid(x, c)
|
| 200 |
+
for uc, ub, s_ in zip(self.up_c, self.up_b, reversed(sk)):
|
| 201 |
+
x = uc(x)
|
| 202 |
+
if x.shape[-1] != s_.shape[-1]: x = F.pad(x, (0, s_.shape[-1]-x.shape[-1]))
|
| 203 |
+
x = ub(torch.cat([x, s_], 1), c)
|
| 204 |
+
return self.out(x).permute(0,2,1)
|
| 205 |
+
|
| 206 |
+
class HumanTrajDiffusion(nn.Module):
|
| 207 |
+
def __init__(self, ad=2, sd=4, gd=2, H=16, T=100, dims=(128,256,512)):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.H = H; self.ad = ad; self.T = T
|
| 210 |
+
self.unet = TrajUNet(ad, sd, gd, H, dims)
|
| 211 |
+
self.sched = CosineNoiseScheduler(T)
|
| 212 |
+
|
| 213 |
+
def forward(self, actions, state, goal):
|
| 214 |
+
B = actions.shape[0]
|
| 215 |
+
t = torch.randint(0, self.T, (B,), device=actions.device)
|
| 216 |
+
noise = torch.randn_like(actions)
|
| 217 |
+
noisy = self.sched.add_noise(actions, noise, t.cpu()).to(actions.device)
|
| 218 |
+
return F.mse_loss(self.unet(noisy, t, state, goal), noise)
|
| 219 |
+
|
| 220 |
+
@torch.no_grad()
|
| 221 |
+
def generate(self, state, goal, n=1):
|
| 222 |
+
if state.dim()==1: state=state.unsqueeze(0)
|
| 223 |
+
if goal.dim()==1: goal=goal.unsqueeze(0)
|
| 224 |
+
dev = state.device
|
| 225 |
+
if n>1: state=state.repeat(n,1); goal=goal.repeat(n,1)
|
| 226 |
+
B = state.shape[0]
|
| 227 |
+
x = torch.randn(B, self.H, self.ad, device=dev)
|
| 228 |
+
for tv in reversed(range(self.T)):
|
| 229 |
+
t = torch.full((B,), tv, device=dev, dtype=torch.long)
|
| 230 |
+
x = self.sched.step(self.unet(x, t, state, goal), t.cpu(), x)
|
| 231 |
+
return x
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 235 |
+
# DATASET
|
| 236 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 237 |
+
|
| 238 |
+
class TrajDS(torch.utils.data.Dataset):
|
| 239 |
+
def __init__(self, dd='/app/dataset', H=16):
|
| 240 |
+
self.H = H
|
| 241 |
+
self.states = np.load(f'{dd}/observation_state.npy')
|
| 242 |
+
self.actions = np.load(f'{dd}/action.npy')
|
| 243 |
+
self.goals = np.load(f'{dd}/observation_goal.npy')
|
| 244 |
+
self.eps = np.load(f'{dd}/episode_index.npy')
|
| 245 |
+
self.sm, self.ss = self.states.mean(0), self.states.std(0)+1e-6
|
| 246 |
+
self.am, self.as_ = self.actions.mean(0), self.actions.std(0)+1e-6
|
| 247 |
+
self.gm, self.gs = self.goals.mean(0), self.goals.std(0)+1e-6
|
| 248 |
+
vi = []
|
| 249 |
+
for e in np.unique(self.eps):
|
| 250 |
+
ei = np.where(self.eps==e)[0]
|
| 251 |
+
for i in range(len(ei)-H):
|
| 252 |
+
if ei[i+H-1]-ei[i]==H-1: vi.append(ei[i])
|
| 253 |
+
self.vi = np.array(vi)
|
| 254 |
+
print(f"Dataset: {len(self.vi)} samples")
|
| 255 |
+
def __len__(self): return len(self.vi)
|
| 256 |
+
def __getitem__(self, i):
|
| 257 |
+
s = self.vi[i]
|
| 258 |
+
return {
|
| 259 |
+
'state': torch.tensor((self.states[s]-self.sm)/self.ss, dtype=torch.float32),
|
| 260 |
+
'goal': torch.tensor((self.goals[s]-self.gm)/self.gs, dtype=torch.float32),
|
| 261 |
+
'actions': torch.tensor((self.actions[s:s+self.H]-self.am)/self.as_, dtype=torch.float32),
|
| 262 |
+
}
|
| 263 |
+
def stats(self):
|
| 264 |
+
return {k: getattr(self, k).tolist() for k in ['sm','ss','am','as_','gm','gs']}
|
| 265 |
+
def stats_named(self):
|
| 266 |
+
return {'state_mean': self.sm.tolist(), 'state_std': self.ss.tolist(),
|
| 267 |
+
'action_mean': self.am.tolist(), 'action_std': self.as_.tolist(),
|
| 268 |
+
'goal_mean': self.gm.tolist(), 'goal_std': self.gs.tolist()}
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 272 |
+
# TRAINING
|
| 273 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 274 |
+
|
| 275 |
+
def cosine_lr(opt, step, total, warmup=300, lo=1e-6, hi=2e-4):
|
| 276 |
+
if step < warmup: lr = hi*step/warmup
|
| 277 |
+
else: lr = lo + (hi-lo)*0.5*(1+math.cos(math.pi*(step-warmup)/(total-warmup)))
|
| 278 |
+
for pg in opt.param_groups: pg['lr'] = lr
|
| 279 |
+
return lr
|
| 280 |
+
|
| 281 |
+
def train():
|
| 282 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 283 |
+
print(f"Device: {device}")
|
| 284 |
+
|
| 285 |
+
cfg = {
|
| 286 |
+
'horizon': 16, 'action_dim': 2, 'state_dim': 4, 'goal_dim': 2,
|
| 287 |
+
'num_diffusion_steps': 100, 'down_dims': [64, 128, 256],
|
| 288 |
+
'batch_size': 32, 'total_steps': 8000,
|
| 289 |
+
'lr': 2e-4, 'weight_decay': 1e-5, 'warmup_steps': 200,
|
| 290 |
+
'grad_clip': 10.0, 'eval_freq': 2000, 'log_freq': 25,
|
| 291 |
+
'hub_model_id': 'precison9/human-like-robot-nav-diffusion',
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
# Init trackio
|
| 295 |
+
try:
|
| 296 |
+
import trackio
|
| 297 |
+
sid = os.environ.get('TRACKIO_SPACE_ID')
|
| 298 |
+
proj = os.environ.get('TRACKIO_PROJECT', 'human-like-robot-nav')
|
| 299 |
+
trackio.init(space_id=sid, project=proj, run="ddpm-traj-cpu-v1", config=cfg)
|
| 300 |
+
HAS_T = True
|
| 301 |
+
print(f"Trackio: {sid}/{proj}")
|
| 302 |
+
except:
|
| 303 |
+
HAS_T = False
|
| 304 |
+
print("No trackio")
|
| 305 |
+
|
| 306 |
+
# Generate data if needed
|
| 307 |
+
if not os.path.exists('/app/dataset/observation_state.npy'):
|
| 308 |
+
build_dataset()
|
| 309 |
+
|
| 310 |
+
torch.manual_seed(42); np.random.seed(42)
|
| 311 |
+
ds = TrajDS('/app/dataset', cfg['horizon'])
|
| 312 |
+
dl = torch.utils.data.DataLoader(ds, batch_size=cfg['batch_size'], shuffle=True,
|
| 313 |
+
num_workers=0, pin_memory=False, drop_last=True)
|
| 314 |
+
|
| 315 |
+
model = HumanTrajDiffusion(ad=2, sd=4, gd=2, H=16, T=100,
|
| 316 |
+
dims=tuple(cfg['down_dims'])).to(device)
|
| 317 |
+
npar = sum(p.numel() for p in model.parameters())
|
| 318 |
+
print(f"Model: {npar:,} params ({npar/1e6:.1f}M)")
|
| 319 |
+
|
| 320 |
+
opt = torch.optim.AdamW(model.parameters(), lr=cfg['lr'], betas=(0.95,0.999),
|
| 321 |
+
weight_decay=cfg['weight_decay'])
|
| 322 |
+
|
| 323 |
+
model.train()
|
| 324 |
+
step = 0; rl = 0.0; best = float('inf'); t0 = time.time()
|
| 325 |
+
|
| 326 |
+
print(f"\n{'='*60}\nTraining {cfg['total_steps']} steps on {device}\n{'='*60}\n")
|
| 327 |
+
|
| 328 |
+
while step < cfg['total_steps']:
|
| 329 |
+
for batch in dl:
|
| 330 |
+
if step >= cfg['total_steps']: break
|
| 331 |
+
s, g, a = batch['state'].to(device), batch['goal'].to(device), batch['actions'].to(device)
|
| 332 |
+
lr = cosine_lr(opt, step, cfg['total_steps'], cfg['warmup_steps'], 1e-6, cfg['lr'])
|
| 333 |
+
loss = model(a, s, g)
|
| 334 |
+
opt.zero_grad(); loss.backward()
|
| 335 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), cfg['grad_clip'])
|
| 336 |
+
opt.step()
|
| 337 |
+
rl += loss.item(); step += 1
|
| 338 |
+
|
| 339 |
+
if step % cfg['log_freq'] == 0:
|
| 340 |
+
al = rl/cfg['log_freq']; el = time.time()-t0; sps = step/el
|
| 341 |
+
print(f"step={step:5d} | loss={al:.6f} | lr={lr:.2e} | {sps:.1f} stp/s | eta={((cfg['total_steps']-step)/sps)/60:.1f}m")
|
| 342 |
+
if HAS_T: trackio.log({'train/loss': al, 'train/lr': lr})
|
| 343 |
+
rl = 0.0
|
| 344 |
+
|
| 345 |
+
if step % cfg['eval_freq'] == 0:
|
| 346 |
+
model.eval()
|
| 347 |
+
els = []
|
| 348 |
+
idx = np.random.choice(len(ds), min(1280, len(ds)), replace=False)
|
| 349 |
+
for i in range(0, len(idx), cfg['batch_size']):
|
| 350 |
+
bi = [ds[j] for j in idx[i:i+cfg['batch_size']]]
|
| 351 |
+
if len(bi)<2: continue
|
| 352 |
+
with torch.no_grad():
|
| 353 |
+
els.append(model(
|
| 354 |
+
torch.stack([x['actions'] for x in bi]).to(device),
|
| 355 |
+
torch.stack([x['state'] for x in bi]).to(device),
|
| 356 |
+
torch.stack([x['goal'] for x in bi]).to(device)).item())
|
| 357 |
+
el = np.mean(els)
|
| 358 |
+
print(f" >>> EVAL step={step}: loss={el:.6f}")
|
| 359 |
+
if HAS_T: trackio.log({'eval/loss': el})
|
| 360 |
+
if el < best:
|
| 361 |
+
best = el
|
| 362 |
+
save(model, opt, step, cfg, ds, '/app/checkpoints/best')
|
| 363 |
+
if HAS_T: trackio.alert("Best", f"eval={el:.6f} step={step}", level="INFO")
|
| 364 |
+
model.train()
|
| 365 |
+
|
| 366 |
+
# Final save
|
| 367 |
+
save(model, opt, step, cfg, ds, '/app/checkpoints/final')
|
| 368 |
+
print(f"\nDone! Best eval: {best:.6f}")
|
| 369 |
+
if HAS_T: trackio.alert("Done", f"steps={step}, best={best:.6f}", level="INFO")
|
| 370 |
+
|
| 371 |
+
# Eval generation
|
| 372 |
+
eval_gen(model, ds, device)
|
| 373 |
+
|
| 374 |
+
# Push
|
| 375 |
+
push(cfg, ds)
|
| 376 |
+
|
| 377 |
+
def save(model, opt, step, cfg, ds, path):
|
| 378 |
+
os.makedirs(path, exist_ok=True)
|
| 379 |
+
torch.save(model.state_dict(), f'{path}/model.pt')
|
| 380 |
+
torch.save({'step':step, 'model':model.state_dict(), 'opt':opt.state_dict()}, f'{path}/checkpoint.pt')
|
| 381 |
+
with open(f'{path}/config.json','w') as f: json.dump(cfg, f, indent=2)
|
| 382 |
+
with open(f'{path}/normalization_stats.json','w') as f: json.dump(ds.stats_named(), f, indent=2)
|
| 383 |
+
print(f" Saved: {path}")
|
| 384 |
+
|
| 385 |
+
def eval_gen(model, ds, device):
|
| 386 |
+
model.eval()
|
| 387 |
+
st = ds.stats_named()
|
| 388 |
+
cases = [
|
| 389 |
+
([2,2,0.5,0.5], [18,18]), ([2,18,0.3,-0.3], [18,2]),
|
| 390 |
+
([10,2,0,0.5], [10,18]), ([5,5,0.3,0.3], [15,15]),
|
| 391 |
+
]
|
| 392 |
+
print(f"\n{'='*60}\nGeneration Evaluation\n{'='*60}")
|
| 393 |
+
all_spd = []
|
| 394 |
+
for i, (s_raw, g_raw) in enumerate(cases):
|
| 395 |
+
s_raw, g_raw = np.array(s_raw, np.float32), np.array(g_raw, np.float32)
|
| 396 |
+
sn = torch.tensor((s_raw-np.array(st['state_mean']))/np.array(st['state_std']), dtype=torch.float32).to(device)
|
| 397 |
+
gn = torch.tensor((g_raw-np.array(st['goal_mean']))/np.array(st['goal_std']), dtype=torch.float32).to(device)
|
| 398 |
+
trajs = model.generate(sn, gn, n=5).cpu().numpy()
|
| 399 |
+
td = trajs*np.array(st['action_std'])+np.array(st['action_mean'])
|
| 400 |
+
pos = np.cumsum(td, axis=1) + s_raw[:2]
|
| 401 |
+
speeds = np.linalg.norm(td, axis=-1)/DT
|
| 402 |
+
all_spd.extend(speeds.flatten().tolist())
|
| 403 |
+
div = np.std(pos[:,-1], axis=0).mean()
|
| 404 |
+
print(f" Case {i+1}: {s_raw[:2].tolist()} โ {g_raw.tolist()} | "
|
| 405 |
+
f"speed={speeds.mean():.2f}m/s | diversity={div:.3f}m")
|
| 406 |
+
|
| 407 |
+
print(f"\n Overall mean speed: {np.mean(all_spd):.2f} m/s (human: ~1.3 m/s)")
|
| 408 |
+
print(f" Speed std: {np.std(all_spd):.2f} m/s")
|
| 409 |
+
|
| 410 |
+
def push(cfg, ds):
|
| 411 |
+
from huggingface_hub import HfApi
|
| 412 |
+
hid = cfg['hub_model_id']
|
| 413 |
+
bp = Path('/app/checkpoints/best')
|
| 414 |
+
fp = Path('/app/checkpoints/final')
|
| 415 |
+
up = bp if bp.exists() else fp
|
| 416 |
+
if not up.exists(): print("No checkpoint!"); return
|
| 417 |
+
|
| 418 |
+
api = HfApi()
|
| 419 |
+
try: api.create_repo(hid, exist_ok=True)
|
| 420 |
+
except Exception as e: print(f"Repo: {e}")
|
| 421 |
+
|
| 422 |
+
st = ds.stats_named()
|
| 423 |
+
np_ = sum(v.numel() for v in torch.load(up/'model.pt', map_location='cpu', weights_only=True).values())
|
| 424 |
+
|
| 425 |
+
readme = f"""---
|
| 426 |
+
tags:
|
| 427 |
+
- robotics
|
| 428 |
+
- trajectory-generation
|
| 429 |
+
- diffusion-model
|
| 430 |
+
- navigation
|
| 431 |
+
- human-like-motion
|
| 432 |
+
- ddpm
|
| 433 |
+
library_name: pytorch
|
| 434 |
+
pipeline_tag: reinforcement-learning
|
| 435 |
+
license: mit
|
| 436 |
+
---
|
| 437 |
+
|
| 438 |
+
# ๐ค๐ถ Human-Like Robot Navigation Trajectory Generator
|
| 439 |
+
|
| 440 |
+
A **DDPM (Denoising Diffusion Probabilistic Model)** that generates human-like 2D navigation trajectories for robots.
|
| 441 |
+
|
| 442 |
+
## What It Does
|
| 443 |
+
|
| 444 |
+
Given a robot's current state (position + velocity) and a goal, this model generates future waypoints that mimic human walking โ smooth curves, natural speed changes, and obstacle-aware paths.
|
| 445 |
+
|
| 446 |
+
```
|
| 447 |
+
Input: [x, y, vx, vy] + [goal_x, goal_y]
|
| 448 |
+
โ DDPM Reverse Diffusion (100 steps)
|
| 449 |
+
โ 1D Temporal UNet + FiLM conditioning
|
| 450 |
+
Output: 16 future waypoints [dx, dy]
|
| 451 |
+
```
|
| 452 |
+
|
| 453 |
+
## Key Features
|
| 454 |
+
|
| 455 |
+
- ๐ถ **Human-like paths** โ smooth curves, not robotic straight lines
|
| 456 |
+
- โก **Variable speed** โ acceleration, cruising, deceleration like real walking
|
| 457 |
+
- ๐งฑ **Obstacle aware** โ learned from social force model training data
|
| 458 |
+
- ๐ฒ **Multi-modal** โ generates diverse trajectory samples via diffusion
|
| 459 |
+
- ๐ฏ **Goal-directed** โ conditions on target position
|
| 460 |
+
|
| 461 |
+
## Architecture
|
| 462 |
+
|
| 463 |
+
| Component | Details |
|
| 464 |
+
|-----------|---------|
|
| 465 |
+
| Backbone | 1D Temporal UNet ({cfg['down_dims']}) |
|
| 466 |
+
| Conditioning | FiLM (Feature-wise Linear Modulation) |
|
| 467 |
+
| Noise Schedule | Cosine (Improved DDPM) |
|
| 468 |
+
| Diffusion Steps | {cfg['num_diffusion_steps']} |
|
| 469 |
+
| Parameters | {np_:,} ({np_/1e6:.1f}M) |
|
| 470 |
+
| Prediction | ฮต-prediction (noise) |
|
| 471 |
+
|
| 472 |
+
## Based On
|
| 473 |
+
|
| 474 |
+
- [Diffusion Policy](https://arxiv.org/abs/2303.04137) (Chi et al., RSS 2023)
|
| 475 |
+
- [TRACE](https://arxiv.org/abs/2304.01893) (Rempe et al., CVPR 2023)
|
| 476 |
+
- [Improved DDPM](https://arxiv.org/abs/2102.09672) (Nichol & Dhariwal, 2021)
|
| 477 |
+
|
| 478 |
+
## Training Data
|
| 479 |
+
|
| 480 |
+
2,000 synthetic episodes in a 20m ร 20m environment with 8 obstacles:
|
| 481 |
+
- Social Force Model physics (Helbing & Molnar 1995)
|
| 482 |
+
- ~156K frames at 10 Hz
|
| 483 |
+
- Speed range: 0.3-2.0 m/s (avg ~1.3 m/s, matching human walking)
|
| 484 |
+
|
| 485 |
+
## Quick Start
|
| 486 |
+
|
| 487 |
+
```python
|
| 488 |
+
import torch, json, numpy as np
|
| 489 |
+
|
| 490 |
+
# Load
|
| 491 |
+
config = json.load(open('config.json'))
|
| 492 |
+
stats = json.load(open('normalization_stats.json'))
|
| 493 |
+
|
| 494 |
+
# Build model (copy architecture classes from this repo)
|
| 495 |
+
model = HumanTrajDiffusion(ad=2, sd=4, gd=2, H=16, T=100, dims=tuple(config['down_dims']))
|
| 496 |
+
model.load_state_dict(torch.load('model.pt', map_location='cpu'))
|
| 497 |
+
model.eval()
|
| 498 |
+
|
| 499 |
+
# Robot at (5,5) moving NE โ goal (15,15)
|
| 500 |
+
state = np.array([5.0, 5.0, 0.5, 0.3])
|
| 501 |
+
goal = np.array([15.0, 15.0])
|
| 502 |
+
|
| 503 |
+
state_n = torch.tensor((state - stats['state_mean']) / stats['state_std'], dtype=torch.float32)
|
| 504 |
+
goal_n = torch.tensor((goal - stats['goal_mean']) / stats['goal_std'], dtype=torch.float32)
|
| 505 |
+
|
| 506 |
+
# Generate 5 diverse paths
|
| 507 |
+
trajectories = model.generate(state_n, goal_n, n=5)
|
| 508 |
+
|
| 509 |
+
# โ Real coordinates
|
| 510 |
+
traj = trajectories.numpy() * stats['action_std'] + stats['action_mean']
|
| 511 |
+
positions = np.cumsum(traj, axis=1) + state[:2]
|
| 512 |
+
# positions.shape = (5, 16, 2) โ 5 paths, 16 waypoints, (x,y)
|
| 513 |
+
```
|
| 514 |
+
|
| 515 |
+
## Config
|
| 516 |
+
```json
|
| 517 |
+
{json.dumps(cfg, indent=2)}
|
| 518 |
+
```
|
| 519 |
+
|
| 520 |
+
## Normalization Stats
|
| 521 |
+
```json
|
| 522 |
+
{json.dumps(st, indent=2)}
|
| 523 |
+
```
|
| 524 |
+
|
| 525 |
+
## Applications
|
| 526 |
+
- ๐ค Mobile robot navigation
|
| 527 |
+
- ๐ฎ NPC pedestrian AI
|
| 528 |
+
- ๐๏ธ Crowd simulation
|
| 529 |
+
- ๐ Trajectory prediction/planning
|
| 530 |
+
"""
|
| 531 |
+
with open(up/'README.md','w') as f: f.write(readme)
|
| 532 |
+
|
| 533 |
+
# Also save model architecture code
|
| 534 |
+
model_code = open('/app/train_cpu.py').read()
|
| 535 |
+
with open(up/'model_architecture.py','w') as f: f.write(model_code)
|
| 536 |
+
|
| 537 |
+
print(f"Pushing to: {hid}")
|
| 538 |
+
try:
|
| 539 |
+
api.upload_folder(folder_path=str(up), repo_id=hid, commit_message="Upload human-like robot nav model")
|
| 540 |
+
print(f"โ
https://huggingface.co/{hid}")
|
| 541 |
+
except Exception as e: print(f"Push error: {e}")
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
if __name__ == '__main__':
|
| 545 |
+
train()
|
normalization_stats.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"state_mean": [
|
| 3 |
+
9.887735366821289,
|
| 4 |
+
10.40771484375,
|
| 5 |
+
0.02240574173629284,
|
| 6 |
+
-0.010746479965746403
|
| 7 |
+
],
|
| 8 |
+
"state_std": [
|
| 9 |
+
4.021646976470947,
|
| 10 |
+
3.9589571952819824,
|
| 11 |
+
0.7364981174468994,
|
| 12 |
+
0.7464056015014648
|
| 13 |
+
],
|
| 14 |
+
"action_mean": [
|
| 15 |
+
0.0022544937673956156,
|
| 16 |
+
-0.001080495654605329
|
| 17 |
+
],
|
| 18 |
+
"action_std": [
|
| 19 |
+
0.07394769042730331,
|
| 20 |
+
0.07494954019784927
|
| 21 |
+
],
|
| 22 |
+
"goal_mean": [
|
| 23 |
+
10.106578826904297,
|
| 24 |
+
10.3273344039917
|
| 25 |
+
],
|
| 26 |
+
"goal_std": [
|
| 27 |
+
4.950056076049805,
|
| 28 |
+
5.060120582580566
|
| 29 |
+
]
|
| 30 |
+
}
|