> ## Documentation Index
> Fetch the complete documentation index at: https://khaos-ml.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Robotics

> Trajectories: demonstration search, stall detection, skill clustering.

## Find similar past demonstrations

**Problem:** given a new motion, retrieve the closest recorded demonstrations.
**Uses:** Khaos and FAISS.

```python theme={null}
import khaos
import faiss
import numpy as np

embed = khaos.load("robo_kinematics_sm")

library = np.stack([embed(t).vector for t in demo_trajectories]).astype("float32")
faiss.normalize_L2(library)
index = faiss.IndexFlatIP(library.shape[1])
index.add(library)

query = embed(new_trajectory).vector.astype("float32")[None]
faiss.normalize_L2(query)
scores, ids = index.search(query, 5)
print(ids[0], scores[0].round(2))
# [412  87 903 15 640] [0.97 0.95 0.93 0.91 0.9 ]
```

## Detect stalls in a control loop

**Problem:** stop a robot arm when a motion stalls. **Uses:** Khaos alone.

```python theme={null}
import khaos
from collections import deque

detector = khaos.load("robo_failure_detection")
window = deque(maxlen=200)

for state in robot.stream_joint_states():
    window.append(state)
    if len(window) == window.maxlen:
        report = detector(list(window))
        if report.stalled:
            robot.stop()
            print("stalled", round(report.score, 2))
            break
# stalled 0.91
```

## Cluster demonstrations into skills

**Problem:** discover the distinct behaviors in a pile of demonstrations. **Uses:**
Khaos and scikit-learn.

```python theme={null}
import khaos
import numpy as np
from sklearn.cluster import KMeans

segment = khaos.load("robo_skill_segmentation")
embed = khaos.load("robo_kinematics_sm")

clips = []
for demo in demonstrations:
    seg = segment(demo)
    edges = [0, *seg.boundaries, len(demo)]
    clips += [demo[a:b] for a, b in zip(edges, edges[1:]) if b - a > 5]

vectors = np.stack([embed(c).vector for c in clips])
labels = KMeans(n_clusters=6, n_init="auto").fit_predict(vectors)
print(np.bincount(labels))
# [212 187 164 140  96  61]
```

## Inputs and outputs for each model

These are real outputs of the v1 models, run through their exported ONNX files on held-out examples. The shapes listed are the exact ONNX inputs and outputs; `batch` and other named sizes are dynamic.

### `robo_kinematics_sm`

A joint trajectory (timesteps x 14 joints, 25 Hz) in, one 128-dimensional vector out. Compare vectors with cosine similarity to find similar motions.

**Model inputs:** `traj float32 [batch, time, 14]; mask float32 [batch, time]`\
**Model outputs:** `vector float32 [batch, 128]`

**Input**

```python theme={null}
traj.shape = (300, 14)   # task: aloha_static_battery
mask = ones(300)
```

**Output**

```json theme={null}
{
  "vector": [
    -0.004,
    0.31,
    -0.319,
    0.217,
    0.348,
    0.24,
    "..."
  ],
  "shape": [
    1,
    128
  ]
}
```

### `robo_skill_segmentation`

A joint trajectory in, a skill label and a boundary score for every timestep out. Consecutive steps with the same skill are merged below; `true` is the dataset's label (derived from gripper phases).

**Model inputs:** `traj float32 [batch, time, 14]; mask float32 [batch, time]`\
**Model outputs:** `boundary_logits float32 [batch, time]; skill_logits float32 [batch, time, 6]`

**Input**

```python theme={null}
traj.shape = (300, 14)   # task: aloha_static_battery
```

**Output**

```json theme={null}
{
  "predicted_segments": [
    {
      "steps": [
        0,
        5
      ],
      "skill": "approach"
    },
    {
      "steps": [
        6,
        6
      ],
      "skill": "retreat"
    },
    {
      "steps": [
        7,
        8
      ],
      "skill": "approach"
    },
    {
      "steps": [
        9,
        9
      ],
      "skill": "retreat"
    },
    {
      "steps": [
        10,
        21
      ],
      "skill": "approach"
    },
    {
      "steps": [
        22,
        27
      ],
      "skill": "transition"
    },
    {
      "steps": [
        28,
        64
      ],
      "skill": "right_hold"
    },
    {
      "steps": [
        65,
        72
      ],
      "skill": "transition"
    },
    {
      "steps": [
        73,
        75
      ],
      "skill": "retreat"
    },
    {
      "steps": [
        76,
        76
      ],
      "skill": "transition"
    },
    {
      "steps": [
        77,
        154
      ],
      "skill": "retreat"
    },
    {
      "steps": [
        155,
        159
      ],
      "skill": "transition"
    },
    {
      "steps": [
        160,
        176
      ],
      "skill": "right_hold"
    },
    {
      "steps": [
        177,
        179
      ],
      "skill": "transition"
    },
    {
      "steps": [
        180,
        299
      ],
      "skill": "retreat"
    }
  ],
  "true_segments": [
    {
      "steps": [
        0,
        4
      ],
      "skill": "transition"
    },
    {
      "steps": [
        5,
        21
      ],
      "skill": "retreat"
    },
    {
      "steps": [
        22,
        27
      ],
      "skill": "transition"
    },
    {
      "steps": [
        28,
        64
      ],
      "skill": "right_hold"
    },
    {
      "steps": [
        65,
        70
      ],
      "skill": "transition"
    },
    {
      "steps": [
        71,
        152
      ],
      "skill": "retreat"
    },
    {
      "steps": [
        153,
        158
      ],
      "skill": "transition"
    },
    {
      "steps": [
        159,
        175
      ],
      "skill": "right_hold"
    },
    {
      "steps": [
        176,
        181
      ],
      "skill": "transition"
    },
    {
      "steps": [
        182,
        299
      ],
      "skill": "retreat"
    }
  ],
  "boundary_score_peaks": [
    5,
    22,
    23,
    24,
    27,
    28,
    31,
    68,
    70,
    71,
    72,
    74,
    75,
    76,
    78,
    80,
    145,
    147,
    153,
    155,
    156,
    159,
    174,
    175,
    176,
    181
  ]
}
```

### `robo_failure_detection`

A joint trajectory in, a failure probability for every timestep out. The model only looks at past steps, so it runs live: read the last value. An alarm needs 3 steps above the calibrated threshold.

**Model inputs:** `traj float32 [batch, time, 14]; mask float32 [batch, time]`\
**Model outputs:** `failure_logits float32 [batch, time]`

**Input**

```python theme={null}
# two trajectories of task aloha_static_thread_velcro: one with a frozen arm, one
# clean
alarm_threshold = 0.970
```

**Output**

```json theme={null}
{
  "frozen_arm": {
    "steps": 350,
    "max_failure_probability": 1.0,
    "first_alarm_step": 160,
    "true_failure_onset_step": 161
  },
  "clean": {
    "steps": 350,
    "max_failure_probability": 0.367,
    "first_alarm_step": null
  }
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.