Add files using upload-large-folder tool
Browse files- .gitignore +70 -0
- .gitmodules +3 -0
- AGENTS.md +40 -0
- CHANGELOG.md +0 -0
- DIALOG.md +0 -0
- README.md +66 -0
- infer_render_auto.sh +113 -0
- posttrain-full-duplex-audio-command.sh +67 -0
- pyproject.toml +85 -0
- tests/test_action_observation_positions.py +152 -0
- tests/test_build_hfd_gqa_scale.py +18 -0
- tests/test_causal_audit_shards.py +65 -0
- tests/test_causal_av_packing.py +189 -0
- tests/test_causal_video_qa.py +66 -0
- tests/test_checkpoint_marker_atomicity.py +34 -0
- tests/test_continuous_audio_command_sources.py +168 -0
- tests/test_control_metrics_distributed.py +35 -0
- tests/test_dlc_storage.py +86 -0
- tests/test_full_duplex_audio_contract.py +60 -0
- tests/test_full_duplex_continuous_cache.py +163 -0
- tests/test_full_duplex_ddp_sync.py +127 -0
- tests/test_hf_audio_motion_handoff.py +205 -0
- tests/test_hf_export_dashboard.py +69 -0
- tests/test_hfd_backchannel_inventory.py +39 -0
- tests/test_hfd_continuation.py +41 -0
- tests/test_hfd_storage_paths.py +48 -0
- tests/test_hfd_training_recipe.py +335 -0
- tests/test_hfd_vqa_candidate_pilot.py +85 -0
- tests/test_hfdv2_qwen_streaming.py +0 -0
- tests/test_listen_hold_targets.py +64 -0
- tests/test_native_visual.py +102 -0
- tests/test_office_background_candidates.py +101 -0
- tests/test_production_a1_control.py +290 -0
- tests/test_speech_runtime_contract.py +65 -0
- tests/test_swa_formal_integration.py +363 -0
- tests/test_swa_manifest_contract.py +122 -0
- tests/test_swa_native_speech.py +75 -0
- tests/test_swa_pipeline_queue.py +137 -0
- tests/test_swa_regressions.py +83 -0
- tests/test_swa_scaleup.py +74 -0
- tests/test_swa_speech_failures.py +29 -0
- tests/test_third_party_dataset.py +96 -0
- tests/test_training_dashboard.py +334 -0
- tests/test_unified_overlay_review.py +103 -0
- tests/test_video_asset_admission.py +117 -0
- tests/test_video_overlay.py +79 -0
- tests/test_visual_dataset_bundle.py +283 -0
- tests/test_vqa_review_dashboard.py +133 -0
- train_dlc.sh +9 -0
- uv.lock +0 -0
.gitignore
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python-generated files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[oc]
|
| 4 |
+
.pytest_cache/
|
| 5 |
+
.mypy_cache/
|
| 6 |
+
.ruff_cache/
|
| 7 |
+
build/
|
| 8 |
+
dist/
|
| 9 |
+
wheels/
|
| 10 |
+
*.egg-info
|
| 11 |
+
|
| 12 |
+
# Virtual environments
|
| 13 |
+
.venv*
|
| 14 |
+
|
| 15 |
+
/data/
|
| 16 |
+
cache
|
| 17 |
+
*.mp4
|
| 18 |
+
ml-egodex_dataset/ # soft link to the egodex dataset
|
| 19 |
+
wandb/
|
| 20 |
+
runs/
|
| 21 |
+
checkpoints/
|
| 22 |
+
log/
|
| 23 |
+
logs/
|
| 24 |
+
profile_output/
|
| 25 |
+
recovery/
|
| 26 |
+
runtime_indexes/
|
| 27 |
+
playgrounds/
|
| 28 |
+
TODO.md
|
| 29 |
+
*.zip
|
| 30 |
+
*.log
|
| 31 |
+
*.safetensors
|
| 32 |
+
*.ckpt
|
| 33 |
+
|
| 34 |
+
runs_old/
|
| 35 |
+
tmp_dir/
|
| 36 |
+
.runs*
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
.env
|
| 40 |
+
.env.local
|
| 41 |
+
|
| 42 |
+
_lerobot_build
|
| 43 |
+
.cache
|
| 44 |
+
.data
|
| 45 |
+
.logs
|
| 46 |
+
|
| 47 |
+
*.local.yaml
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
vq/
|
| 51 |
+
extern/vq_bet_official/
|
| 52 |
+
src/fast/egodex-*
|
| 53 |
+
*.pkl
|
| 54 |
+
!src/fast/egodex-rel-50w-1x48-v2048-s100
|
| 55 |
+
|
| 56 |
+
.deepspeed_env
|
| 57 |
+
*.bak
|
| 58 |
+
#uv.lock
|
| 59 |
+
.vscode/
|
| 60 |
+
.direnv/
|
| 61 |
+
third_party/
|
| 62 |
+
src/gr00t/.venv/
|
| 63 |
+
props/
|
| 64 |
+
textures/
|
| 65 |
+
test.py
|
| 66 |
+
*.npy
|
| 67 |
+
|
| 68 |
+
unitree_sdk2_python
|
| 69 |
+
|
| 70 |
+
dataset/
|
.gitmodules
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[submodule "third_party/SIMPLE"]
|
| 2 |
+
path = third_party/SIMPLE
|
| 3 |
+
url = git@github.com:songlin/SIMPLE.git
|
AGENTS.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Repository workflow
|
| 2 |
+
|
| 3 |
+
Do not create standalone documentation unless the user explicitly requests it.
|
| 4 |
+
Routine work updates belong in the existing CHANGELOG/DIALOG (or consolidated
|
| 5 |
+
doc/工作留痕.md), not additional dated documents.
|
| 6 |
+
|
| 7 |
+
This repository is the standalone code backup for Humanoid-Full-Duplex (HFD).
|
| 8 |
+
It must not push to, inherit new work from, or otherwise mutate the old
|
| 9 |
+
Psi0-yth repository. Follow these rules for every change made in this working
|
| 10 |
+
tree.
|
| 11 |
+
|
| 12 |
+
1. Use one branch per HFD change or project version. Do not reuse old Psi0-yth
|
| 13 |
+
version prefixes such as `v26-`. Every newly created branch must include a
|
| 14 |
+
`YYMMDDHHMM` timestamp in its name.
|
| 15 |
+
2. After changing source code, configuration, scripts, tests, or documentation,
|
| 16 |
+
add a concise but complete Chinese entry to `CHANGELOG.md`.
|
| 17 |
+
3. Run checks appropriate to the change, then create a focused commit with a
|
| 18 |
+
concise message that says what changed.
|
| 19 |
+
4. Push the commit to the same branch on `origin`, then merge that tested branch
|
| 20 |
+
into the repository's configured default branch and push the default branch
|
| 21 |
+
as well. Preserve the feature commit and its authorship in the merge history.
|
| 22 |
+
If either push or merge is blocked, report it explicitly; do not silently
|
| 23 |
+
leave unpushed or default-branch-only work.
|
| 24 |
+
5. Never commit training runs, checkpoints, datasets, runtime indexes, caches,
|
| 25 |
+
credentials, `.env` files, or repository SSH keys.
|
| 26 |
+
6. Keep the repository-specific SSH key and Git identity local to `.git/` and
|
| 27 |
+
`.git/config`; do not modify global Git or SSH configuration for this repo.
|
| 28 |
+
7. Record each substantive user request and its outcome in `DIALOG.md` as well
|
| 29 |
+
as the Chinese change summary in `CHANGELOG.md`. Preserve the user's original
|
| 30 |
+
wording in DIALOG and summarize the assistant's work. Experiments must also
|
| 31 |
+
be recorded in both logs, with evidence limits stated explicitly.
|
| 32 |
+
8. In this formal working tree, `experiments/` is for Markdown reports only:
|
| 33 |
+
one consolidated report per experiment, named with its start date. Update
|
| 34 |
+
that report instead of creating dated progress, plan, audit, and conclusion
|
| 35 |
+
fragments. Keep formal implementation and usage/check details in the normal
|
| 36 |
+
source locations and DIALOG/CHANGELOG, not in an experiment report.
|
| 37 |
+
9. Keep temporary experiment code, raw metrics, checkpoints, caches, and audit
|
| 38 |
+
traces outside this formal tree in an isolated experiment workspace. Before
|
| 39 |
+
removing redundant artifacts, verify the exact scope and preserve unique
|
| 40 |
+
useful evidence; never clean unrelated user files or active training output.
|
CHANGELOG.md
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
DIALOG.md
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
README.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# HFD — Humanoid Full-Duplex
|
| 2 |
+
|
| 3 |
+
HFD研究持续交互中的人形机器人全双工行为:接收语音与可选的图像/视频,连续生成动作,并在视觉问答时生成语音回答。
|
| 4 |
+
|
| 5 |
+
任务包括 **turn-taking、interruption(含stop)、backchannel、hesitation、pause**。视觉问答叠加到这些交互任务中,不另设独立的SWA任务。代码中保留的`swa`名称用于模块与历史配置兼容。
|
| 6 |
+
|
| 7 |
+
## 当前入口
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
# 正式训练:参数集中在脚本顶部;使用作业分配的GPU
|
| 11 |
+
bash posttrain-full-duplex-audio-command.sh
|
| 12 |
+
|
| 13 |
+
# 仅打印训练配置,不启动训练
|
| 14 |
+
bash posttrain-full-duplex-audio-command.sh --print-config
|
| 15 |
+
|
| 16 |
+
# 自动推理/渲染:可指定run目录;省略时选择兼容的最新run
|
| 17 |
+
bash infer_render_auto.sh /path/to/run
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
直接执行`bash infer_render_auto.sh`会选择兼容的最新run并持续监听。
|
| 21 |
+
该入口接替原`infer_render_auto_multiturn.sh`;任务集合、train/val样例、多卡队列、
|
| 22 |
+
checkpoint间隔和异步渲染逻辑不变。无需另起内部worker,也不要同时启动两份自动推理。
|
| 23 |
+
|
| 24 |
+
训练环境复用`.venv-psi`。依赖、模型和数据路径必须可用,启动器会检查;不要把配置打印成功当成完整训练验证。关键参数在训练脚本顶部,固定配置与环境变量映射在[当前配方](src/psi/config/hfd_current_recipe.py)。完整续训与WandB续接参数见训练脚本末尾说明。
|
| 25 |
+
|
| 26 |
+
历史数据工具已移入[`backup/`](backup/README.md),不是日常训推入口:
|
| 27 |
+
`backup/prepare_full_duplex_continuous_audio.sh`用于连续背景音数据重建(旧流程还会导出hidden),
|
| 28 |
+
`backup/prepare_omni_training_data.sh`及其调用的`backup/cache_video_omni_embeds.py`
|
| 29 |
+
用于历史数据重建/兼容。已有数据训练无需运行它们,
|
| 30 |
+
不要为清理目录而重新执行造数据。旧canonical-motion消融、旧OSS索引预构建、
|
| 31 |
+
早期hidden包装入口已退役,恢复方式见清理记录。
|
| 32 |
+
|
| 33 |
+
## 项目结构
|
| 34 |
+
|
| 35 |
+
| 位置 | 用途 |
|
| 36 |
+
|---|---|
|
| 37 |
+
| `posttrain-full-duplex-audio-command.sh` | 正式训练入口 |
|
| 38 |
+
| `infer_render_auto.sh` | 唯一自动推理入口:多任务、多卡、异步渲染 |
|
| 39 |
+
| `scripts/infer/run_audio_case.sh` | 调度器内部音频样例/渲染执行器,不需单独启动 |
|
| 40 |
+
| `src/psi/models/`、`src/psi/trainers/` | HFD模型和训练器;含仍在复用的Psi0基础实现 |
|
| 41 |
+
| `src/psi/data/seed/` | 音频/动作、视觉问答、流式session数据构造 |
|
| 42 |
+
| `src/psi/runtime/` | 推理运行时 |
|
| 43 |
+
| `scripts/data/` | 数据准备、质检、GT渲染和审核看板 |
|
| 44 |
+
| `scripts/infer/` | 推理、任务样例与异步渲染调度 |
|
| 45 |
+
| `assets/stats/` | 动作归一化等统计量,不能当作旧宣传素材删除 |
|
| 46 |
+
| `tests/` | 回归测试 |
|
| 47 |
+
| `doc/`、`experiments/` | 技术文档与历史实验报告 |
|
| 48 |
+
| `runs/` | 本机运行产物,不纳入Git |
|
| 49 |
+
|
| 50 |
+
HFD仍沿用`psi`包名、部分基础模型、数据变换和训练基类。**不能按文件名含`psi0`就删除**,也不要重命名包来“清理”:旧checkpoint和当前导入路径都依赖它。
|
| 51 |
+
|
| 52 |
+
## 数据与审核看板
|
| 53 |
+
|
| 54 |
+
- [当前数据盘点](doc/260928-data.md):数据量、存储与路径;是有日期的快照,实时准入情况以清单为准。
|
| 55 |
+
- [看板使用说明](scripts/data/review_dashboard/README.md):候选、已准入素材、人工备注和审核进度。
|
| 56 |
+
- 已有索引时启动网页:`.venv-psi/bin/python scripts/data/review_dashboard/server.py`。
|
| 57 |
+
- 网页默认监听本机8770,远程使用DSW/IDE端口代理;`/progress`显示审核进度。机器重启后,网页和审核后台需要分别恢复,普通tmux不提供开机自启。
|
| 58 |
+
- 数据位于项目外的`videogen/`等目录;审核运行记录在项目外`hfd_experiments/`。不要把机器审核pending清单当作正式可训练清单。
|
| 59 |
+
|
| 60 |
+
## 历史代码与来源
|
| 61 |
+
|
| 62 |
+
无关的Psi0 baseline、旧训练入口和SIMPLE示例已从当前目录移除,范围与可恢复备份见[合并工作留痕](doc/工作留痕.md)。共享基础代码、环境、数据、模型权重和历史实验文档未随之清理。
|
| 63 |
+
|
| 64 |
+
本项目复用[Psi0](https://github.com/physical-superintelligence-lab/Psi0)的基础实现;原版权声明和[LICENSE](LICENSE)保留。原上游README在Git历史及本次可恢复备份中保留,本页仅说明HFD当前入口。
|
| 65 |
+
|
| 66 |
+
历史变更见[CHANGELOG.md](CHANGELOG.md),对话决策见[DIALOG.md](DIALOG.md),更多技术文档见[doc/README.md](doc/README.md)。
|
infer_render_auto.sh
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -Eeuo pipefail
|
| 3 |
+
|
| 4 |
+
PROJECT_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
| 5 |
+
PYTHON_BIN=${HFD_INFER_PYTHON:-$PROJECT_ROOT/.venv-psi/bin/python}
|
| 6 |
+
# Plain bash: pin the newest compatible run once, then watch its checkpoints.
|
| 7 |
+
# To inspect an older run, edit RUN_DIR here or still pass it as argument 1.
|
| 8 |
+
RUN_DIR=${1:-${HFD_INFER_RUN_DIR:-auto}}
|
| 9 |
+
RUNS_ROOT=${HFD_INFER_RUNS_ROOT:-$PROJECT_ROOT/runs}
|
| 10 |
+
# All tasks on the first checkpoint, then every >=20k training steps. Saving
|
| 11 |
+
# remains every 5k. Explicit one-shot bypasses this; 0 processes every checkpoint.
|
| 12 |
+
export HFD_INFER_CHECKPOINT_INTERVAL=${HFD_INFER_CHECKPOINT_INTERVAL:-20000}
|
| 13 |
+
|
| 14 |
+
cd "$PROJECT_ROOT"
|
| 15 |
+
export PYTHONPATH="$PROJECT_ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
|
| 16 |
+
if (( $# > 1 )); then
|
| 17 |
+
echo "[error] Usage: bash infer_render_auto.sh [RUN_DIR]" >&2
|
| 18 |
+
exit 2
|
| 19 |
+
fi
|
| 20 |
+
RUN_DIR=$("$PYTHON_BIN" "$PROJECT_ROOT/scripts/infer/run_multiturn_infer_suite.py" \
|
| 21 |
+
"$RUN_DIR" --runs-root "$RUNS_ROOT" --resolve-only)
|
| 22 |
+
echo "[HFD] pinned inference run: $RUN_DIR"
|
| 23 |
+
# A lightweight launch check; never allocates GPUs or scans all dataset files.
|
| 24 |
+
if [[ "${HFD_INFER_CONFIG_ONLY:-0}" == "1" ]]; then
|
| 25 |
+
echo "[HFD] inference GPUs: ${HFD_INFER_GPUS:-${CUDA_VISIBLE_DEVICES-all allocated}}"
|
| 26 |
+
exit 0
|
| 27 |
+
fi
|
| 28 |
+
echo "[HFD] Inference shares its visible GPUs across all tasks. Use a separate GPU allocation to avoid slowing training."
|
| 29 |
+
|
| 30 |
+
# Audio-only cases are unchanged. SWA automatically generates native answer
|
| 31 |
+
# speech; the legacy ``contract`` switch below only runs an extra startup check
|
| 32 |
+
# (it is NOT the on/off switch for SWA speech).
|
| 33 |
+
SPEECH_RUNTIME_MODE=${HFD_SPEECH_RUNTIME_MODE:-off}
|
| 34 |
+
case "$SPEECH_RUNTIME_MODE" in
|
| 35 |
+
off)
|
| 36 |
+
;;
|
| 37 |
+
contract)
|
| 38 |
+
QA_ARGS=()
|
| 39 |
+
if [[ -n "${HFD_QA_LORA_CHECKPOINT:-}" ]]; then
|
| 40 |
+
QA_ARGS+=(--qa-checkpoint "$HFD_QA_LORA_CHECKPOINT")
|
| 41 |
+
fi
|
| 42 |
+
"$PYTHON_BIN" -u "$PROJECT_ROOT/scripts/infer/validate_speech_qa_runtime.py" "${QA_ARGS[@]}"
|
| 43 |
+
;;
|
| 44 |
+
*)
|
| 45 |
+
echo "[error] HFD_SPEECH_RUNTIME_MODE must be off or contract (optional startup validation only)." >&2
|
| 46 |
+
exit 2
|
| 47 |
+
;;
|
| 48 |
+
esac
|
| 49 |
+
|
| 50 |
+
echo "[HFD] speech runtime contract=$SPEECH_RUNTIME_MODE solver=${HFD_SPEECH_SOLVER:-euler} steps=${HFD_SPEECH_SOLVER_STEPS:-6} codec_chunk=${HFD_SPEECH_CODEC_CHUNK_CODES:-36} first_chunk=${HFD_SPEECH_FIRST_CHUNK_CODES:-36} playback_buffer=${HFD_SPEECH_PLAYBACK_BUFFER_SECONDS:-0.20}s"
|
| 51 |
+
|
| 52 |
+
if [[ -z "$RUN_DIR" || ! -f "$RUN_DIR/run_config.json" ]]; then
|
| 53 |
+
echo "[error] A valid HFD run directory is required." >&2
|
| 54 |
+
exit 2
|
| 55 |
+
fi
|
| 56 |
+
# Validate the data actually saved with this run, including legacy audio-only
|
| 57 |
+
# runs. A newer launcher's default must not substitute a different SWA plan.
|
| 58 |
+
mapfile -t SAVED_SWA < <("$PYTHON_BIN" - "$RUN_DIR/run_config.json" <<'PY'
|
| 59 |
+
import json, sys
|
| 60 |
+
with open(sys.argv[1]) as file:
|
| 61 |
+
config = json.load(file)
|
| 62 |
+
print("enabled" if config.get("model", {}).get("swa_visual_qa_enabled", False) else "disabled")
|
| 63 |
+
print(config.get("data", {}).get("swa_source_plan", ""))
|
| 64 |
+
PY
|
| 65 |
+
)
|
| 66 |
+
SWA_DATA_MODE=${HFD_SWA_DATA_MODE:-${SAVED_SWA[0]}}
|
| 67 |
+
SWA_SOURCE_PLAN=${HFD_SWA_SOURCE_PLAN:-${SAVED_SWA[1]}}
|
| 68 |
+
SWA_FRONTEND_SAMPLE_COUNT=${HFD_SWA_FRONTEND_SAMPLE_COUNT:-2}
|
| 69 |
+
# Unified overlays must validate this run's actual manifests, not the retired
|
| 70 |
+
# standalone SWA source_plan/frontend cache still present for old checkpoints.
|
| 71 |
+
HAS_OVERLAY=$("$PYTHON_BIN" -c 'import json,sys; print(int(bool(json.load(open(sys.argv[1])).get("data",{}).get("multimodal_overlay_manifests"))))' "$RUN_DIR/run_config.json")
|
| 72 |
+
if [[ "$HAS_OVERLAY" == "1" ]]; then
|
| 73 |
+
"$PYTHON_BIN" "$PROJECT_ROOT/scripts/infer/check_run_visual_data.py" "$RUN_DIR"
|
| 74 |
+
else
|
| 75 |
+
case "$SWA_DATA_MODE" in
|
| 76 |
+
disabled)
|
| 77 |
+
echo "[HFD] SWA visual-QA inference=disabled by explicit override"
|
| 78 |
+
;;
|
| 79 |
+
contract)
|
| 80 |
+
if ! [[ "$SWA_FRONTEND_SAMPLE_COUNT" =~ ^[1-9][0-9]*$ ]]; then
|
| 81 |
+
echo "[error] HFD_SWA_FRONTEND_SAMPLE_COUNT must be a positive integer." >&2
|
| 82 |
+
exit 2
|
| 83 |
+
fi
|
| 84 |
+
"$PYTHON_BIN" -u "$PROJECT_ROOT/scripts/data/validate_swa_manifest.py" \
|
| 85 |
+
--source-plan "$SWA_SOURCE_PLAN" \
|
| 86 |
+
--sample-frontends "$SWA_FRONTEND_SAMPLE_COUNT" \
|
| 87 |
+
--require-visual \
|
| 88 |
+
--json
|
| 89 |
+
echo "[ready] SWA visual-QA contract verified"
|
| 90 |
+
;;
|
| 91 |
+
enabled)
|
| 92 |
+
"$PYTHON_BIN" -u "$PROJECT_ROOT/scripts/data/validate_swa_manifest.py" \
|
| 93 |
+
--source-plan "$SWA_SOURCE_PLAN" --sample-frontends "$SWA_FRONTEND_SAMPLE_COUNT" --require-visual --json
|
| 94 |
+
;;
|
| 95 |
+
*)
|
| 96 |
+
echo "[error] HFD_SWA_DATA_MODE must be disabled, contract or enabled." >&2
|
| 97 |
+
exit 2
|
| 98 |
+
;;
|
| 99 |
+
esac
|
| 100 |
+
fi
|
| 101 |
+
|
| 102 |
+
# All established interaction cases and SWA video/static train/val cases share one
|
| 103 |
+
# dynamic inference GPU queue (one model job per GPU). Rendering/mux use a
|
| 104 |
+
# separate bounded queue and never hold these model slots; default 4 workers,
|
| 105 |
+
# 32 outstanding videos. HFD_RENDER_WORKERS / HFD_RENDER_PENDING_LIMIT override
|
| 106 |
+
# these limits if needed. HFD_INCLUDE_SWA_SUITE=0 disables only SWA diagnostics.
|
| 107 |
+
if [[ "$SWA_DATA_MODE" == "enabled" ]]; then
|
| 108 |
+
export HFD_INCLUDE_SWA_SUITE=${HFD_INCLUDE_SWA_SUITE:-1}
|
| 109 |
+
echo "[HFD] SWA: model answer -> native Talker/Token2Wav -> independent speech worker -> video audio mix"
|
| 110 |
+
else
|
| 111 |
+
export HFD_INCLUDE_SWA_SUITE=0
|
| 112 |
+
fi
|
| 113 |
+
"$PYTHON_BIN" -u "$PROJECT_ROOT/scripts/infer/run_multiturn_infer_suite.py" "$RUN_DIR"
|
posttrain-full-duplex-audio-command.sh
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# 正式联合训练:直接 bash 本脚本;打印配置(不占 GPU):bash 本脚本 --print-config
|
| 3 |
+
# 提前离线准备索引(无需 GPU/WandB):bash 本脚本 --prepare-data;训练自动复用。
|
| 4 |
+
set -Eeuo pipefail
|
| 5 |
+
# 新训练固定40维动作 + FP32输入小投影;其余网络保持 BF16 AMP。
|
| 6 |
+
PROJECT_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
| 7 |
+
source "$PROJECT_ROOT/scripts/activate_psi_env.sh"
|
| 8 |
+
if [[ -f "${HFD_ENV_FILE:-$PROJECT_ROOT/.env}" ]]; then
|
| 9 |
+
set -a
|
| 10 |
+
source "${HFD_ENV_FILE:-$PROJECT_ROOT/.env}"
|
| 11 |
+
set +a
|
| 12 |
+
fi
|
| 13 |
+
export PYTHONPATH="$PROJECT_ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
|
| 14 |
+
|
| 15 |
+
# ── 新训练常调参数 ──────────────────────────────────────────────
|
| 16 |
+
# 完整续训自动继承原 run 的参数,不用这里的新训练默认值覆盖旧配置。
|
| 17 |
+
# 外部设置的同名环境变量优先;不指定 GPU 时使用作业分配的全部卡。
|
| 18 |
+
if [[ "${HFD_RESUME_LOAD_FULL_STATE:-0}" != "1" ]]; then
|
| 19 |
+
export HFD_TRAIN_BATCH_SIZE=${HFD_TRAIN_BATCH_SIZE:-16} # 每卡;统一AV的H200长KV压测配置
|
| 20 |
+
export HFD_MAX_TRAINING_STEPS=${HFD_MAX_TRAINING_STEPS:-1500000}
|
| 21 |
+
export HFD_LEARNING_RATE=${HFD_LEARNING_RATE:-8e-5} # 动作头峰值 LR
|
| 22 |
+
export HFD_QWEN_LR=${HFD_QWEN_LR:-2e-6}
|
| 23 |
+
export HFD_WARMUP_STEPS=${HFD_WARMUP_STEPS:-$((HFD_MAX_TRAINING_STEPS / 100))}
|
| 24 |
+
export HFD_CHECKPOINTING_STEPS=${HFD_CHECKPOINTING_STEPS:-5000}
|
| 25 |
+
export HFD_VALIDATION_STEPS=${HFD_VALIDATION_STEPS:-20000} # 0 = 不验证
|
| 26 |
+
export HFD_VAL_BATCH_SIZE=${HFD_VAL_BATCH_SIZE:-8}
|
| 27 |
+
export HFD_VAL_NUM_BATCHES=${HFD_VAL_NUM_BATCHES:-64} # 全卡合计验证 source 数
|
| 28 |
+
export HFD_NUM_WORKERS=${HFD_NUM_WORKERS:-16} # 每卡数据进程
|
| 29 |
+
export HFD_STATIONARY_LISTEN_HOLD=${HFD_STATIONARY_LISTEN_HOLD:-1} # 所有原任务:听时抬手保持,末姿态接动作
|
| 30 |
+
export HFD_SESSION_MIN_TURNS=${HFD_SESSION_MIN_TURNS:-1} # 1~4条;新动作打断仍至少2条。设2复用旧范围
|
| 31 |
+
|
| 32 |
+
# ── 音频任务配比:四类按合成 session 数,turn-taking 自动取剩余 ──
|
| 33 |
+
# 默认 turn-taking 60% / interruption 15% / stop 10% / backchannel 15%。
|
| 34 |
+
# 以下三项之和必须 < 1;不是候选池 variants 数,更不是 loss 权重。
|
| 35 |
+
export HFD_INTERRUPTION_TASK_SESSION_RATIO=${HFD_INTERRUPTION_TASK_SESSION_RATIO:-0.15}
|
| 36 |
+
export HFD_CONTROL_TASK_SESSION_RATIO=${HFD_CONTROL_TASK_SESSION_RATIO:-0.10} # stop
|
| 37 |
+
export HFD_BACKCHANNEL_TASK_SESSION_RATIO=${HFD_BACKCHANNEL_TASK_SESSION_RATIO:-0.15}
|
| 38 |
+
# 下两类按音频窗口数额外配比,与上面的 session 百分比不是同一分母。
|
| 39 |
+
export HFD_HESITATION_TASK_WINDOW_RATIO=${HFD_HESITATION_TASK_WINDOW_RATIO:-0.12}
|
| 40 |
+
export HFD_PAUSE_TASK_WINDOW_RATIO=${HFD_PAUSE_TASK_WINDOW_RATIO:-0.08}
|
| 41 |
+
# third-party:额外追加审核通过的26737条训练session;不删旧任务、不重复采样。
|
| 42 |
+
# 复用已混合音频,动作由当前listen保持/40维管线生成;路径在current_recipe。
|
| 43 |
+
|
| 44 |
+
# ── 各原任务统一叠加视觉问答,不再另设 SWA 任务 ─────────────────
|
| 45 |
+
# 默认统一包 hfd_visual_dataset/images + videos;均为八音色,同一 session 固定同音色。
|
| 46 |
+
export HFD_OVERLAY_QA_RATIO=${HFD_OVERLAY_QA_RATIO:-0.75}
|
| 47 |
+
export HFD_OVERLAY_VISUAL_ONLY_RATIO=${HFD_OVERLAY_VISUAL_ONLY_RATIO:-0.10}
|
| 48 |
+
export HFD_VISUAL_INPUT_MODE=${HFD_VISUAL_INPUT_MODE:-cached} # cached=读特征;raw=原图/视频在线编码
|
| 49 |
+
# 剩余15%纯音频;上面是抽样概率,安全时间段不足时回落纯音频。
|
| 50 |
+
# 可选 HFD_OVERLAY_MANIFESTS='["/path/to/hfd_visual_dataset"]';兼容旧 JSON 清单。
|
| 51 |
+
# enabled / disabled;disabled 为原纯音频模式。
|
| 52 |
+
export HFD_SWA_DATA_MODE=${HFD_SWA_DATA_MODE:-enabled}
|
| 53 |
+
# 新训练不加载旧实验权重:原始预训练 Qwen + 新动作头 / 新问答 LoRA。
|
| 54 |
+
# A1:共享前28层、独立后8层+cross;C:语义锚定状态token延迟写入下一packet。
|
| 55 |
+
# 两分支独立KV,QA loss不修改身体Qwen。
|
| 56 |
+
# 默认只用已审核发布清单;不在启动时重新合成数据。
|
| 57 |
+
fi
|
| 58 |
+
|
| 59 |
+
# ── 日志与续训 ──────────────────────────────────────────────────
|
| 60 |
+
export HFD_REPORT_TO=${HFD_REPORT_TO:-wandb} # wandb / None
|
| 61 |
+
export HFD_WANDB_RESUME=${HFD_WANDB_RESUME:-never} # 默认新曲线
|
| 62 |
+
# 完整续训:HFD_RESUME_FROM_CHECKPOINT=/path/to/ckpt_N
|
| 63 |
+
# HFD_RESUME_LOAD_FULL_STATE=1
|
| 64 |
+
# 接原曲线再设置:HFD_WANDB_RESUME=must HFD_WANDB_ID=原曲线ID
|
| 65 |
+
# CUDA_VISIBLE_DEVICES / HFD_NPROC_PER_NODE 可选;DLC 默认不管理占卡程序。
|
| 66 |
+
# 固定算法、路径和进阶参数:src/psi/config/hfd_current_recipe.py
|
| 67 |
+
exec python "$PROJECT_ROOT/scripts/launch_hfd_training.py" "$@"
|
pyproject.toml
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "psi"
|
| 3 |
+
version = "0.0.0"
|
| 4 |
+
description = "Psi: towards humanoid foundation model"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
requires-python = "==3.10.*"
|
| 7 |
+
dependencies = [
|
| 8 |
+
"albumentations==1.4.18",
|
| 9 |
+
"datasets==3.6.0",
|
| 10 |
+
"dm-tree==0.1.8",
|
| 11 |
+
"einops==0.8.1",
|
| 12 |
+
"einx>=0.3.0",
|
| 13 |
+
"h5py==3.14.0",
|
| 14 |
+
"imageio==2.34.2",
|
| 15 |
+
"jsonlines>=4.0.0",
|
| 16 |
+
"numpy<2.0.0",
|
| 17 |
+
"numpydantic==1.6.7",
|
| 18 |
+
"omegaconf>=2.3.0",
|
| 19 |
+
"opencv-python",
|
| 20 |
+
"plotly==6.2.0",
|
| 21 |
+
"pydantic==2.10.6",
|
| 22 |
+
"pydantic-yaml>=1.6.0",
|
| 23 |
+
"tqdm==4.67.1",
|
| 24 |
+
"typer>=0.19.1",
|
| 25 |
+
"tyro==0.9.32",
|
| 26 |
+
"vuer[all]>=0.0.68",
|
| 27 |
+
"wandb>=0.20.0",
|
| 28 |
+
"simplejpeg>=1.9.0",
|
| 29 |
+
"dotenv",
|
| 30 |
+
"gdown>=5.2.0",
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
[build-system]
|
| 34 |
+
requires = ["setuptools>=61.0"]
|
| 35 |
+
build-backend = "setuptools.build_meta"
|
| 36 |
+
|
| 37 |
+
[tool.setuptools.package-data]
|
| 38 |
+
psi = ["assets/*"]
|
| 39 |
+
|
| 40 |
+
[tool.uv.sources]
|
| 41 |
+
psi = { path = ".", editable = true }
|
| 42 |
+
simple = { path = "third_party/SIMPLE", editable = true }
|
| 43 |
+
|
| 44 |
+
[tool.uv.workspace]
|
| 45 |
+
members = ["packages/*"]
|
| 46 |
+
|
| 47 |
+
[dependency-groups]
|
| 48 |
+
serve = [
|
| 49 |
+
"fastapi",
|
| 50 |
+
"uvicorn",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
viz = [
|
| 54 |
+
"transforms3d>=0.4.2",
|
| 55 |
+
"vuer[all]>=0.0.68",
|
| 56 |
+
"viser>=1.0.15",
|
| 57 |
+
#"pin>=3.8.0",
|
| 58 |
+
#"numpy<2.0.0",
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
psi = [
|
| 62 |
+
"setuptools>=61",
|
| 63 |
+
"torch==2.7.0",
|
| 64 |
+
"torchvision==0.22.0",
|
| 65 |
+
"torchcodec==0.4.0",
|
| 66 |
+
"transformers==4.57.0",
|
| 67 |
+
"deepspeed==0.17.1",
|
| 68 |
+
"flash_attn==2.7.4.post1",
|
| 69 |
+
"triton==3.3.0",
|
| 70 |
+
"accelerate==1.7.0",
|
| 71 |
+
"peft==0.17.1",
|
| 72 |
+
"qwen-vl-utils==0.0.14",
|
| 73 |
+
"sentencepiece",
|
| 74 |
+
"lerobot @ git+https://github.com/songlin/lerobot.git@09929d8057b044b53aecaf5c6d7eb71f99e8beb9"
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
#simple = [
|
| 78 |
+
# "simple[full]",
|
| 79 |
+
#]
|
| 80 |
+
|
| 81 |
+
[tool.uv.extra-build-dependencies]
|
| 82 |
+
flash-attn = [{ requirement = "torch", match-runtime = true }]
|
| 83 |
+
|
| 84 |
+
[project.scripts]
|
| 85 |
+
serve_psi0 = "psi.deploy.psi0_serve_simple:main"
|
tests/test_action_observation_positions.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Padding is not elapsed time: body/control positions must be source-local."""
|
| 2 |
+
from types import SimpleNamespace
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from psi.models.psi0 import ObservationProjection, _PositionalEncoding
|
| 8 |
+
from psi.models.relative_instruction_memory import architecture_contract
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def projection(mask_aware):
|
| 12 |
+
torch.manual_seed(17)
|
| 13 |
+
model = ObservationProjection(n_conditions=0, output_dim=16, odim=5,
|
| 14 |
+
view_feature_dim=8)
|
| 15 |
+
model.mask_aware_positions = mask_aware
|
| 16 |
+
return model.eval()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def inputs(padded=False):
|
| 20 |
+
torch.manual_seed(13)
|
| 21 |
+
# Three valid AV tokens, a predicted control token, then two state tokens.
|
| 22 |
+
av = torch.randn(1, 1, 3, 8)
|
| 23 |
+
control = torch.randn(1, 1, 1, 8)
|
| 24 |
+
states = torch.randn(1, 2, 5).requires_grad_()
|
| 25 |
+
gap = torch.randn(1, 1, 5 if padded else 0, 8)
|
| 26 |
+
views = torch.cat((av, gap, control), dim=2).requires_grad_()
|
| 27 |
+
mask = torch.tensor([[1] * 3 + [0] * gap.shape[2] + [1]])
|
| 28 |
+
return views, states, mask
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def output_and_gradients(model, padded):
|
| 32 |
+
views, states, mask = inputs(padded)
|
| 33 |
+
out, out_mask = model(views, states, vlm_attn_mask=mask)
|
| 34 |
+
valid = out[out_mask.bool()]
|
| 35 |
+
# Unequal weights prevent accidentally hiding a permutation in the test.
|
| 36 |
+
loss = (valid * torch.arange(1, 7)[:, None]).square().sum()
|
| 37 |
+
model.zero_grad(set_to_none=True)
|
| 38 |
+
loss.backward()
|
| 39 |
+
return valid.detach(), states.grad, views.grad[0, 0, mask[0].bool()], {
|
| 40 |
+
name: p.grad.clone() for name, p in model.named_parameters() if p.grad is not None
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_legacy_padding_changes_control_and_state_positions():
|
| 45 |
+
model = projection(False)
|
| 46 |
+
plain, *_ = output_and_gradients(model, False)
|
| 47 |
+
padded, *_ = output_and_gradients(model, True)
|
| 48 |
+
torch.testing.assert_close(plain[:3], padded[:3], rtol=0, atol=0)
|
| 49 |
+
assert (plain[3:] - padded[3:]).abs().max() > 0.5
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_mask_aware_positions_ignore_padding_in_forward_and_backward():
|
| 53 |
+
model = projection(True)
|
| 54 |
+
plain = output_and_gradients(model, False)
|
| 55 |
+
padded = output_and_gradients(model, True)
|
| 56 |
+
for a, b in zip(plain[:3], padded[:3]):
|
| 57 |
+
torch.testing.assert_close(a, b, rtol=1e-6, atol=1e-5)
|
| 58 |
+
for name in plain[3]:
|
| 59 |
+
torch.testing.assert_close(plain[3][name], padded[3][name], rtol=1e-6, atol=1e-4)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_mask_positions_are_independent_in_a_ragged_batch():
|
| 63 |
+
model = projection(True)
|
| 64 |
+
views, states, mask = inputs(True)
|
| 65 |
+
out, valid = model(views, states, vlm_attn_mask=mask)
|
| 66 |
+
# A second, longer source must not affect the first source's valid tokens.
|
| 67 |
+
batched, batched_mask = model(torch.cat((views, torch.randn_like(views))),
|
| 68 |
+
torch.cat((states, torch.randn_like(states))),
|
| 69 |
+
vlm_attn_mask=torch.cat((mask, torch.ones_like(mask))))
|
| 70 |
+
torch.testing.assert_close(out[valid.bool()], batched[0][batched_mask[0].bool()])
|
| 71 |
+
plain_views, plain_states, plain_mask = inputs(False)
|
| 72 |
+
plain, plain_valid = model(plain_views, plain_states, vlm_attn_mask=plain_mask)
|
| 73 |
+
torch.testing.assert_close(plain[plain_valid.bool()], batched[0][batched_mask[0].bool()])
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_all_valid_and_legacy_none_are_bitwise_unchanged():
|
| 77 |
+
encoding = _PositionalEncoding(16)
|
| 78 |
+
x = torch.empty(8, 3, 16)
|
| 79 |
+
torch.testing.assert_close(encoding(x), encoding(x, torch.ones(3, 8)), rtol=0, atol=0)
|
| 80 |
+
with pytest.raises(ValueError, match="shape"):
|
| 81 |
+
encoding(x, torch.ones(3, 7))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_architecture_contract_and_config_preserve_old_runs():
|
| 85 |
+
from psi.config.model_full_duplex_psi0 import FullDuplexPsi0ModelConfig
|
| 86 |
+
from psi.config.hfd_current_recipe import FIELDS
|
| 87 |
+
assert not FullDuplexPsi0ModelConfig.model_fields['action_mask_aware_positions'].default
|
| 88 |
+
assert FIELDS['model.action-mask-aware-positions'][0] is True
|
| 89 |
+
assert architecture_contract(SimpleNamespace()) == {}
|
| 90 |
+
assert architecture_contract(SimpleNamespace(action_mask_aware_positions=True)) == {
|
| 91 |
+
'action_observation_positions_v1': 'valid_tokens_only'}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_model_constructor_uses_saved_position_setting():
|
| 95 |
+
from psi.models.psi0 import Psi0Model
|
| 96 |
+
cfg = SimpleNamespace(
|
| 97 |
+
action_chunk_size=30, action_dim=4, action_exec_horizon=20,
|
| 98 |
+
max_delay=11, rtc=True, use_dit=False, nhead=2, hidden_dim=16,
|
| 99 |
+
num_blocks=2, resnet_store_path="", odim=5, view_feature_dim=8,
|
| 100 |
+
use_film=False, combined_temb=False, action_mask_aware_positions=True,
|
| 101 |
+
)
|
| 102 |
+
model = Psi0Model(cfg, None)
|
| 103 |
+
assert model.action_header.obs_proj.mask_aware_positions is True
|
| 104 |
+
cfg.action_mask_aware_positions = False
|
| 105 |
+
legacy = Psi0Model(cfg, None)
|
| 106 |
+
assert legacy.action_header.obs_proj.mask_aware_positions is False
|
| 107 |
+
assert list(model.state_dict()) == list(legacy.state_dict())
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_full_action_transformer_padding_invariance_and_optimizer_step():
|
| 111 |
+
from psi.models.psi0 import ActionTransformerModel
|
| 112 |
+
torch.manual_seed(19)
|
| 113 |
+
model = ActionTransformerModel(
|
| 114 |
+
attention_head_dim=8, num_attention_heads=2, action_nheads=2,
|
| 115 |
+
action_num_blocks=2, action_hidden_dim=16, action_dim=4,
|
| 116 |
+
action_pred_horizon=30, view_feature_dim=8, odim=5,
|
| 117 |
+
use_future_progress_embedding=True,
|
| 118 |
+
).eval()
|
| 119 |
+
model.obs_proj.mask_aware_positions = True
|
| 120 |
+
# Open the normally zero-initialized output so a vacuous zero prediction
|
| 121 |
+
# cannot pass the invariance check.
|
| 122 |
+
torch.nn.init.normal_(model.action_proj_out.linear.weight, std=0.1)
|
| 123 |
+
for block in model.transformer_blocks:
|
| 124 |
+
torch.nn.init.normal_(block.norm1_act.linear.weight, std=0.1)
|
| 125 |
+
noisy = torch.randn(1, 30, 4)
|
| 126 |
+
times = torch.full((1, 30), 0.4)
|
| 127 |
+
times[:, :10] = 0 # Same RTC geometry as the production solver.
|
| 128 |
+
phase = torch.randn(1, 30, 5)
|
| 129 |
+
|
| 130 |
+
def run(padded):
|
| 131 |
+
views, state, mask = inputs(padded)
|
| 132 |
+
return model(
|
| 133 |
+
noisy, timestep=times, vlm_attn_mask=mask.float(),
|
| 134 |
+
joint_attention_kwargs=dict(action_hidden_embeds=noisy,
|
| 135 |
+
views=views, obs=state, traj2ds=None,
|
| 136 |
+
future_progress=phase),
|
| 137 |
+
).action
|
| 138 |
+
|
| 139 |
+
plain, padded = run(False), run(True)
|
| 140 |
+
assert plain.abs().max() > 0
|
| 141 |
+
torch.testing.assert_close(plain, padded, rtol=1e-5, atol=1e-6)
|
| 142 |
+
model.obs_proj.mask_aware_positions = False
|
| 143 |
+
assert (run(False) - run(True)).abs().max() > 1e-5
|
| 144 |
+
model.obs_proj.mask_aware_positions = True
|
| 145 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
|
| 146 |
+
padded.square().mean().backward()
|
| 147 |
+
grads = [p.grad for p in model.parameters() if p.grad is not None]
|
| 148 |
+
assert grads and all(torch.isfinite(g).all() for g in grads)
|
| 149 |
+
assert model.obs_proj.views_proj.weight.grad.abs().sum() > 0
|
| 150 |
+
before = model.action_proj_out.linear.weight.detach().clone()
|
| 151 |
+
optimizer.step()
|
| 152 |
+
assert not torch.equal(before, model.action_proj_out.linear.weight)
|
tests/test_build_hfd_gqa_scale.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
import sys
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
_PATH = Path(__file__).parents[1] / "scripts" / "data" / "build_hfd_gqa_scale.py"
|
| 7 |
+
sys.path.insert(0, str(_PATH.parent))
|
| 8 |
+
_SPEC = importlib.util.spec_from_file_location("build_hfd_gqa_scale", _PATH)
|
| 9 |
+
_MODULE = importlib.util.module_from_spec(_SPEC)
|
| 10 |
+
assert _SPEC.loader is not None
|
| 11 |
+
_SPEC.loader.exec_module(_MODULE)
|
| 12 |
+
score = _MODULE.score
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_score_is_stable_and_question_specific():
|
| 16 |
+
row = {"imageId": "42", "id": "q1"}
|
| 17 |
+
assert score(row) == score(dict(row))
|
| 18 |
+
assert score(row) != score({"imageId": "42", "id": "q2"})
|
tests/test_causal_audit_shards.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
spec = importlib.util.spec_from_file_location('audit', Path(__file__).parents[1]/'scripts/data/audit_hfd_live_video_windows.py')
|
| 6 |
+
audit = importlib.util.module_from_spec(spec)
|
| 7 |
+
spec.loader.exec_module(audit)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_shards_cover_all_without_overlap_and_keep_voices_together():
|
| 11 |
+
rows = [[dict(asset_id=str(i), voice=str(v)) for v in range(8)] for i in range(101)]
|
| 12 |
+
shards = [audit.shard_assets(rows,i,4) for i in range(4)]
|
| 13 |
+
ids = [v[0]['asset_id'] for shard in shards for v in shard]
|
| 14 |
+
assert len(ids) == len(set(ids)) == 101
|
| 15 |
+
assert all(len(v)==8 for shard in shards for v in shard)
|
| 16 |
+
assert audit.shard_assets(list(reversed(rows)),2,4) == list(reversed(shards[2]))
|
| 17 |
+
assert audit.shard_assets(rows,0,1) == rows
|
| 18 |
+
with pytest.raises(ValueError): audit.shard_assets(rows,4,4)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_manifest_flush_always_includes_last_partial_batch():
|
| 22 |
+
assert [i for i in range(1,252) if audit.checkpoint_due(i,251,100)] == [100,200,251]
|
| 23 |
+
assert audit.checkpoint_due(3,3,100)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_union_decode_preserves_every_prefix_exactly():
|
| 27 |
+
import numpy as np
|
| 28 |
+
calls = []
|
| 29 |
+
def decode(path, targets, *, end_seconds):
|
| 30 |
+
calls.append(targets.copy())
|
| 31 |
+
pts = np.floor(targets * 25) / 25
|
| 32 |
+
return pts[:,None,None,None] + np.zeros((len(pts),2,2,3)), pts
|
| 33 |
+
times = [2.2,5.4,29.8,70.2]
|
| 34 |
+
actual = audit.decode_prefixes('unused', 71., times, 64, decoder=decode)
|
| 35 |
+
assert len(calls) == 1
|
| 36 |
+
for t,(frames,pts) in zip(times,actual):
|
| 37 |
+
reference, stamps = decode('unused', audit.prefix_deadlines(t,max_frames=64),end_seconds=71.)
|
| 38 |
+
np.testing.assert_array_equal(frames,reference)
|
| 39 |
+
np.testing.assert_array_equal(pts,stamps)
|
| 40 |
+
assert (pts <= t).all()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_batched_jobs_keep_identity_and_obey_memory_budget():
|
| 44 |
+
jobs = [dict(index=i,images=[None]*n) for i,n in enumerate([4,64,20,10,64,8,12])]
|
| 45 |
+
batches = list(audit.job_batches(jobs,3,80))
|
| 46 |
+
assert sorted(j['index'] for b in batches for j in b) == list(range(7))
|
| 47 |
+
assert all(len(b)<=3 and sum(len(j['images']) for j in b)<=80 for b in batches)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_prefetch_order_empty_and_error_propagation():
|
| 51 |
+
assert list(audit.ordered_prefetch([],lambda x:x)) == []
|
| 52 |
+
assert list(audit.ordered_prefetch(range(5),lambda x:x*2)) == list(range(0,10,2))
|
| 53 |
+
def fail(x):
|
| 54 |
+
raise ValueError('decode failed')
|
| 55 |
+
with pytest.raises(ValueError,match='decode failed'):
|
| 56 |
+
list(audit.ordered_prefetch([1],fail))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_reuse_requires_known_engine_and_unchanged_semantics():
|
| 60 |
+
new = dict(code_sha256='current', version='v2', source_sha256='source',
|
| 61 |
+
max_frames=64, max_points=8, blind_prompt='same', helper_sha256='helper')
|
| 62 |
+
old = dict(new,code_sha256=audit.LEGACY_CODE_SHA256,num_shards=4)
|
| 63 |
+
assert audit.compatible_contract(old,new)
|
| 64 |
+
for field in ['version','source_sha256','max_frames','blind_prompt','helper_sha256','code_sha256']:
|
| 65 |
+
assert not audit.compatible_contract(dict(old,**{field:'changed'}),new)
|
tests/test_causal_av_packing.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import SimpleNamespace
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from transformers.cache_utils import DynamicCache
|
| 7 |
+
|
| 8 |
+
from psi.models.causal_av import prepare_av_batch, encode_av, fit_complete_av_windows
|
| 9 |
+
from psi.models.full_duplex_psi0 import QwenStreamingKVCache
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class FakeQwen(nn.Module):
|
| 13 |
+
def __init__(self):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.model = FakeCore()
|
| 16 |
+
self.config = SimpleNamespace(vision_start_token_id=9)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class FakeCore(nn.Module):
|
| 20 |
+
def __init__(self):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.embed_tokens = nn.Embedding(10, 4)
|
| 23 |
+
self.calls = []
|
| 24 |
+
def forward(self, **kw):
|
| 25 |
+
self.calls.append(kw)
|
| 26 |
+
x = kw["inputs_embeds"]
|
| 27 |
+
past = kw["past_key_values"] or DynamicCache()
|
| 28 |
+
past.update(x[:, None], x[:, None], 0)
|
| 29 |
+
return SimpleNamespace(last_hidden_state=x + self.embed_tokens.weight[0],
|
| 30 |
+
past_key_values=past)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def packets():
|
| 34 |
+
return [dict(ids=torch.tensor(ids), embeds=torch.arange(len(ids)*4).reshape(-1,4).float(),
|
| 35 |
+
positions=torch.arange(len(ids)).expand(3,-1), next_position=len(ids)+2)
|
| 36 |
+
for ids in ([1,2,9,4], [1,9], [1,2,9])]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_packed_av_matches_original_input_offsets_and_inactive_ledger():
|
| 40 |
+
qwen = FakeQwen()
|
| 41 |
+
rows = packets()
|
| 42 |
+
prepared = prepare_av_batch(qwen, rows, [True, False, True])
|
| 43 |
+
cache = QwenStreamingKVCache.empty(["a","b","c"])
|
| 44 |
+
cache.av_next_positions = (8,10,20)
|
| 45 |
+
result = encode_av(qwen, cache, rows, [True,False,True], memory_seconds=96,
|
| 46 |
+
context_limit=512, prepared=prepared)
|
| 47 |
+
call = qwen.model.calls[-1]
|
| 48 |
+
for row, packet in enumerate(rows):
|
| 49 |
+
size = len(packet["ids"])
|
| 50 |
+
torch.testing.assert_close(call["inputs_embeds"][row,:size], packet["embeds"])
|
| 51 |
+
torch.testing.assert_close(call["position_ids"][:,row,:size], packet["positions"] + [8,10,20][row])
|
| 52 |
+
assert call["inputs_embeds"][row,size:].count_nonzero() == 0
|
| 53 |
+
assert call["position_ids"][:,row,size:].count_nonzero() == 0
|
| 54 |
+
assert result[-1].logical_window_counts == (1,0,1)
|
| 55 |
+
assert result[-1].logical_token_counts == (4,0,3)
|
| 56 |
+
assert result[-1].av_next_positions == (14,10,25)
|
| 57 |
+
assert result[-1].token_birth_windows.tolist() == [[-1,-1,0,0],[-2,-2,-2,-2],[-1,-1,0,-2]]
|
| 58 |
+
# Reusing immutable inputs cannot share private model KVs/gradients.
|
| 59 |
+
private = FakeQwen()
|
| 60 |
+
next_private = encode_av(private, QwenStreamingKVCache.empty(["a","b","c"]), rows,
|
| 61 |
+
[True,False,True], memory_seconds=96, context_limit=512, prepared=prepared)
|
| 62 |
+
next_private[0].sum().backward()
|
| 63 |
+
assert qwen.model.embed_tokens.weight.grad is None
|
| 64 |
+
assert private.model.embed_tokens.weight.grad is not None
|
| 65 |
+
assert next_private[-1].past_key_values is not result[-1].past_key_values
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_scalar_activity_and_bad_shapes():
|
| 69 |
+
qwen = FakeQwen()
|
| 70 |
+
assert prepare_av_batch(qwen, packets(), True).active == (True,True,True)
|
| 71 |
+
with pytest.raises(ValueError, match="one entry"):
|
| 72 |
+
prepare_av_batch(qwen, packets(), [True])
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_token_bound_keeps_whole_packets_prefix_positions_and_each_source():
|
| 76 |
+
cache = QwenStreamingKVCache.empty(["a", "b"])
|
| 77 |
+
cache.logical_window_counts = (3, 3)
|
| 78 |
+
cache.av_next_positions = (123, 456)
|
| 79 |
+
cache.token_count = 10
|
| 80 |
+
cache.attention_mask = torch.tensor([[1]*10, [1]*8+[0]*2])
|
| 81 |
+
cache.token_birth_windows = torch.tensor([
|
| 82 |
+
[-1,-1,0,0,0,1,1,1,2,2],
|
| 83 |
+
[-1,0,0,1,1,1,2,2,-2,-2],
|
| 84 |
+
])
|
| 85 |
+
keys = torch.arange(20).reshape(2,1,10,1).float()
|
| 86 |
+
cache.past_key_values = DynamicCache()
|
| 87 |
+
cache.past_key_values.update(keys, keys + 100, 0)
|
| 88 |
+
fit_complete_av_windows(cache, current_tokens=2, auxiliary_tokens=1, context_limit=9)
|
| 89 |
+
# Six old tokens fit, but row a's 3-token packet 1 must not be split.
|
| 90 |
+
assert cache.token_count == 6
|
| 91 |
+
assert cache.attention_mask.tolist() == [[1,1,1,1,0,0], [1]*6]
|
| 92 |
+
assert cache.token_birth_windows.tolist() == [[-1,-1,2,2,-2,-2], [-1,1,1,1,2,2]]
|
| 93 |
+
assert cache.past_key_values.layers[0].keys[0,0,:4,0].tolist() == [0,1,8,9]
|
| 94 |
+
assert cache.past_key_values.layers[0].keys[1,0,:,0].tolist() == [10,13,14,15,16,17]
|
| 95 |
+
assert cache.logical_window_counts == (3,3)
|
| 96 |
+
assert cache.av_next_positions == (123,456)
|
| 97 |
+
cache.rebind_rows(["new","b"], [True,False])
|
| 98 |
+
assert cache.av_next_positions == (0,456)
|
| 99 |
+
assert cache.attention_mask[0].sum() == 0
|
| 100 |
+
assert cache.attention_mask[1].sum() == 6
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_av_stream_exceeds_time_vs_token_budget_without_crashing():
|
| 104 |
+
qwen = FakeQwen().eval()
|
| 105 |
+
cache = QwenStreamingKVCache.empty(["a"])
|
| 106 |
+
rows = [packets()[0]]
|
| 107 |
+
with torch.inference_mode():
|
| 108 |
+
for i in range(30):
|
| 109 |
+
result = encode_av(qwen, cache, rows, True, memory_seconds=96,
|
| 110 |
+
context_limit=24, auxiliary=4)
|
| 111 |
+
cache = result[-1]
|
| 112 |
+
cache.detach()
|
| 113 |
+
assert cache.token_count <= 20
|
| 114 |
+
assert cache.logical_window_counts == (i+1,)
|
| 115 |
+
assert cache.av_next_positions == ((i+1)*6,)
|
| 116 |
+
assert cache.reclaimed_token_count > 0
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_av_fitting_is_noop_without_pressure_and_rejects_impossible_prefix():
|
| 120 |
+
cache = QwenStreamingKVCache.empty(["a"])
|
| 121 |
+
fit_complete_av_windows(cache, current_tokens=4, auxiliary_tokens=4, context_limit=8)
|
| 122 |
+
assert cache.past_key_values is None
|
| 123 |
+
cache.token_count=3
|
| 124 |
+
cache.attention_mask=torch.ones(1,3,dtype=torch.long)
|
| 125 |
+
cache.token_birth_windows=torch.full((1,3),-1)
|
| 126 |
+
with pytest.raises(RuntimeError,match="system prefix"):
|
| 127 |
+
fit_complete_av_windows(cache,current_tokens=4,auxiliary_tokens=4,context_limit=10)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class LiveQwen(FakeQwen):
|
| 131 |
+
def __init__(self):
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.config = SimpleNamespace(vision_start_token_id=9, video_token_id=8,
|
| 134 |
+
vision_end_token_id=7, audio_start_token_id=6, audio_token_id=5, audio_end_token_id=4)
|
| 135 |
+
self._hfd_av_prefix_ids = (1, 2)
|
| 136 |
+
self.audio_tower = nn.Linear(1,1).requires_grad_(False)
|
| 137 |
+
self.audio_tower._get_feat_extract_output_lengths = lambda n: (n, (n-1)//2//2+1)
|
| 138 |
+
def get_input_embeddings(self):
|
| 139 |
+
return self.model.embed_tokens
|
| 140 |
+
def get_rope_index(self, ids, **kw):
|
| 141 |
+
assert ids.device.type == kw['audio_seqlens'].device.type == 'cpu'
|
| 142 |
+
return torch.arange(ids.shape[-1])[None,None].expand(3,1,-1), None
|
| 143 |
+
def get_audio_features(self, features, masks):
|
| 144 |
+
counts = ((masks.sum(-1)-1)//2//2+1).tolist()
|
| 145 |
+
return torch.cat([features[i].mean().expand(n,4) for i,n in enumerate(counts)])
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def live_packet(value, *, visual=True, first=True):
|
| 149 |
+
return dict(live_audio=True, first_window=first, camera_count=5,
|
| 150 |
+
input_features=torch.full((128,63),float(value)),
|
| 151 |
+
feature_attention_mask=torch.ones(63),
|
| 152 |
+
visual_features=torch.full((192,4),13.) if visual else None)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@pytest.mark.skipif(not torch.cuda.is_available(), reason='CUDA placement regression')
|
| 156 |
+
def test_live_packets_already_placed_by_accelerate():
|
| 157 |
+
model = LiveQwen().cuda()
|
| 158 |
+
packet = {k:(v.cuda() if isinstance(v,torch.Tensor) else v)
|
| 159 |
+
for k,v in live_packet(3).items()}
|
| 160 |
+
prepared = prepare_av_batch(model,[packet],True)
|
| 161 |
+
assert prepared.embeds.device.type == 'cuda'
|
| 162 |
+
assert prepared.positions.device.type == 'cuda'
|
| 163 |
+
actual = prepared.embeds[0,prepared.ids[0]==5]
|
| 164 |
+
torch.testing.assert_close(actual,torch.full_like(actual,3.))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def test_live_audio_visual_and_refill_share_one_batch_without_cross_source_state():
|
| 168 |
+
model = LiveQwen()
|
| 169 |
+
a,b = live_packet(3),live_packet(7,visual=False)
|
| 170 |
+
prepared = prepare_av_batch(model,[a,b],[True,True])
|
| 171 |
+
for row, value in enumerate((3.,7.)):
|
| 172 |
+
assert torch.all(prepared.embeds[row,prepared.ids[row]==5] == value)
|
| 173 |
+
assert torch.all(prepared.embeds[0,prepared.ids[0]==8] == 13.)
|
| 174 |
+
assert (prepared.ids[1]==8).sum() == 0
|
| 175 |
+
result = encode_av(model,QwenStreamingKVCache.empty(['a','b']),[a,b],True,
|
| 176 |
+
memory_seconds=96,context_limit=1024,prepared=prepared)
|
| 177 |
+
cache=result[-1];cache.detach()
|
| 178 |
+
b_offset=cache.av_next_positions[1]
|
| 179 |
+
cache.rebind_rows(['c','b'],[True,False])
|
| 180 |
+
assert cache.av_next_positions==(0,b_offset)
|
| 181 |
+
assert cache.attention_mask[0].sum()==0 and cache.attention_mask[1].sum()>0
|
| 182 |
+
next_packets=[live_packet(11,visual=False),live_packet(19,first=False)]
|
| 183 |
+
next_p=prepare_av_batch(model,next_packets,True)
|
| 184 |
+
result=encode_av(model,cache,next_packets,True,memory_seconds=96,context_limit=1024,prepared=next_p)
|
| 185 |
+
assert result[-1].logical_window_counts == (1,2)
|
| 186 |
+
assert torch.all(next_p.embeds[0,next_p.ids[0]==5]==11)
|
| 187 |
+
assert model.model.calls[-1]['position_ids'][0,0,0]==0
|
| 188 |
+
assert model.model.calls[-1]['position_ids'][0,1,0]==b_offset
|
| 189 |
+
assert not next_p.embeds.requires_grad
|
tests/test_causal_video_qa.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from psi.data.seed.causal_video_qa import (DurationPool, candidate_times,
|
| 5 |
+
point, prefix_deadlines, valid_point, question_end_choices)
|
| 6 |
+
from test_live_multimodal_overlay import dataset, source
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_history_not_just_recent_and_no_future():
|
| 10 |
+
times = prefix_deadlines(12.)
|
| 11 |
+
assert times[0] == 0 and times[-1] == 12
|
| 12 |
+
assert np.any(times < 10.5) and np.all(times <= 12)
|
| 13 |
+
assert len(prefix_deadlines(200.)) == 64
|
| 14 |
+
with pytest.raises(ValueError):
|
| 15 |
+
prefix_deadlines(float('nan'))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.mark.parametrize('duration', [5.039, 10., 15., 30., 180.])
|
| 19 |
+
def test_short_videos_admitted_on_real_semantic_grid(duration):
|
| 20 |
+
times = candidate_times(duration)
|
| 21 |
+
assert times and len(times) <= 8
|
| 22 |
+
assert all(valid_point(point(t), duration) for t in times)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_exact_points_no_bridging_and_reply_must_fit():
|
| 26 |
+
row = dict(duration_seconds=20., causal_qa_points=[point(5.4), point(8.2)])
|
| 27 |
+
assert question_end_choices(row, [(4.,9.2)], 1., 10.2) == [5.4,8.2]
|
| 28 |
+
assert question_end_choices(row, [(6.,8.)], 1., 10.2) == []
|
| 29 |
+
assert question_end_choices(row, [(4.,9.2)], 1., 8.8) == [5.4]
|
| 30 |
+
bad = point(5.4); bad['reply_deadlines'][1] = 5.
|
| 31 |
+
assert not valid_point(bad,20.)
|
| 32 |
+
assert not valid_point(point(5.5),20.)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_duration_buckets_skip_short_rejects_prefer_near_fit():
|
| 36 |
+
rows = [dict(video_path='too-short', duration_seconds=2.) for _ in range(10000)]
|
| 37 |
+
rows += [dict(video_path='fits', duration_seconds=12.), dict(video_path='long', duration_seconds=40.)]
|
| 38 |
+
index = DurationPool(rows)
|
| 39 |
+
assert list(index.picks(11.,np.random.default_rng(42))) == [10000,10001]
|
| 40 |
+
assert list(index.picks(31.,np.random.default_rng(42))) == [10001]
|
| 41 |
+
assert list(index.picks(41.,np.random.default_rng(42))) == []
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_exact_qa_end_and_motion_unchanged(tmp_path):
|
| 45 |
+
ds = dataset(tmp_path)
|
| 46 |
+
row = ds.by_voice['female_01_en'][0]
|
| 47 |
+
row.update(video_path='short.mp4', duration_seconds=12.,
|
| 48 |
+
causal_qa_points=[point(5.4)], earliest_answer_video_seconds=5.4)
|
| 49 |
+
raw = source(); out = ds.compose(raw, 'qa')
|
| 50 |
+
relation = out['multimodal_overlay']
|
| 51 |
+
assert relation['mode'] == 'qa'
|
| 52 |
+
assert relation['question_start'] == pytest.approx(4.4)
|
| 53 |
+
assert relation['question_end'] == pytest.approx(5.4)
|
| 54 |
+
for a,b in zip(raw['steps'],out['steps']):
|
| 55 |
+
for k in ('actions','states','control_label','future_progress'):
|
| 56 |
+
np.testing.assert_array_equal(a[k],b[k])
|
| 57 |
+
row['causal_qa_points'] = [point(9.4)] # question outside safe motion region
|
| 58 |
+
assert ds.compose(raw,'qa')['multimodal_overlay']['mode'] == 'audio-only'
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_replaced_inference_pool_rebuilds_index(tmp_path):
|
| 62 |
+
ds = dataset(tmp_path); row = ds.by_voice['female_01_en'][0]
|
| 63 |
+
ds.by_voice['female_01_en'] = [dict(row,asset_id=str(i)) for i in range(70)]
|
| 64 |
+
assert ds.compose(source(),'qa')['multimodal_overlay']['mode'] == 'qa'
|
| 65 |
+
ds.by_voice['female_01_en'] = [dict(row,video_path='short',duration_seconds=2.) for _ in range(70)]
|
| 66 |
+
assert ds.compose(source(),'qa')['multimodal_overlay']['mode'] == 'audio-only'
|
tests/test_checkpoint_marker_atomicity.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import SimpleNamespace
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from psi.trainers import posttrain_full_duplex as module
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_invalid_contract_does_not_truncate_existing_marker(tmp_path, monkeypatch):
|
| 9 |
+
marker = tmp_path / 'full_duplex_source_boundary.json'
|
| 10 |
+
marker.write_text('{"previous": "valid"}')
|
| 11 |
+
trainer = module.PosttrainFullDuplexTrainer.__new__(module.PosttrainFullDuplexTrainer)
|
| 12 |
+
trainer.accelerator = SimpleNamespace(is_main_process=True)
|
| 13 |
+
|
| 14 |
+
def invalid():
|
| 15 |
+
raise RuntimeError('missing production marker')
|
| 16 |
+
|
| 17 |
+
monkeypatch.setattr(module, '_active_continuous_data_contract_identity', invalid)
|
| 18 |
+
with pytest.raises(RuntimeError, match='missing production marker'):
|
| 19 |
+
trainer._write_full_duplex_boundary_marker(str(tmp_path), global_step=10)
|
| 20 |
+
assert marker.read_text() == '{"previous": "valid"}'
|
| 21 |
+
assert not (tmp_path / 'full_duplex_source_boundary.json.partial').exists()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_invalid_contract_fails_before_saving_state(monkeypatch):
|
| 25 |
+
trainer = module.PosttrainFullDuplexTrainer.__new__(module.PosttrainFullDuplexTrainer)
|
| 26 |
+
trainer._at_source_group_boundary = True
|
| 27 |
+
|
| 28 |
+
def invalid():
|
| 29 |
+
raise RuntimeError('missing production marker')
|
| 30 |
+
|
| 31 |
+
monkeypatch.setattr(module, '_active_continuous_data_contract_identity', invalid)
|
| 32 |
+
# No accelerator/model is provided: touching save_state would fail this test.
|
| 33 |
+
with pytest.raises(RuntimeError, match='missing production marker'):
|
| 34 |
+
trainer.save_checkpoint(10)
|
tests/test_continuous_audio_command_sources.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import importlib.util
|
| 4 |
+
import json
|
| 5 |
+
import wave
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
+
SCRIPT = (
|
| 13 |
+
PROJECT_ROOT
|
| 14 |
+
/ "scripts"
|
| 15 |
+
/ "data"
|
| 16 |
+
/ "build_continuous_audio_command_sources.py"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _load_module():
|
| 21 |
+
spec = importlib.util.spec_from_file_location(
|
| 22 |
+
"build_continuous_audio_command_sources_test",
|
| 23 |
+
SCRIPT,
|
| 24 |
+
)
|
| 25 |
+
assert spec is not None and spec.loader is not None
|
| 26 |
+
module = importlib.util.module_from_spec(spec)
|
| 27 |
+
spec.loader.exec_module(module)
|
| 28 |
+
return module
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _write_wav(path: Path, samples: np.ndarray) -> None:
|
| 32 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
pcm = np.rint(
|
| 34 |
+
np.clip(np.asarray(samples), -1.0, 1.0) * 32767.0
|
| 35 |
+
).astype("<i2")
|
| 36 |
+
with wave.open(str(path), "wb") as handle:
|
| 37 |
+
handle.setnchannels(1)
|
| 38 |
+
handle.setsampwidth(2)
|
| 39 |
+
handle.setframerate(16_000)
|
| 40 |
+
handle.writeframes(pcm.tobytes())
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_mixed_source_keeps_one_background_timeline_at_both_boundaries(
|
| 44 |
+
tmp_path: Path,
|
| 45 |
+
) -> None:
|
| 46 |
+
module = _load_module()
|
| 47 |
+
source_key = "seed_audio/000001/female_01_en"
|
| 48 |
+
speech_root = tmp_path / "speech"
|
| 49 |
+
mixed_root = tmp_path / "mixed"
|
| 50 |
+
time = np.arange(16_000, dtype=np.float32) / 16_000.0
|
| 51 |
+
speech = 0.1 * np.sin(2.0 * np.pi * 440.0 * time)
|
| 52 |
+
_write_wav(speech_root / f"{source_key}.wav", speech)
|
| 53 |
+
|
| 54 |
+
background_pcm = (
|
| 55 |
+
(np.arange(160_000, dtype=np.int32) % 2000) - 1000
|
| 56 |
+
).astype("<i2")
|
| 57 |
+
session = {
|
| 58 |
+
"key": "sessions/office",
|
| 59 |
+
"sha256": "test-background",
|
| 60 |
+
"window_count": (
|
| 61 |
+
(background_pcm.size - module.WINDOW_SAMPLES)
|
| 62 |
+
// module.STRIDE_SAMPLES
|
| 63 |
+
+ 1
|
| 64 |
+
),
|
| 65 |
+
"pcm": background_pcm,
|
| 66 |
+
}
|
| 67 |
+
row = module._build_one_source(
|
| 68 |
+
source_key=source_key,
|
| 69 |
+
speech_root=speech_root,
|
| 70 |
+
mixed_root=mixed_root,
|
| 71 |
+
max_motion_frames=40,
|
| 72 |
+
sessions=[session],
|
| 73 |
+
initial_idle_max_steps=2,
|
| 74 |
+
stationary_blend_frames=20,
|
| 75 |
+
safety_steps=1,
|
| 76 |
+
seed=123,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
mixed = module._read_pcm16(Path(row["mixed_audio_path"]))
|
| 80 |
+
background_start = (
|
| 81 |
+
row["background_listen_start_index"] * module.STRIDE_SAMPLES
|
| 82 |
+
)
|
| 83 |
+
expected = background_pcm[
|
| 84 |
+
background_start : background_start + mixed.size
|
| 85 |
+
]
|
| 86 |
+
speech_start = row["speech_offset_samples"]
|
| 87 |
+
speech_end = speech_start + row["speech_samples"]
|
| 88 |
+
np.testing.assert_array_equal(mixed[:speech_start], expected[:speech_start])
|
| 89 |
+
np.testing.assert_array_equal(mixed[speech_end:], expected[speech_end:])
|
| 90 |
+
decoded_speech = module._read_speech_float(
|
| 91 |
+
speech_root / f"{source_key}.wav"
|
| 92 |
+
)
|
| 93 |
+
expected_mixed = expected.copy()
|
| 94 |
+
expected_mixed[speech_start:speech_end] = np.rint(
|
| 95 |
+
(
|
| 96 |
+
expected[speech_start:speech_end].astype(np.float32)
|
| 97 |
+
/ np.float32(32768.0)
|
| 98 |
+
+ decoded_speech * np.float32(row["speech_scale"])
|
| 99 |
+
)
|
| 100 |
+
* np.float32(32768.0)
|
| 101 |
+
).clip(-32768, 32767).astype("<i2")
|
| 102 |
+
np.testing.assert_array_equal(mixed, expected_mixed)
|
| 103 |
+
actual_windows = (
|
| 104 |
+
(mixed.size - module.WINDOW_SAMPLES) // module.STRIDE_SAMPLES + 1
|
| 105 |
+
)
|
| 106 |
+
assert actual_windows == row["listen_window_count"]
|
| 107 |
+
assert row["background_listen_start_index"] >= 2
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_background_slot_is_deterministic_and_never_wraps() -> None:
|
| 111 |
+
module = _load_module()
|
| 112 |
+
sessions = [
|
| 113 |
+
{"key": "short", "window_count": 10},
|
| 114 |
+
{"key": "long", "window_count": 100},
|
| 115 |
+
]
|
| 116 |
+
first = module._select_background_slot(
|
| 117 |
+
source_key="seed_audio/000001/voice",
|
| 118 |
+
listen_windows=20,
|
| 119 |
+
max_motion_steps=30,
|
| 120 |
+
sessions=sessions,
|
| 121 |
+
initial_idle_max_steps=5,
|
| 122 |
+
safety_steps=10,
|
| 123 |
+
seed=42,
|
| 124 |
+
)
|
| 125 |
+
second = module._select_background_slot(
|
| 126 |
+
source_key="seed_audio/000001/voice",
|
| 127 |
+
listen_windows=20,
|
| 128 |
+
max_motion_steps=30,
|
| 129 |
+
sessions=sessions,
|
| 130 |
+
initial_idle_max_steps=5,
|
| 131 |
+
safety_steps=10,
|
| 132 |
+
seed=42,
|
| 133 |
+
)
|
| 134 |
+
assert first[0]["key"] == "long"
|
| 135 |
+
assert (first[0]["key"], first[1]) == (second[0]["key"], second[1])
|
| 136 |
+
assert first[1] >= 5
|
| 137 |
+
assert first[1] + 20 + 30 + 10 <= first[0]["window_count"]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_valid_source_list_can_be_reused_after_legacy_cache_cleanup(
|
| 141 |
+
tmp_path: Path,
|
| 142 |
+
) -> None:
|
| 143 |
+
module = _load_module()
|
| 144 |
+
assignment_path = tmp_path / "source_background_assignments.jsonl"
|
| 145 |
+
rows = [
|
| 146 |
+
{
|
| 147 |
+
"source_key": "seed_audio/000001/female_01_en",
|
| 148 |
+
"listen_window_count": 7,
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"source_key": "seed_audio/000002/male_01_zh",
|
| 152 |
+
"listen_window_count": 11,
|
| 153 |
+
},
|
| 154 |
+
]
|
| 155 |
+
assignment_path.write_text(
|
| 156 |
+
"".join(json.dumps(row) + "\n" for row in rows),
|
| 157 |
+
encoding="utf-8",
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
result = module._load_valid_sources(
|
| 161 |
+
tmp_path / "deleted_legacy_cache",
|
| 162 |
+
assignment_path,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
assert result == {
|
| 166 |
+
"seed_audio/000001/female_01_en": 7,
|
| 167 |
+
"seed_audio/000002/male_01_zh": 11,
|
| 168 |
+
}
|
tests/test_control_metrics_distributed.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Eight logical ranks, including ranks without observations, reduce once."""
|
| 2 |
+
import json
|
| 3 |
+
from types import SimpleNamespace
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
import torch.multiprocessing as mp
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def worker(rank, rendezvous, output):
|
| 10 |
+
from psi.models.interaction_arch.control_metrics import flush
|
| 11 |
+
torch.set_num_threads(1)
|
| 12 |
+
dist.init_process_group('gloo', init_method='file://'+rendezvous, rank=rank, world_size=8)
|
| 13 |
+
try:
|
| 14 |
+
trainer=SimpleNamespace(model=SimpleNamespace(), accelerator=SimpleNamespace(
|
| 15 |
+
device=torch.device('cpu'), unwrap_model=lambda model:model))
|
| 16 |
+
if rank < 2:
|
| 17 |
+
cm=torch.zeros(9,dtype=torch.long)
|
| 18 |
+
cm[rank]=3 if rank==0 else 1
|
| 19 |
+
trainer._token_control_meters={'train':dict(confusion=cm, paired=0,
|
| 20 |
+
gt_switch=0,pred_switch=0,exact_switch=0,false_switch=0,triplets=0,flicker=0)}
|
| 21 |
+
metrics=flush(trainer,'train')
|
| 22 |
+
assert metrics['train/token_control_accuracy']==0.75
|
| 23 |
+
assert metrics['train/token_control_cm_listen_listen']==3
|
| 24 |
+
assert metrics['train/token_control_cm_listen_motion']==1
|
| 25 |
+
assert flush(trainer,'train')=={}
|
| 26 |
+
if rank==0:
|
| 27 |
+
with open(output,'w') as stream:json.dump(metrics,stream)
|
| 28 |
+
finally:
|
| 29 |
+
dist.destroy_process_group()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_eight_rank_metric_reduction_with_empty_ranks(tmp_path):
|
| 33 |
+
mp.start_processes(worker,args=(str(tmp_path/'init'),str(tmp_path/'metrics.json')),
|
| 34 |
+
nprocs=8,join=True,start_method='fork')
|
| 35 |
+
assert json.loads((tmp_path/'metrics.json').read_text())['train/token_control_accuracy']==.75
|
tests/test_dlc_storage.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import pytest
|
| 4 |
+
from psi import dlc_storage as storage
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def checkpoint(run, step, world=8):
|
| 8 |
+
path = run/'checkpoints'/f'ckpt_{step}'
|
| 9 |
+
path.mkdir(parents=True)
|
| 10 |
+
for name in ['model.safetensors', 'optimizer.bin', 'scheduler.bin', 'custom_checkpoint_0.pkl'] + [f'random_states_{i}.pkl' for i in range(world)]:
|
| 11 |
+
(path/name).write_bytes(b'complete-state-'+str(step).encode())
|
| 12 |
+
(path/'hfd_fused_delta_manifest.json').write_text(json.dumps({'contract': {'version': 1}}))
|
| 13 |
+
(path/'full_duplex_source_boundary.json').write_text(json.dumps(dict(
|
| 14 |
+
global_step=step, source_group_complete=True, train_infer_contract={'version': 1})))
|
| 15 |
+
return path
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def run_files(run):
|
| 19 |
+
run.mkdir(exist_ok=True)
|
| 20 |
+
for name in ['run_config.json', 'argv.txt', 'architecture_manifest.json', 'control_token_contract.json']:
|
| 21 |
+
(run/name).write_text('{}')
|
| 22 |
+
(run/'control_tokenizer').mkdir(exist_ok=True)
|
| 23 |
+
(run/'control_tokenizer/tokenizer.json').write_text('{}')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_eight_rank_roundtrip_and_transactional_retention(tmp_path):
|
| 27 |
+
run, backup, restored = [tmp_path/n for n in ['run', 'backup', 'restored']]
|
| 28 |
+
run_files(run)
|
| 29 |
+
for step in (10, 20, 30):
|
| 30 |
+
checkpoint(run, step)
|
| 31 |
+
assert storage.synchronize(run, backup, 8) == step
|
| 32 |
+
assert not (backup/'checkpoints/ckpt_10').exists()
|
| 33 |
+
assert (backup/'checkpoints/ckpt_20').exists()
|
| 34 |
+
restored_ckpt = storage.restore(backup, restored, 8)
|
| 35 |
+
assert storage.ready(restored_ckpt, 8)
|
| 36 |
+
assert (restored/'control_tokenizer/tokenizer.json').is_file()
|
| 37 |
+
assert storage.digest(restored_ckpt/'optimizer.bin') == storage.digest(run/'checkpoints/ckpt_30/optimizer.bin')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_incomplete_rank_rng_is_never_published(tmp_path):
|
| 41 |
+
run, backup = tmp_path/'run', tmp_path/'backup'
|
| 42 |
+
run_files(run)
|
| 43 |
+
ckpt = checkpoint(run, 10)
|
| 44 |
+
(ckpt/'random_states_7.pkl').unlink()
|
| 45 |
+
assert storage.synchronize(run, backup, 8) is None
|
| 46 |
+
assert not (backup/'latest_backup.json').exists()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_copy_failure_keeps_previous_generation_and_retries(tmp_path, monkeypatch):
|
| 50 |
+
run, backup = tmp_path/'run', tmp_path/'backup'
|
| 51 |
+
run_files(run)
|
| 52 |
+
checkpoint(run, 10)
|
| 53 |
+
storage.synchronize(run, backup, 8)
|
| 54 |
+
checkpoint(run, 20)
|
| 55 |
+
original = storage.copy_verified
|
| 56 |
+
def failed(source, target):
|
| 57 |
+
if source.name == 'optimizer.bin':
|
| 58 |
+
raise OSError('No space left on device')
|
| 59 |
+
return original(source, target)
|
| 60 |
+
monkeypatch.setattr(storage, 'copy_verified', failed)
|
| 61 |
+
with pytest.raises(OSError):
|
| 62 |
+
storage.synchronize(run, backup, 8)
|
| 63 |
+
assert json.loads((backup/'latest_backup.json').read_text())['step'] == 10
|
| 64 |
+
assert not (backup/'checkpoints/ckpt_20').exists()
|
| 65 |
+
monkeypatch.setattr(storage, 'copy_verified', original)
|
| 66 |
+
assert storage.synchronize(run, backup, 8) == 20
|
| 67 |
+
assert storage.ready(backup/'checkpoints/ckpt_20', 8)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_restore_rejects_corrupted_bytes(tmp_path):
|
| 71 |
+
run, backup = tmp_path/'run', tmp_path/'backup'
|
| 72 |
+
run_files(run)
|
| 73 |
+
checkpoint(run, 10)
|
| 74 |
+
storage.synchronize(run, backup, 8)
|
| 75 |
+
(backup/'checkpoints/ckpt_10/optimizer.bin').write_bytes(b'corrupted')
|
| 76 |
+
with pytest.raises(OSError, match='checksum'):
|
| 77 |
+
storage.restore(backup, tmp_path/'restore', 8)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_restore_rejects_world_size_change(tmp_path):
|
| 81 |
+
run, backup = tmp_path/'run', tmp_path/'backup'
|
| 82 |
+
run_files(run)
|
| 83 |
+
checkpoint(run,10)
|
| 84 |
+
storage.synchronize(run,backup,8)
|
| 85 |
+
with pytest.raises(ValueError,match='rank count'):
|
| 86 |
+
storage.restore(backup,tmp_path/'restore',1)
|
tests/test_full_duplex_audio_contract.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from psi.data.seed.full_duplex_audio_contract import (
|
| 8 |
+
HFD_ONLINE_ENCODER_CONTRACT,
|
| 9 |
+
encoder_contract_payload,
|
| 10 |
+
validate_encoder_cache,
|
| 11 |
+
write_json_atomic,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _write_fake_model(path):
|
| 16 |
+
path.mkdir()
|
| 17 |
+
(path / "config.json").write_text('{"model_type": "qwen2_5_omni"}\n')
|
| 18 |
+
(path / "tokenizer_config.json").write_text('{"model_max_length": 32768}\n')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_verified_encoder_cache_contract_is_accepted(tmp_path):
|
| 22 |
+
model = tmp_path / "model"
|
| 23 |
+
cache = tmp_path / "cache"
|
| 24 |
+
_write_fake_model(model)
|
| 25 |
+
contract = encoder_contract_payload(model)
|
| 26 |
+
write_json_atomic(cache / "_reports" / "encoder_contract.json", contract)
|
| 27 |
+
write_json_atomic(
|
| 28 |
+
cache / "_reports" / "online_hidden_verify.json",
|
| 29 |
+
{
|
| 30 |
+
**contract,
|
| 31 |
+
"verified_sources": 2,
|
| 32 |
+
"verified_windows": 3,
|
| 33 |
+
"mismatched_windows": 0,
|
| 34 |
+
"max_abs_error": 0.0,
|
| 35 |
+
},
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
accepted = validate_encoder_cache(cache, model)
|
| 39 |
+
|
| 40 |
+
assert accepted["encoder_contract"] == HFD_ONLINE_ENCODER_CONTRACT
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_non_exact_online_report_is_rejected(tmp_path):
|
| 44 |
+
model = tmp_path / "model"
|
| 45 |
+
cache = tmp_path / "cache"
|
| 46 |
+
_write_fake_model(model)
|
| 47 |
+
contract = encoder_contract_payload(model)
|
| 48 |
+
write_json_atomic(cache / "_reports" / "encoder_contract.json", contract)
|
| 49 |
+
report = {
|
| 50 |
+
**contract,
|
| 51 |
+
"verified_windows": 1,
|
| 52 |
+
"mismatched_windows": 1,
|
| 53 |
+
"max_abs_error": 0.125,
|
| 54 |
+
}
|
| 55 |
+
report_path = cache / "_reports" / "online_hidden_verify.json"
|
| 56 |
+
report_path.parent.mkdir(parents=True, exist_ok=True)
|
| 57 |
+
report_path.write_text(json.dumps(report))
|
| 58 |
+
|
| 59 |
+
with pytest.raises(RuntimeError, match="failed exact online equivalence"):
|
| 60 |
+
validate_encoder_cache(cache, model)
|
tests/test_full_duplex_continuous_cache.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from psi.data.seed.full_duplex_audio_command_dataset import (
|
| 9 |
+
AudioSource,
|
| 10 |
+
FullDuplexAudioCommandDataset,
|
| 11 |
+
HiddenSlice,
|
| 12 |
+
)
|
| 13 |
+
from psi.models.full_duplex_psi0 import StreamingCausalMemory
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _minimal_source_dataset(monkeypatch) -> FullDuplexAudioCommandDataset:
|
| 17 |
+
dataset = FullDuplexAudioCommandDataset.__new__(FullDuplexAudioCommandDataset)
|
| 18 |
+
dataset.records = [
|
| 19 |
+
{
|
| 20 |
+
"row_id": 3,
|
| 21 |
+
"filename": "test_motion",
|
| 22 |
+
"instruction": "test",
|
| 23 |
+
"audio_dir": "seed_audio/000003",
|
| 24 |
+
"motion_dir": Path("/unused/test_motion"),
|
| 25 |
+
"declared_frames": 20,
|
| 26 |
+
}
|
| 27 |
+
]
|
| 28 |
+
dataset.audio_catalog = {
|
| 29 |
+
"seed_audio/000003": (
|
| 30 |
+
AudioSource(
|
| 31 |
+
"seed_audio/000003/voice",
|
| 32 |
+
(HiddenSlice(0, Path("/unused/0"), 0, 1),),
|
| 33 |
+
),
|
| 34 |
+
)
|
| 35 |
+
}
|
| 36 |
+
dataset.white_noise_hidden = (torch.full((2, 8), 9.0),)
|
| 37 |
+
dataset.fixed_voice_per_record = True
|
| 38 |
+
dataset.action_chunk_size = 30
|
| 39 |
+
dataset.action_exec_horizon = 20
|
| 40 |
+
dataset.prefix_frames = 10
|
| 41 |
+
dataset.max_motion_steps = 0
|
| 42 |
+
dataset.initial_idle_max_steps = 1
|
| 43 |
+
dataset.stationary_blend_frames = 20
|
| 44 |
+
motion = np.zeros((20, 36), dtype=np.float32)
|
| 45 |
+
motion[:, 32] = 1.0
|
| 46 |
+
monkeypatch.setattr(dataset, "_load_motion", lambda path: motion)
|
| 47 |
+
monkeypatch.setattr(dataset, "_load_slice", lambda item: torch.ones(2, 8))
|
| 48 |
+
monkeypatch.setattr(
|
| 49 |
+
dataset,
|
| 50 |
+
"_sample_stationary_anchor",
|
| 51 |
+
lambda task_start_pose: np.asarray(task_start_pose, dtype=np.float32),
|
| 52 |
+
)
|
| 53 |
+
monkeypatch.setattr(
|
| 54 |
+
dataset,
|
| 55 |
+
"_sample_stationary_sequence",
|
| 56 |
+
lambda phase, frame_count, anchor_pose: (
|
| 57 |
+
np.repeat(
|
| 58 |
+
np.asarray(anchor_pose, dtype=np.float32)[None, :],
|
| 59 |
+
frame_count,
|
| 60 |
+
axis=0,
|
| 61 |
+
),
|
| 62 |
+
f"test-{phase}",
|
| 63 |
+
),
|
| 64 |
+
)
|
| 65 |
+
monkeypatch.setattr(
|
| 66 |
+
dataset,
|
| 67 |
+
"_build_task_sequence",
|
| 68 |
+
lambda task_motion, stationary_anchor: (
|
| 69 |
+
np.asarray(task_motion, dtype=np.float32),
|
| 70 |
+
1,
|
| 71 |
+
),
|
| 72 |
+
)
|
| 73 |
+
monkeypatch.setattr("random.randint", lambda low, high: 1)
|
| 74 |
+
return dataset
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_idle_listen_and_motion_keep_qwen_cadence_with_dense_actions(monkeypatch):
|
| 78 |
+
source = _minimal_source_dataset(monkeypatch)[0]
|
| 79 |
+
|
| 80 |
+
phases = [step["phase"] for step in source["steps"]]
|
| 81 |
+
assert phases.count("idle") == 20
|
| 82 |
+
assert phases.count("listen") == 20
|
| 83 |
+
assert phases.count("motion") == 9
|
| 84 |
+
assert [
|
| 85 |
+
index
|
| 86 |
+
for index, step in enumerate(source["steps"])
|
| 87 |
+
if step["update_semantic_cache"]
|
| 88 |
+
] == [0, 20, 40]
|
| 89 |
+
assert all(
|
| 90 |
+
step["action_substep"] == 0
|
| 91 |
+
for step in source["steps"]
|
| 92 |
+
if step["update_semantic_cache"]
|
| 93 |
+
)
|
| 94 |
+
assert all(
|
| 95 |
+
not step["update_semantic_cache"]
|
| 96 |
+
for step in source["steps"]
|
| 97 |
+
if step["action_substep"] != 0
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_continuous_cache_caps_each_source_without_padding_shrinkage():
|
| 102 |
+
memory = StreamingCausalMemory(
|
| 103 |
+
input_dim=8,
|
| 104 |
+
hidden_dim=16,
|
| 105 |
+
num_layers=1,
|
| 106 |
+
num_heads=4,
|
| 107 |
+
dropout=0.0,
|
| 108 |
+
max_cache_tokens=3,
|
| 109 |
+
).eval()
|
| 110 |
+
cache = memory.begin_source(["long-source", "finished-source"])
|
| 111 |
+
|
| 112 |
+
for _ in range(3):
|
| 113 |
+
_, cache, _ = memory(
|
| 114 |
+
torch.randn(2, 8),
|
| 115 |
+
cache,
|
| 116 |
+
source_ids=["long-source", "finished-source"],
|
| 117 |
+
update_cache=[True, True],
|
| 118 |
+
)
|
| 119 |
+
assert cache.sequence_lengths == (3, 3)
|
| 120 |
+
|
| 121 |
+
# False denotes only a padded row. Continuing the other source must retain
|
| 122 |
+
# the finished source's newest three real observations under the shared cap.
|
| 123 |
+
for _ in range(4):
|
| 124 |
+
_, cache, _ = memory(
|
| 125 |
+
torch.randn(2, 8),
|
| 126 |
+
cache,
|
| 127 |
+
source_ids=["long-source", "finished-source"],
|
| 128 |
+
update_cache=[True, False],
|
| 129 |
+
)
|
| 130 |
+
assert cache.sequence_lengths == (3, 3)
|
| 131 |
+
assert cache.valid_mask is not None
|
| 132 |
+
assert cache.valid_mask.sum(dim=-1).tolist() == [3, 3]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def test_all_padding_rows_leave_cache_objects_unchanged():
|
| 136 |
+
memory = StreamingCausalMemory(
|
| 137 |
+
input_dim=8,
|
| 138 |
+
hidden_dim=16,
|
| 139 |
+
num_layers=2,
|
| 140 |
+
num_heads=4,
|
| 141 |
+
dropout=0.0,
|
| 142 |
+
max_cache_tokens=4,
|
| 143 |
+
).eval()
|
| 144 |
+
cache = memory.begin_source(["source-a", "source-b"])
|
| 145 |
+
_, cache, _ = memory(
|
| 146 |
+
torch.randn(2, 8),
|
| 147 |
+
cache,
|
| 148 |
+
source_ids=["source-a", "source-b"],
|
| 149 |
+
update_cache=[True, True],
|
| 150 |
+
)
|
| 151 |
+
before_keys = cache.keys
|
| 152 |
+
before_values = cache.values
|
| 153 |
+
|
| 154 |
+
_, padded_cache, _ = memory(
|
| 155 |
+
torch.randn(2, 8),
|
| 156 |
+
cache,
|
| 157 |
+
source_ids=["source-a", "source-b"],
|
| 158 |
+
update_cache=[False, False],
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
assert padded_cache.sequence_lengths == (1, 1)
|
| 162 |
+
assert all(before is after for before, after in zip(before_keys, padded_cache.keys))
|
| 163 |
+
assert all(before is after for before, after in zip(before_values, padded_cache.values))
|
tests/test_full_duplex_ddp_sync.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import multiprocessing as mp
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.distributed as dist
|
| 8 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 9 |
+
|
| 10 |
+
from psi.trainers.posttrain_full_duplex import (
|
| 11 |
+
_all_reduce_sum_copy,
|
| 12 |
+
average_full_duplex_gradients,
|
| 13 |
+
build_dynamic_source_slot_plan,
|
| 14 |
+
active_source_schedule_offsets,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_metric_collective_does_not_mutate_rank_local_denominator(monkeypatch):
|
| 19 |
+
local_count = torch.tensor(7.0, requires_grad=True)
|
| 20 |
+
|
| 21 |
+
def fake_all_reduce(value, op):
|
| 22 |
+
assert op == dist.ReduceOp.SUM
|
| 23 |
+
value.mul_(8.0)
|
| 24 |
+
|
| 25 |
+
monkeypatch.setattr(dist, "all_reduce", fake_all_reduce)
|
| 26 |
+
global_count = _all_reduce_sum_copy(local_count, distributed=True)
|
| 27 |
+
|
| 28 |
+
assert global_count.item() == 56.0
|
| 29 |
+
assert local_count.item() == 7.0
|
| 30 |
+
assert global_count.data_ptr() != local_count.data_ptr()
|
| 31 |
+
assert global_count.requires_grad is False
|
| 32 |
+
|
| 33 |
+
metric_row = torch.stack(
|
| 34 |
+
[torch.tensor(5.0), local_count.detach()]
|
| 35 |
+
)
|
| 36 |
+
dist.all_reduce(metric_row, op=dist.ReduceOp.SUM)
|
| 37 |
+
assert torch.isclose(
|
| 38 |
+
metric_row[0] / metric_row[1],
|
| 39 |
+
torch.tensor(5.0 / 7.0),
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _ddp_worker(rank: int, init_file: str, result_queue) -> None:
|
| 44 |
+
dist.init_process_group(
|
| 45 |
+
"gloo",
|
| 46 |
+
init_method=f"file://{init_file}",
|
| 47 |
+
rank=rank,
|
| 48 |
+
world_size=2,
|
| 49 |
+
)
|
| 50 |
+
try:
|
| 51 |
+
# Rank 0's local timeline has a gap at 2,3; rank 1 still has real
|
| 52 |
+
# windows there. Both must keep the union and drop only the shared
|
| 53 |
+
# gap 4..19, including when their local timelines have different ends.
|
| 54 |
+
sources = [
|
| 55 |
+
{"source_id": str(i), "steps": [
|
| 56 |
+
{"update_semantic_cache": j == 0}
|
| 57 |
+
for j in range(2 if rank == 0 else 4)
|
| 58 |
+
]} for i in range(2)
|
| 59 |
+
]
|
| 60 |
+
plan = build_dynamic_source_slot_plan(sources, slot_count=1, semantic_cadence=20)
|
| 61 |
+
timeline = torch.tensor(plan.dense_steps)
|
| 62 |
+
dist.all_reduce(timeline, op=dist.ReduceOp.MAX)
|
| 63 |
+
offsets = active_source_schedule_offsets(
|
| 64 |
+
plan, int(timeline), device=torch.device("cpu"), distributed=True,
|
| 65 |
+
)
|
| 66 |
+
assert offsets == [0, 1, 2, 3, 20, 21, 22, 23]
|
| 67 |
+
torch.manual_seed(7)
|
| 68 |
+
model = DistributedDataParallel(
|
| 69 |
+
torch.nn.Linear(4, 2, bias=True),
|
| 70 |
+
broadcast_buffers=False,
|
| 71 |
+
find_unused_parameters=False,
|
| 72 |
+
)
|
| 73 |
+
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
|
| 74 |
+
forwards = 1 if rank == 0 else 3
|
| 75 |
+
local_max = torch.tensor(forwards, dtype=torch.long)
|
| 76 |
+
dist.all_reduce(local_max, op=dist.ReduceOp.MAX)
|
| 77 |
+
loss = None
|
| 78 |
+
with model.no_sync():
|
| 79 |
+
for offset in range(int(local_max.item())):
|
| 80 |
+
if offset >= forwards:
|
| 81 |
+
# This rank is padded while the longer rank continues.
|
| 82 |
+
continue
|
| 83 |
+
inputs = torch.full((2, 4), float(rank + offset + 1))
|
| 84 |
+
value = model(inputs).square().mean() / float(forwards)
|
| 85 |
+
loss = value if loss is None else loss + value
|
| 86 |
+
assert loss is not None
|
| 87 |
+
# One backward after the complete local source, with no graph
|
| 88 |
+
# truncation or optimizer mutation inside it.
|
| 89 |
+
loss.backward()
|
| 90 |
+
average_full_duplex_gradients(
|
| 91 |
+
model.parameters(), world_size=2, bucket_cap_mb=1
|
| 92 |
+
)
|
| 93 |
+
optimizer.step()
|
| 94 |
+
optimizer.zero_grad()
|
| 95 |
+
|
| 96 |
+
flat = torch.cat([parameter.detach().reshape(-1) for parameter in model.parameters()])
|
| 97 |
+
gathered = [torch.empty_like(flat) for _ in range(2)]
|
| 98 |
+
dist.all_gather(gathered, flat)
|
| 99 |
+
if rank == 0:
|
| 100 |
+
result_queue.put(bool(torch.equal(gathered[0], gathered[1])))
|
| 101 |
+
finally:
|
| 102 |
+
dist.destroy_process_group()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def test_different_source_lengths_use_one_complete_source_collective(
|
| 106 |
+
tmp_path: Path,
|
| 107 |
+
):
|
| 108 |
+
init_file = tmp_path / "gloo_init"
|
| 109 |
+
context = mp.get_context("spawn")
|
| 110 |
+
result_queue = context.Queue()
|
| 111 |
+
processes = [
|
| 112 |
+
context.Process(
|
| 113 |
+
target=_ddp_worker,
|
| 114 |
+
args=(rank, str(init_file), result_queue),
|
| 115 |
+
)
|
| 116 |
+
for rank in range(2)
|
| 117 |
+
]
|
| 118 |
+
for process in processes:
|
| 119 |
+
process.start()
|
| 120 |
+
for process in processes:
|
| 121 |
+
# Spawned ranks import the full Transformers/Scipy stack from CPFS
|
| 122 |
+
# before entering Gloo. Cold FUSE directory scans alone can exceed
|
| 123 |
+
# 30 seconds even though the collective completes immediately.
|
| 124 |
+
process.join(timeout=180)
|
| 125 |
+
assert not process.is_alive(), "DDP gradient synchronization deadlocked"
|
| 126 |
+
assert process.exitcode == 0
|
| 127 |
+
assert result_queue.get(timeout=5) is True
|
tests/test_hf_audio_motion_handoff.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU-only contract tests. All generated data remains in pytest temp dirs."""
|
| 2 |
+
import importlib.util
|
| 3 |
+
import io
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
import tarfile
|
| 9 |
+
import wave
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load(name):
|
| 18 |
+
spec = importlib.util.spec_from_file_location(name, ROOT / 'scripts/data' / (name + '.py'))
|
| 19 |
+
module = importlib.util.module_from_spec(spec)
|
| 20 |
+
spec.loader.exec_module(module)
|
| 21 |
+
return module
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
pack = load('package_hf_audio_motion')
|
| 25 |
+
read = load('read_hf_audio_motion')
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def fixture_export(tmp_path):
|
| 29 |
+
motion = tmp_path / 'source/动作/g1/csv_sonic/day/clip'
|
| 30 |
+
motion.mkdir(parents=True)
|
| 31 |
+
for name, width in [('joint_pos.csv', 29), ('body_pos.csv', 3), ('body_quat.csv', 4)]:
|
| 32 |
+
np.savetxt(motion / name, np.arange(3 * width).reshape(3, width), delimiter=',', header=','.join(f'v{i}' for i in range(width)), comments='')
|
| 33 |
+
wav = tmp_path / 'source/speech.wav'
|
| 34 |
+
with wave.open(str(wav), 'wb') as handle:
|
| 35 |
+
handle.setnchannels(1)
|
| 36 |
+
handle.setsampwidth(2)
|
| 37 |
+
handle.setframerate(16000)
|
| 38 |
+
handle.writeframes(b'\0\0' * 100)
|
| 39 |
+
meta = tmp_path / 'source/manifest.jsonl'
|
| 40 |
+
meta.write_text(json.dumps({'text': '停下', 'audio': '/legacy/speech.wav'}, ensure_ascii=False) + '\n')
|
| 41 |
+
dest = tmp_path / 'export'
|
| 42 |
+
records = []
|
| 43 |
+
for name, entries in [('seed_motion', [(motion, 'motion/seed_all/g1/csv_sonic/day/clip')]),
|
| 44 |
+
('seed_tts', [(wav, 'audio/seed_tts/speech.wav'), (meta, 'audio/seed_tts/metadata.jsonl')])]:
|
| 45 |
+
buckets, _ = pack.plan_shards(name, entries, 2)
|
| 46 |
+
for i, bucket in enumerate(buckets):
|
| 47 |
+
if bucket:
|
| 48 |
+
records.append(pack.pack_shard(dest, name, i, bucket))
|
| 49 |
+
pack.write_index(dest, records)
|
| 50 |
+
(dest / 'PATH_MAP.json').write_text(json.dumps({'prefixes': {'/legacy': 'audio/seed_tts'}}))
|
| 51 |
+
return dest, motion, records
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_lossless_offsets_motion_and_original_paths(tmp_path):
|
| 55 |
+
dest, motion, records = fixture_export(tmp_path)
|
| 56 |
+
store = read.ShardStore(dest)
|
| 57 |
+
try:
|
| 58 |
+
assert store.motion36('motion/seed_all/g1/csv_sonic/day/clip').shape == (3, 36)
|
| 59 |
+
assert store.read('/legacy/speech.wav') == (tmp_path / 'source/speech.wav').read_bytes()
|
| 60 |
+
assert list(store.jsonl('audio/seed_tts/metadata.jsonl'))[0]['text'] == '停下'
|
| 61 |
+
for record in records:
|
| 62 |
+
with tarfile.open(dest / record['file']) as tar:
|
| 63 |
+
for member in tar:
|
| 64 |
+
if member.name.endswith('.json') and not member.name.endswith('.payload.json'):
|
| 65 |
+
paths = json.load(tar.extractfile(member))['paths']
|
| 66 |
+
for field, logical in paths.items():
|
| 67 |
+
other = tar.getmember(member.name[:-5] + '.' + field)
|
| 68 |
+
assert store.read(logical) == tar.extractfile(other).read()
|
| 69 |
+
finally:
|
| 70 |
+
store.close()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def test_resume_and_changed_source(tmp_path):
|
| 74 |
+
dest, motion, records = fixture_export(tmp_path)
|
| 75 |
+
buckets, _ = pack.plan_shards('seed_motion', [(motion, 'motion/seed_all/g1/csv_sonic/day/clip')], 2)
|
| 76 |
+
i, bucket = next((i, b) for i, b in enumerate(buckets) if b)
|
| 77 |
+
record = pack.pack_shard(dest, 'seed_motion', i, bucket)
|
| 78 |
+
old_mtime = (dest / record['file']).stat().st_mtime_ns
|
| 79 |
+
assert pack.pack_shard(dest, 'seed_motion', i, bucket) == record
|
| 80 |
+
assert (dest / record['file']).stat().st_mtime_ns == old_mtime
|
| 81 |
+
(motion / 'body_pos.csv').write_text('changed')
|
| 82 |
+
buckets, _ = pack.plan_shards('seed_motion', [(motion, 'motion/seed_all/g1/csv_sonic/day/clip')], 2)
|
| 83 |
+
with pytest.raises(RuntimeError, match='Sources changed'):
|
| 84 |
+
pack.pack_shard(dest, 'seed_motion', i, buckets[i])
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_smplx_extension_same_reader_and_no_pickle(tmp_path):
|
| 88 |
+
dest, _, records = fixture_export(tmp_path)
|
| 89 |
+
path = tmp_path / 'human.npz'
|
| 90 |
+
expected = dict(trans=np.zeros((3, 3)), root_orient=np.zeros((3, 3)),
|
| 91 |
+
pose_body=np.zeros((3, 63)), pose_hand=np.zeros((3, 90)),
|
| 92 |
+
betas=np.zeros(16), sample_times=np.array([0., .033, .066]))
|
| 93 |
+
np.savez(path, **expected)
|
| 94 |
+
logical = 'motion/seed_all/smplx_amass/motions/day/clip.npz'
|
| 95 |
+
buckets, _ = pack.plan_shards('seed_smplx', [(path, logical)], 2)
|
| 96 |
+
records += [pack.pack_shard(dest, 'seed_smplx', i, b) for i, b in enumerate(buckets) if b]
|
| 97 |
+
pack.write_index(dest, records)
|
| 98 |
+
store = read.ShardStore(dest)
|
| 99 |
+
try:
|
| 100 |
+
actual = store.smplx(logical)
|
| 101 |
+
for k, v in expected.items():
|
| 102 |
+
np.testing.assert_array_equal(actual[k], v)
|
| 103 |
+
assert store.motion36('motion/seed_all/g1/csv_sonic/day/clip').shape == (3, 36)
|
| 104 |
+
finally:
|
| 105 |
+
store.close()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_incremental_records_preserve_old_packages_and_skip_progress(tmp_path):
|
| 109 |
+
dest, _, records = fixture_export(tmp_path)
|
| 110 |
+
assert pack.completed_records(dest) == sorted(records, key=lambda row: row['file'])
|
| 111 |
+
source = tmp_path / 'incremental'
|
| 112 |
+
(source / '.progress').mkdir(parents=True)
|
| 113 |
+
(source / '.progress/junk.json').write_text('{}')
|
| 114 |
+
(source / 'asset.wav').write_bytes(b'audio')
|
| 115 |
+
assert [p.name for p in pack.files_under(source)] == ['asset.wav']
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_corrupt_shard_rejected(tmp_path):
|
| 119 |
+
dest, motion, records = fixture_export(tmp_path)
|
| 120 |
+
buckets, _ = pack.plan_shards('seed_motion', [(motion, 'motion/seed_all/g1/csv_sonic/day/clip')], 2)
|
| 121 |
+
i, bucket = next((i, b) for i, b in enumerate(buckets) if b)
|
| 122 |
+
record = pack.pack_shard(dest, 'seed_motion', i, bucket)
|
| 123 |
+
(dest / record['file']).write_bytes(b'broken')
|
| 124 |
+
with pytest.raises(RuntimeError, match='corrupted'):
|
| 125 |
+
pack.pack_shard(dest, 'seed_motion', i, bucket)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_webdataset_compatibility(tmp_path):
|
| 129 |
+
wds = pytest.importorskip('webdataset')
|
| 130 |
+
dest, _, _ = fixture_export(tmp_path)
|
| 131 |
+
samples = list(wds.WebDataset([str(p) for p in sorted((dest / 'shards/seed_motion').glob('*.tar'))], shardshuffle=False))
|
| 132 |
+
assert len(samples) == 1
|
| 133 |
+
assert {'json', 'joint_pos.csv', 'body_pos.csv', 'body_quat.csv'} <= samples[0].keys()
|
| 134 |
+
assert len(json.loads(samples[0]['json'])['paths']) == 3
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def test_audio_decode(tmp_path):
|
| 138 |
+
pytest.importorskip('soundfile')
|
| 139 |
+
dest, _, _ = fixture_export(tmp_path)
|
| 140 |
+
store = read.ShardStore(dest)
|
| 141 |
+
try:
|
| 142 |
+
audio, rate = store.audio('/legacy/speech.wav')
|
| 143 |
+
assert audio.shape == (100, 1) and rate == 16000
|
| 144 |
+
assert np.all(audio == 0)
|
| 145 |
+
finally:
|
| 146 |
+
store.close()
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_symlink_and_unknown_prefix_rejected(tmp_path):
|
| 150 |
+
(tmp_path / 'link').symlink_to('/etc/passwd')
|
| 151 |
+
with pytest.raises(ValueError, match='symlink'):
|
| 152 |
+
list(pack.files_under(tmp_path))
|
| 153 |
+
dest, _, _ = fixture_export(tmp_path)
|
| 154 |
+
store = read.ShardStore(dest)
|
| 155 |
+
try:
|
| 156 |
+
with pytest.raises(KeyError):
|
| 157 |
+
store.read('/unknown/file.wav')
|
| 158 |
+
finally:
|
| 159 |
+
store.close()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_code_comment_secret_export_only_and_executable_rejected(tmp_path):
|
| 163 |
+
source = tmp_path / 'example.py'
|
| 164 |
+
token = 'hf_' + 'x' * 32
|
| 165 |
+
source.write_text('# token=' + token + '\nx=1\n')
|
| 166 |
+
target = tmp_path / 'code.tar.gz'
|
| 167 |
+
pack.write_archive(target, [(source, 'HFD/example.py')])
|
| 168 |
+
with tarfile.open(target) as archive:
|
| 169 |
+
exported = archive.extractfile('HFD/example.py').read()
|
| 170 |
+
assert token.encode() not in exported
|
| 171 |
+
assert token in source.read_text()
|
| 172 |
+
source.write_text('token="' + token + '"')
|
| 173 |
+
with pytest.raises(ValueError, match='credential'):
|
| 174 |
+
pack.safe_code_bytes(source)
|
| 175 |
+
source.write_text('task="task-hesitation-pause-v2-preroll"')
|
| 176 |
+
assert pack.safe_code_bytes(source) == source.read_bytes()
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test_full_cli_export_and_resume(tmp_path):
|
| 180 |
+
_, motion, _ = fixture_export(tmp_path)
|
| 181 |
+
motion_root = motion.parents[3]
|
| 182 |
+
(motion_root / 'metadata').mkdir()
|
| 183 |
+
(motion_root / 'metadata/seed_metadata_v004.csv').write_text('filename\nclip\n')
|
| 184 |
+
tts = tmp_path / 'tts'
|
| 185 |
+
(tts / 'seed_audio/000000').mkdir(parents=True)
|
| 186 |
+
(tts / 'seed_audio/000000/voice.wav').write_bytes((tmp_path / 'source/speech.wav').read_bytes())
|
| 187 |
+
(tts / 'metadata.jsonl').write_text('{"filename":"clip"}\n')
|
| 188 |
+
data = tmp_path / 'data'
|
| 189 |
+
for package in pack.PACKAGES:
|
| 190 |
+
(data / package).mkdir(parents=True)
|
| 191 |
+
(data / package / 'manifest.jsonl').write_text('{}\n')
|
| 192 |
+
output = tmp_path / 'cli_export'
|
| 193 |
+
cmd = [sys.executable, str(ROOT / 'scripts/data/package_hf_audio_motion.py'), '--part', 'data', '--build', '--output', str(output), '--motion-root', str(motion_root), '--tts-root', str(tts), '--data-root', str(data), '--shards', '2', '--workers', '2']
|
| 194 |
+
first = subprocess.run(cmd, capture_output=True, text=True)
|
| 195 |
+
assert first.returncode == 0, first.stderr
|
| 196 |
+
second = subprocess.run(cmd, capture_output=True, text=True)
|
| 197 |
+
assert second.returncode == 0, second.stderr
|
| 198 |
+
dest = output / 'hfd_data'
|
| 199 |
+
for line in (dest / 'SHA256SUMS').read_text().splitlines():
|
| 200 |
+
sha, file = line.split(' ', 1)
|
| 201 |
+
assert pack.digest(dest / file) == sha
|
| 202 |
+
# Removing the only file in a package must not silently upload its stale tar.
|
| 203 |
+
(data / pack.PACKAGES[-1] / 'manifest.jsonl').unlink()
|
| 204 |
+
third = subprocess.run(cmd, capture_output=True, text=True)
|
| 205 |
+
assert third.returncode != 0 and 'inventory changed' in third.stderr
|
tests/test_hf_export_dashboard.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
from collections import deque
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
spec = importlib.util.spec_from_file_location('dashboard', Path(__file__).resolve().parents[1] / 'scripts/data/hf_export_dashboard.py')
|
| 7 |
+
m = importlib.util.module_from_spec(spec)
|
| 8 |
+
spec.loader.exec_module(m)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_rate_needs_elapsed_time_and_no_negative_speed():
|
| 12 |
+
values = deque()
|
| 13 |
+
assert m.rate(values, 0, 10) is None
|
| 14 |
+
assert m.rate(values, 10, 20) is None
|
| 15 |
+
assert m.rate(values, 20, 50) == 2
|
| 16 |
+
assert m.rate(values, 30, 0) == 0
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_waiting_period_not_counted_as_packing_time():
|
| 20 |
+
values = deque([(0, 0), (100, 0)])
|
| 21 |
+
assert m.rate(values, 115, 150) is None
|
| 22 |
+
assert m.rate(values, 130, 300) == 10
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_metadata_only_scan_cursor(tmp_path, monkeypatch):
|
| 26 |
+
metadata = tmp_path / 'metadata.csv'
|
| 27 |
+
metadata.write_text('move_g1_path\ng1/csv/240101/a.csv\ng1/csv/240101/b.csv\ng1/csv/240101/b.csv\n')
|
| 28 |
+
obj = m.Observer(tmp_path / 'export', tmp_path / 'state', metadata)
|
| 29 |
+
obj.keys_set = set(obj.keys)
|
| 30 |
+
monkeypatch.setattr(m, 'processes', lambda _: [{'kind': 'pack', 'source_cursor': '240101/a'}])
|
| 31 |
+
obj.sample()
|
| 32 |
+
assert obj.latest['scan']['estimated_completed_motions'] == 1
|
| 33 |
+
assert obj.latest['scan']['total_motions'] == 2
|
| 34 |
+
assert obj.latest['phase'] == '扫描动作文件'
|
| 35 |
+
assert not (tmp_path / 'export').exists() # Observer never creates/modifies export tree.
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_partial_not_counted_as_complete(tmp_path, monkeypatch):
|
| 39 |
+
metadata = tmp_path / 'metadata.csv'
|
| 40 |
+
metadata.write_text('move_g1_path\ng1/csv/day/clip.csv\n')
|
| 41 |
+
export = tmp_path / 'export'
|
| 42 |
+
shard = export / 'hfd_data/shards/seed_motion/00000.tar.partial'
|
| 43 |
+
shard.parent.mkdir(parents=True)
|
| 44 |
+
shard.write_bytes(b'hello')
|
| 45 |
+
obj = m.Observer(export, tmp_path / 'state', metadata)
|
| 46 |
+
obj.keys_set = set(obj.keys)
|
| 47 |
+
monkeypatch.setattr(m, 'processes', lambda _: [])
|
| 48 |
+
obj.sample()
|
| 49 |
+
row = obj.latest['packages'][0]
|
| 50 |
+
assert row['written_bytes'] == 5 and row['done'] == 0
|
| 51 |
+
assert row['eta_seconds'] is None and row['bytes_per_second'] is None
|
| 52 |
+
assert obj.latest['local_ready'] is False
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_completed_markers_and_safe_relative_api(tmp_path, monkeypatch):
|
| 56 |
+
metadata = tmp_path / 'metadata.csv'
|
| 57 |
+
metadata.write_text('move_g1_path\n')
|
| 58 |
+
export = tmp_path / 'export'
|
| 59 |
+
marker = export / 'hfd_data/.build/hfd_control_commands_v1/00000.done.json'
|
| 60 |
+
marker.parent.mkdir(parents=True)
|
| 61 |
+
marker.write_text(json.dumps({'archive_bytes': 100, 'files': 4}))
|
| 62 |
+
obj = m.Observer(export, tmp_path / 'state', metadata)
|
| 63 |
+
obj.keys_set = set()
|
| 64 |
+
monkeypatch.setattr(m, 'processes', lambda _: [])
|
| 65 |
+
obj.sample()
|
| 66 |
+
row = next(r for r in obj.latest['packages'] if r['name'] == 'hfd_control_commands_v1')
|
| 67 |
+
assert row['done'] == 1 and row['files_done'] == 4
|
| 68 |
+
assert "fetch('api/status'" in m.HTML
|
| 69 |
+
assert 'textContent' in m.HTML
|
tests/test_hfd_backchannel_inventory.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
SCRIPT_DIR = Path(__file__).resolve().parents[1] / "scripts" / "data"
|
| 6 |
+
if str(SCRIPT_DIR) not in sys.path:
|
| 7 |
+
sys.path.insert(0, str(SCRIPT_DIR))
|
| 8 |
+
|
| 9 |
+
from generate_hfd_backchannels import DEFAULT_OUTPUT, PHRASES # noqa: E402
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_backchannel_inventory_excludes_sentence_like_feedback():
|
| 13 |
+
phrase_ids = {row["phrase_id"] for row in PHRASES}
|
| 14 |
+
assert phrase_ids.isdisjoint(
|
| 15 |
+
{"bc_cont_09", "bc_cont_12", "bc_assess_05"}
|
| 16 |
+
)
|
| 17 |
+
assert len(PHRASES) == 15
|
| 18 |
+
assert DEFAULT_OUTPUT.name == "hfd_backchannel_commands_v2_short"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_backchannel_inventory_keeps_both_functions_in_each_split():
|
| 22 |
+
categories = {
|
| 23 |
+
split: {
|
| 24 |
+
row["category"] for row in PHRASES if row["split"] == split
|
| 25 |
+
}
|
| 26 |
+
for split in ("train", "val")
|
| 27 |
+
}
|
| 28 |
+
assert categories == {
|
| 29 |
+
"train": {"continuer", "assessment"},
|
| 30 |
+
"val": {"continuer", "assessment"},
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_backchannel_inventory_keeps_train_and_val_meanings_disjoint():
|
| 35 |
+
train_ids = {row["phrase_id"] for row in PHRASES if row["split"] == "train"}
|
| 36 |
+
val_ids = {row["phrase_id"] for row in PHRASES if row["split"] == "val"}
|
| 37 |
+
assert train_ids
|
| 38 |
+
assert val_ids
|
| 39 |
+
assert train_ids.isdisjoint(val_ids)
|
tests/test_hfd_continuation.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
import math
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
spec=importlib.util.spec_from_file_location('continuation',Path(__file__).parents[1]/'scripts/prepare_hfd_continuation.py')
|
| 7 |
+
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_lr_continuity_floor_and_clock():
|
| 11 |
+
from transformers.optimization import get_scheduler
|
| 12 |
+
import torch
|
| 13 |
+
base=[8e-5,2e-6,8e-5,5e-5];step=1005983;old_total=1250000;warmup=12500
|
| 14 |
+
f=.05+.95*.5*(1+math.cos(math.pi*(step-warmup)/(old_total-warmup)))
|
| 15 |
+
saved=dict(base_lrs=base,_last_lr=[b*f for b in base],last_epoch=step*8,_step_count=step*8+1,
|
| 16 |
+
lr_lambdas=[{} for _ in base])
|
| 17 |
+
new,rate=module.extended_schedule(saved,step=step,old_world=8,new_world=4,
|
| 18 |
+
warmup=warmup,total=1800000,floor=.05)
|
| 19 |
+
assert saved['last_epoch']==step*8
|
| 20 |
+
assert new['last_epoch']==step*4
|
| 21 |
+
params=[torch.nn.Parameter(torch.ones(1)) for _ in base]
|
| 22 |
+
opt=torch.optim.AdamW([dict(params=[p],lr=b) for p,b in zip(params,new['base_lrs'])])
|
| 23 |
+
scheduler=get_scheduler('cosine_with_min_lr',opt,num_warmup_steps=warmup*4,
|
| 24 |
+
num_training_steps=1800000*4,scheduler_specific_kwargs={'min_lr_rate':rate})
|
| 25 |
+
scheduler.load_state_dict(new)
|
| 26 |
+
for i,b in enumerate(new['base_lrs']):
|
| 27 |
+
fn=scheduler.lr_lambdas[i]
|
| 28 |
+
assert b*fn(step*4)==pytest.approx(saved['_last_lr'][i],rel=1e-12)
|
| 29 |
+
assert b*fn(1800000*4)==pytest.approx(base[i]*.05,rel=1e-12)
|
| 30 |
+
assert b*fn(step*4+4)<=saved['_last_lr'][i]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_reject_wrong_clock():
|
| 34 |
+
with pytest.raises(ValueError,match='clock'):
|
| 35 |
+
module.extended_schedule({'last_epoch':10},step=100,old_world=8,new_world=4,
|
| 36 |
+
warmup=0,total=1000,floor=.05)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_reject_unsupported_world():
|
| 40 |
+
with pytest.raises(ValueError,match='non-increasing-world'):
|
| 41 |
+
module.extended_schedule({},step=100,old_world=4,new_world=8,warmup=0,total=1000,floor=.05)
|
tests/test_hfd_storage_paths.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
from psi.data.seed.storage_paths import relocate_hfd_storage_path
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_relocates_legacy_hfd_storage_prefixes() -> None:
|
| 7 |
+
root = (
|
| 8 |
+
"/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/"
|
| 9 |
+
"user_workspace"
|
| 10 |
+
)
|
| 11 |
+
assert relocate_hfd_storage_path(
|
| 12 |
+
"/cpfs01/videogen/yetinghong/datasets/hfd_control_commands_v1/"
|
| 13 |
+
"manifest.jsonl"
|
| 14 |
+
) == Path(
|
| 15 |
+
f"{root}/yetinghong/videogen/hfd_control_commands_v1/manifest.jsonl"
|
| 16 |
+
)
|
| 17 |
+
assert relocate_hfd_storage_path(
|
| 18 |
+
"/cpfs01/users/buwendong/code/qwen3-tts/metadata.jsonl"
|
| 19 |
+
) == Path(f"{root}/buwendong/user/code/qwen3-tts/metadata.jsonl")
|
| 20 |
+
assert relocate_hfd_storage_path(
|
| 21 |
+
"/cpfs01/users/yetinghong/code/HFD/run_config.json"
|
| 22 |
+
) == Path(f"{root}/yetinghong/code/HFD/run_config.json")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_relocates_embedded_legacy_tts_waveform_path() -> None:
|
| 26 |
+
assert relocate_hfd_storage_path(
|
| 27 |
+
"/cpfs01/users/buwendong/code/qwen3-tts/seed_audio/"
|
| 28 |
+
"003782/female_02_en.wav"
|
| 29 |
+
) == Path(
|
| 30 |
+
"/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/"
|
| 31 |
+
"user_workspace/buwendong/user/code/qwen3-tts/seed_audio/"
|
| 32 |
+
"003782/female_02_en.wav"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_keeps_qwen_and_relative_paths_unchanged() -> None:
|
| 37 |
+
qwen = Path(
|
| 38 |
+
"/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/"
|
| 39 |
+
"team_workspace/public_ckpt/Qwen/Qwen2.5-Omni-3B"
|
| 40 |
+
)
|
| 41 |
+
relative = Path("manifests/background_sessions.jsonl")
|
| 42 |
+
migrated = Path(
|
| 43 |
+
"/cpfs01/thscc/sharestorage/AIGC-06-01/Hithink_VideoGen_Group/"
|
| 44 |
+
"user_workspace/buwendong/user/code/qwen3-tts/metadata.jsonl"
|
| 45 |
+
)
|
| 46 |
+
assert relocate_hfd_storage_path(qwen) == qwen
|
| 47 |
+
assert relocate_hfd_storage_path(relative) == relative
|
| 48 |
+
assert relocate_hfd_storage_path(migrated) == migrated
|
tests/test_hfd_training_recipe.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Launcher-only regressions; no model, training run, network or GPU allocation."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import subprocess
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from psi.hfd_training_launcher import (
|
| 11 |
+
CONFIG_MODULE, parse_options, resolve, runtime_environment, to_args,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_offline_entry_uses_training_data_config_without_launch(monkeypatch):
|
| 18 |
+
import scripts.launch_hfd_training as launcher
|
| 19 |
+
import scripts.data.prepare_full_duplex_indexes as prepare
|
| 20 |
+
import sys
|
| 21 |
+
called = []
|
| 22 |
+
monkeypatch.setattr(sys, "argv", ["launch_hfd_training.py", "--prepare-data"])
|
| 23 |
+
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1,2")
|
| 24 |
+
monkeypatch.setattr(prepare, "warm_indexes", lambda config: called.append(config))
|
| 25 |
+
monkeypatch.setattr(os, "execvpe", lambda *args: pytest.fail("Offline preparation launched training"))
|
| 26 |
+
launcher.main()
|
| 27 |
+
assert os.environ["CUDA_VISIBLE_DEVICES"] == ""
|
| 28 |
+
assert len(called) == 1
|
| 29 |
+
assert called[0].stationary_listen_hold
|
| 30 |
+
assert called[0].multimodal_overlay_qa_ratio == .75
|
| 31 |
+
assert called[0].command_interruption_session_variants == 2
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_new_session_range_and_explicit_legacy_override():
|
| 35 |
+
options, _ = resolve(ROOT, {})
|
| 36 |
+
assert options["data.session-min-turns"] == 1
|
| 37 |
+
assert options["data.session-max-turns"] == 4
|
| 38 |
+
legacy, _ = resolve(ROOT, {"HFD_SESSION_MIN_TURNS": "2"})
|
| 39 |
+
assert legacy["data.session-min-turns"] == 2
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_eval_cpu_prefetch_default_and_opt_out():
|
| 43 |
+
options, _ = resolve(ROOT, {})
|
| 44 |
+
assert options["train.val-num-workers"] == 2
|
| 45 |
+
serial, _ = resolve(ROOT, {"HFD_VAL_NUM_WORKERS": "0"})
|
| 46 |
+
assert serial["train.val-num-workers"] == 0
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_resolved_config_matches_pre_refactor_baseline():
|
| 50 |
+
import tyro
|
| 51 |
+
from psi.config.train.posttrain_full_duplex_audio_command_psi0_config import DynamicLaunchConfig
|
| 52 |
+
options, _ = resolve(ROOT, {})
|
| 53 |
+
config = tyro.cli(DynamicLaunchConfig,
|
| 54 |
+
config=(tyro.conf.ConsolidateSubcommandArgs,),
|
| 55 |
+
args=to_args(options)[1:]).model_dump(mode="json")
|
| 56 |
+
config["timestamp"] = "STAMP"
|
| 57 |
+
config["train"]["output_dir"] = "RUNS"
|
| 58 |
+
assert config['train']['max_training_steps'] == 1500000
|
| 59 |
+
config['train']['max_training_steps'] = 1250000
|
| 60 |
+
assert config['train']['warmup_steps'] == 15000
|
| 61 |
+
config['train']['warmup_steps'] = 12500
|
| 62 |
+
for key in ('third_party_root', 'third_party_train_selection', 'third_party_val_selection'):
|
| 63 |
+
assert config['data'].pop(key)
|
| 64 |
+
# A staged checkout may share the original environment; normalize this
|
| 65 |
+
# unused DDP path before comparing the otherwise unchanged recipe.
|
| 66 |
+
config["train"]["deepspeed_config"] = str((ROOT/'.venv-psi').resolve().parent / 'src/InternVLA/config/deepseeds/zero3.json')
|
| 67 |
+
# New recipe changes are explicit; all unrelated settings stay identical.
|
| 68 |
+
assert config["model"].pop("interaction_architecture") == "a1_c_deferred"
|
| 69 |
+
assert config["model"].pop("action_mask_aware_positions") is True
|
| 70 |
+
assert config["model"].pop("action_input_projection_fp32") is True
|
| 71 |
+
assert config["model"].pop("action_representation") == "root40_v1"
|
| 72 |
+
assert config["data"]["transform"]["repack"].pop("root40_actions") is True
|
| 73 |
+
for key in ("action_dim", "odim"):
|
| 74 |
+
assert config["model"][key] == 40
|
| 75 |
+
config["model"][key] = 39
|
| 76 |
+
for section in ("repack", "field"):
|
| 77 |
+
for key in ("pad_action_dim", "pad_state_dim"):
|
| 78 |
+
assert config["data"]["transform"][section][key] == 40
|
| 79 |
+
config["data"]["transform"][section][key] = 39
|
| 80 |
+
config["data"]["transform"]["field"]["action_norm_type"] = "bounds_q99"
|
| 81 |
+
config["data"]["transform"]["field"]["stat_path"] = "assets/stats/seed_all_g1_motion39_textop_stats.json"
|
| 82 |
+
from psi.config.transform import ActionStateTransform
|
| 83 |
+
config["data"]["transform"]["field"] = ActionStateTransform.model_validate(
|
| 84 |
+
config["data"]["transform"]["field"]).model_dump(mode="json")
|
| 85 |
+
assert config["train"].pop("swa_generated_history_probability") == 0.0
|
| 86 |
+
assert config["train"].pop("swa_generated_history_warmup_steps") == 12500
|
| 87 |
+
assert config["train"].pop("swa_generated_history_ramp_steps") == 37500
|
| 88 |
+
assert config["model"].pop("swa_reply_detach_body") is True
|
| 89 |
+
assert config["data"].pop("stationary_listen_hold") is True
|
| 90 |
+
manifests=config["data"].pop("multimodal_overlay_manifests")
|
| 91 |
+
assert len(manifests)==1 and manifests[0].endswith('/hfd_visual_dataset')
|
| 92 |
+
assert config["data"].pop("multimodal_overlay_qa_ratio") == .75
|
| 93 |
+
assert config["data"].pop("multimodal_overlay_visual_only_ratio") == .10
|
| 94 |
+
assert config["data"].pop("multimodal_overlay_strict_voice") is True
|
| 95 |
+
assert config["data"].pop("multimodal_visual_input_mode") == "cached"
|
| 96 |
+
assert config["data"]["session_min_turns"] == 1
|
| 97 |
+
config["data"]["session_min_turns"] = 2 # Historical recipe snapshot.
|
| 98 |
+
assert config["data"]["command_interruption_session_variants"] == 2
|
| 99 |
+
config["data"]["command_interruption_session_variants"] = 1 # Historical pool size.
|
| 100 |
+
assert config["train"]["val_num_workers"] == 2
|
| 101 |
+
config["train"]["val_num_workers"] = 0 # Historical synchronous eval.
|
| 102 |
+
# The working production recipe was already B16 before native vision.
|
| 103 |
+
for field in ('train_batch_size', 'target_effective_sources_per_gpu'):
|
| 104 |
+
assert config['train'][field] == 16
|
| 105 |
+
config['train'][field] = 72
|
| 106 |
+
# Independent-QA production recipe snapshot (6382ed6), including implicit
|
| 107 |
+
# defaults. The older snapshot predated the separate QA configuration.
|
| 108 |
+
assert hashlib.sha256(json.dumps(config, sort_keys=True).encode()).hexdigest() == (
|
| 109 |
+
"3adbf2580a40859d81951d0c8d943657c90feb492b8860dd11db0ba2a3dd291a"
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def write_resume_fixture(tmp_path):
|
| 114 |
+
saved, _ = resolve(ROOT, {
|
| 115 |
+
"HFD_TRAIN_BATCH_SIZE": "48", "HFD_WARMUP_STEPS": "0",
|
| 116 |
+
"HFD_MAX_TRAINING_STEPS": "200000", "HFD_SWA_SOURCE_PLAN": "/fixture/a plan.json",
|
| 117 |
+
"HFD_DYNAMIC_SOURCE_REFILL": "0", "HFD_CONTROL_HEAD_LR_MULTIPLIER": "1",
|
| 118 |
+
"HFD_RUN_TIMESTAMP": "2609181234-old", "HFD_INTERRUPTION_TASK_SESSION_RATIO": ".2",
|
| 119 |
+
})
|
| 120 |
+
checkpoint = tmp_path / "checkpoints" / "ckpt_100"
|
| 121 |
+
checkpoint.mkdir(parents=True)
|
| 122 |
+
(tmp_path / "run_config.json").write_text(json.dumps({
|
| 123 |
+
"train": {"stage": 0, "full_duplex_semantics_version": 24}}))
|
| 124 |
+
# Match scripts/train.py: each flag and all its list values on ONE line.
|
| 125 |
+
args = to_args(saved)
|
| 126 |
+
lines = ["scripts/train.py"]
|
| 127 |
+
for arg in args:
|
| 128 |
+
if arg.startswith("--") or arg == CONFIG_MODULE:
|
| 129 |
+
lines.append(arg)
|
| 130 |
+
else:
|
| 131 |
+
lines[-1] += " " + arg
|
| 132 |
+
(tmp_path / "argv.txt").write_text("\n".join(lines) + "\n")
|
| 133 |
+
return checkpoint, saved
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def test_full_state_resume_preserves_entire_saved_recipe(tmp_path):
|
| 137 |
+
checkpoint, saved = write_resume_fixture(tmp_path)
|
| 138 |
+
env = {"HFD_RESUME_LOAD_FULL_STATE": "1", "HFD_RESUME_FROM_CHECKPOINT": str(checkpoint),
|
| 139 |
+
"HFD_WANDB_RESUME": "must", "HFD_WANDB_ID": "original-id"}
|
| 140 |
+
resumed, _ = resolve(ROOT, env)
|
| 141 |
+
operational = {"train.resume-load-full-state", "train.resume-from-checkpoint", "wandb.resume", "wandb.id"}
|
| 142 |
+
assert {k: v for k, v in resumed.items() if k not in operational} == {
|
| 143 |
+
k: v for k, v in saved.items() if k not in operational}
|
| 144 |
+
assert resumed["train.resume-load-full-state"]
|
| 145 |
+
assert resumed["wandb.resume"] == "must"
|
| 146 |
+
assert resumed["wandb.id"] == "original-id"
|
| 147 |
+
assert resumed["train.lr-scheduler-kwargs.betas"] == (.9, .999)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def test_legacy_resume_does_not_inherit_new_position_setting(tmp_path):
|
| 151 |
+
checkpoint, _ = write_resume_fixture(tmp_path)
|
| 152 |
+
path = checkpoint.parent.parent / "argv.txt"
|
| 153 |
+
lines = path.read_text().splitlines()
|
| 154 |
+
path.write_text("\n".join(x for x in lines if not x.startswith((
|
| 155 |
+
"--model.action-mask-aware-positions",
|
| 156 |
+
))) + "\n")
|
| 157 |
+
resumed, _ = resolve(ROOT, {
|
| 158 |
+
"HFD_RESUME_LOAD_FULL_STATE": "1",
|
| 159 |
+
"HFD_RESUME_FROM_CHECKPOINT": str(checkpoint),
|
| 160 |
+
})
|
| 161 |
+
assert "model.action-mask-aware-positions" not in resumed
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@pytest.mark.parametrize("mode", ["enabled", "disabled"])
|
| 165 |
+
def test_listen_hold_applies_to_new_audio_and_joint_recipes(mode):
|
| 166 |
+
options, _ = resolve(ROOT, {"HFD_SWA_DATA_MODE": mode})
|
| 167 |
+
assert options["data.stationary-listen-hold"] is True
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def test_legacy_resume_does_not_inherit_new_listen_targets(tmp_path):
|
| 171 |
+
checkpoint, _ = write_resume_fixture(tmp_path)
|
| 172 |
+
path = checkpoint.parent.parent / "argv.txt"
|
| 173 |
+
path.write_text("\n".join(line for line in path.read_text().splitlines()
|
| 174 |
+
if not line.startswith("--data.stationary-listen-hold")) + "\n")
|
| 175 |
+
resumed, _ = resolve(ROOT, {
|
| 176 |
+
"HFD_RESUME_LOAD_FULL_STATE": "1",
|
| 177 |
+
"HFD_RESUME_FROM_CHECKPOINT": str(checkpoint),
|
| 178 |
+
})
|
| 179 |
+
assert "data.stationary-listen-hold" not in resumed
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def test_removed_history_not_in_recipe_and_nonzero_request_is_rejected():
|
| 183 |
+
options, _ = resolve(ROOT, {})
|
| 184 |
+
assert options["train.swa-generated-history-probability"] == 0.0
|
| 185 |
+
with pytest.raises(ValueError, match="generated-history training was removed"):
|
| 186 |
+
resolve(ROOT, {"HFD_SWA_GENERATED_HISTORY_PROBABILITY": ".25"})
|
| 187 |
+
with pytest.raises(ValueError, match="generated-history training was removed"):
|
| 188 |
+
resolve(ROOT, {}, ["--train.swa-generated-history-probability=.25"])
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_shell_does_not_overwrite_resume_batch_warmup_or_task_mix(tmp_path):
|
| 192 |
+
checkpoint, saved = write_resume_fixture(tmp_path)
|
| 193 |
+
env = {k: v for k, v in os.environ.items() if not k.startswith("HFD_")}
|
| 194 |
+
env.update(HFD_ENV_FILE="/nonexistent", HFD_CONFIG_ONLY="1",
|
| 195 |
+
HFD_RESUME_LOAD_FULL_STATE="1", HFD_RESUME_FROM_CHECKPOINT=str(checkpoint))
|
| 196 |
+
result = subprocess.run(["bash", str(ROOT / "posttrain-full-duplex-audio-command.sh")],
|
| 197 |
+
cwd=tmp_path, env=env, text=True, capture_output=True, check=True)
|
| 198 |
+
actual = json.loads(result.stdout)
|
| 199 |
+
for key in ("train.train-batch-size", "train.warmup-steps", "train.max-training-steps",
|
| 200 |
+
"train.dynamic-source-refill", "data.swa-source-plan",
|
| 201 |
+
"data.interruption-task-session-ratio", "timestamp"):
|
| 202 |
+
assert actual[key] == saved[key]
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def test_paths_with_spaces_and_bool_cli_override_survive_roundtrip():
|
| 206 |
+
o, _ = resolve(ROOT, {"HFD_OUTPUT_DIR": "/tmp/my_test run", "HFD_RUN_TIMESTAMP": "2609181234-trial"},
|
| 207 |
+
["--train.no-dynamic-source-refill", "--train.train_batch_size=96"])
|
| 208 |
+
roundtrip = parse_options(to_args(o)[1:])
|
| 209 |
+
assert roundtrip["train.output-dir"] == "/tmp/my_test run"
|
| 210 |
+
assert roundtrip["timestamp"] == "2609181234-trial"
|
| 211 |
+
assert roundtrip["train.train-batch-size"] == roundtrip["train.target-effective-sources-per-gpu"] == 96
|
| 212 |
+
assert roundtrip["train.dynamic-source-refill"] is False
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def test_env_overrides_and_derived_paths_prefetch_and_warmup():
|
| 216 |
+
o, mode = resolve(ROOT, {"HFD_TRAIN_BATCH_SIZE": "96", "HFD_MAX_TRAINING_STEPS": "10000",
|
| 217 |
+
"HFD_CONTINUOUS_DATA_ROOT": "/fixture/audio", "HFD_MOTION_ROOT": "/fixture/motion",
|
| 218 |
+
"HFD_SWA_DATA_MODE": "disabled", "HFD_NUM_WORKERS": "12",
|
| 219 |
+
"HFD_REPORT_TO": "none"})
|
| 220 |
+
assert o["train.target-effective-sources-per-gpu"] == 96
|
| 221 |
+
assert o["train.warmup-steps"] == 100
|
| 222 |
+
assert o["data.background-assignment-path"] == "/fixture/audio/manifests/source_background_assignments.jsonl"
|
| 223 |
+
assert o["data.motion-metadata-csv"] == "/fixture/motion/metadata/seed_metadata_v004.csv"
|
| 224 |
+
assert o["log.report-to"] is None
|
| 225 |
+
assert mode == "disabled" and not o["model.swa-visual-qa-enabled"]
|
| 226 |
+
env = runtime_environment(o, {"CUDA_VISIBLE_DEVICES": "GPU-xyz"})
|
| 227 |
+
assert env["CUDA_VISIBLE_DEVICES"] == "GPU-xyz"
|
| 228 |
+
assert env["PSI_DATALOADER_PREFETCH_FACTOR"] == "32"
|
| 229 |
+
assert env["HFD_CONTINUOUS_DATA_CONTRACT_PATH"] == "/fixture/audio/reports/production_complete.json"
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@pytest.mark.parametrize("env", [
|
| 233 |
+
{"HFD_FULL_DUPLEX_SEMANTICS_VERSION": "12"}, {"HFD_STAGE": "1"},
|
| 234 |
+
{"HFD_STAGE2_SOURCE_BATCH_SIZE": "16"}, {"HFD_RESUME_LOAD_FULL_STATE": "1"},
|
| 235 |
+
{"HFD_EFFECTIVE_SOURCES_PER_GPU": "99"}, {"HFD_TRAIN_BATCH_SIZE": "0"},
|
| 236 |
+
{"HFD_WARMUP_STEPS": "-1"}, {"HFD_QWEN_KV_GRADIENT_HORIZON": "2"},
|
| 237 |
+
{"HFD_SWA_DATA_MODE": "auto"}, {"HFD_SWA_TRAIN_REPEAT": "6"},
|
| 238 |
+
{"HFD_MANAGE_GPU_MONITOR": "yes"}, {"HFD_WANDB_RESUME": "must"},
|
| 239 |
+
{"HFD_INTERRUPTION_TASK_SESSION_RATIO": ".9"},
|
| 240 |
+
{"HFD_BACKCHANNEL_TASK_SESSION_RATIO": "nan"}, {"HFD_HESITATION_TASK_WINDOW_RATIO": ".99"},
|
| 241 |
+
{"HFD_SAFE_HOLD_VARIANTS": "1"}, {"HFD_CONTROL_POST_IDLE_MAX_STEPS": "100"},
|
| 242 |
+
{"HFD_STOP_RELEASE_LOSS_WEIGHT": "0"}, {"HFD_SESSION_VOICE_VARIANTS": "1"},
|
| 243 |
+
{"HFD_NUM_WORKERS": "-1"}, {"HFD_ALLOW_V11_WEIGHTS_INIT": "1"},
|
| 244 |
+
{"HFD_RESUME_LOAD_FULL_STATE": "true"}, {"HFD_MANAGE_GPU_MONITOR": "true"},
|
| 245 |
+
])
|
| 246 |
+
def test_bad_settings_fail_before_torchrun(env):
|
| 247 |
+
with pytest.raises(ValueError):
|
| 248 |
+
resolve(ROOT, env)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def test_cli_cannot_bypass_saved_recipe_loading_for_full_resume():
|
| 252 |
+
with pytest.raises(ValueError, match="Use HFD_RESUME"):
|
| 253 |
+
resolve(ROOT, {}, ["--train.resume-load-full-state", "--train.resume-from-checkpoint=/tmp/old"])
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def test_cpu_config_print_does_not_require_data_or_gpu(tmp_path):
|
| 257 |
+
env = {k: v for k, v in os.environ.items() if not k.startswith("HFD_")}
|
| 258 |
+
env.update(HFD_ENV_FILE="/nonexistent", HFD_CONTINUOUS_DATA_ROOT="/missing",
|
| 259 |
+
HFD_SWA_SOURCE_PLAN="/missing.json", CUDA_VISIBLE_DEVICES="")
|
| 260 |
+
result = subprocess.run(["bash", str(ROOT / "posttrain-full-duplex-audio-command.sh"), "--print-config"],
|
| 261 |
+
cwd=tmp_path, env=env, capture_output=True, text=True, check=True)
|
| 262 |
+
assert json.loads(result.stdout)["data.swa-visual-qa-enabled"] is True
|
| 263 |
+
assert not list(tmp_path.iterdir())
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
@pytest.mark.parametrize("monitor", ["0", "1"])
|
| 267 |
+
def test_launch_handoff_uses_allocated_gpus_and_all_admission_checks(monkeypatch, monitor):
|
| 268 |
+
import importlib.util
|
| 269 |
+
import sys
|
| 270 |
+
import torch
|
| 271 |
+
import psi.hfd_training_preflight as preflight
|
| 272 |
+
spec = importlib.util.spec_from_file_location("hfd_launch_test", ROOT / "scripts/launch_hfd_training.py")
|
| 273 |
+
module = importlib.util.module_from_spec(spec)
|
| 274 |
+
spec.loader.exec_module(module)
|
| 275 |
+
for key in list(os.environ):
|
| 276 |
+
if key.startswith("HFD_"):
|
| 277 |
+
monkeypatch.delenv(key)
|
| 278 |
+
monkeypatch.setenv("HFD_REPORT_TO", "None")
|
| 279 |
+
monkeypatch.setenv("HFD_MANAGE_GPU_MONITOR", monitor)
|
| 280 |
+
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "GPU-a,GPU-b")
|
| 281 |
+
monkeypatch.setattr(sys, "argv", [str(ROOT / "scripts/launch_hfd_training.py")])
|
| 282 |
+
monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
|
| 283 |
+
checks = []
|
| 284 |
+
monkeypatch.setattr(preflight, "validate_inputs", lambda *args: checks.append("data"))
|
| 285 |
+
monkeypatch.setattr(preflight, "validate_wandb", lambda *args: checks.append("wandb"))
|
| 286 |
+
launched = []
|
| 287 |
+
monkeypatch.setattr(os, "execvpe", lambda *args: launched.append(args))
|
| 288 |
+
monkeypatch.chdir(ROOT)
|
| 289 |
+
module.main()
|
| 290 |
+
assert checks == ["data", "wandb"]
|
| 291 |
+
executable, command, env = launched[0]
|
| 292 |
+
assert "--nproc_per_node=2" in command
|
| 293 |
+
assert "--train.train-batch-size=16" in command
|
| 294 |
+
assert "--data.swa-visual-qa-enabled" in command
|
| 295 |
+
assert env["CUDA_VISIBLE_DEVICES"] == "GPU-a,GPU-b"
|
| 296 |
+
assert env["HFD_MANUAL_DDP_SYNC"] == "1"
|
| 297 |
+
assert (executable == "bash") == (monitor == "1")
|
| 298 |
+
assert any("train_with_gpu_monitor.sh" in arg for arg in command) == (monitor == "1")
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@pytest.mark.parametrize('legacy_paths', [False, True])
|
| 302 |
+
def test_raw_data_admission_keeps_hash_count_and_waveform_checks(tmp_path, monkeypatch, legacy_paths):
|
| 303 |
+
import wave
|
| 304 |
+
from psi.hfd_training_preflight import validate_raw_audio
|
| 305 |
+
background = tmp_path / "background"
|
| 306 |
+
background.mkdir()
|
| 307 |
+
wav = background / "bg.wav"
|
| 308 |
+
with wave.open(str(wav), "wb") as stream:
|
| 309 |
+
stream.setnchannels(1)
|
| 310 |
+
stream.setsampwidth(2)
|
| 311 |
+
stream.setframerate(16000)
|
| 312 |
+
stream.writeframes(b"\0" * 32)
|
| 313 |
+
manifests = tmp_path / "manifests"
|
| 314 |
+
manifests.mkdir()
|
| 315 |
+
mixed_path, background_path = str(wav), 'bg.wav'
|
| 316 |
+
if legacy_paths:
|
| 317 |
+
import psi.data.seed.storage_paths as paths
|
| 318 |
+
monkeypatch.setattr(paths, '_LEGACY_STORAGE_PREFIXES', ((Path('/legacy-data'), tmp_path),))
|
| 319 |
+
mixed_path = background_path = '/legacy-data/background/bg.wav'
|
| 320 |
+
(manifests / "background_sessions.jsonl").write_text(
|
| 321 |
+
json.dumps({"filename": "bg", "audio_path": background_path}) + "\n")
|
| 322 |
+
assignment = manifests / "source_background_assignments.jsonl"
|
| 323 |
+
assignment.write_text(json.dumps({"mixed_audio_path": mixed_path, "background_key": "bg"}) + "\n")
|
| 324 |
+
marker = tmp_path / "marker.json"
|
| 325 |
+
marker.write_text(json.dumps({
|
| 326 |
+
"format": "hfd_continuous_office_production_v1", "source_count": 1,
|
| 327 |
+
"initial_idle_max_steps": 5, "stationary_blend_frames": 20,
|
| 328 |
+
"assignment_sha256": hashlib.sha256(assignment.read_bytes()).hexdigest(),
|
| 329 |
+
}))
|
| 330 |
+
o, _ = resolve(ROOT, {"HFD_CONTINUOUS_DATA_ROOT": str(tmp_path)})
|
| 331 |
+
env = {"HFD_CONTINUOUS_DATA_CONTRACT_PATH": str(marker)}
|
| 332 |
+
validate_raw_audio(o, env)
|
| 333 |
+
assignment.write_text(assignment.read_text() + "\n")
|
| 334 |
+
with pytest.raises(RuntimeError, match="changed after production"):
|
| 335 |
+
validate_raw_audio(o, env)
|
tests/test_hfd_vqa_candidate_pilot.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small, offline regression tests for the opt-in VQA admission pilot."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import importlib.util
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
+
SPEC = importlib.util.spec_from_file_location(
|
| 13 |
+
"hfd_vqa_candidate_pilot", ROOT / "scripts/data/build_hfd_vqa_candidate_pilot.py"
|
| 14 |
+
)
|
| 15 |
+
assert SPEC is not None and SPEC.loader is not None
|
| 16 |
+
PILOT = importlib.util.module_from_spec(SPEC)
|
| 17 |
+
SPEC.loader.exec_module(PILOT)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _row(tmp_path: Path, *, split: str = "train", accepted: bool = True) -> dict:
|
| 21 |
+
body = tmp_path / f"{split}.pt"
|
| 22 |
+
body.write_bytes(b"body")
|
| 23 |
+
voice = tmp_path / f"{split}.wav"
|
| 24 |
+
voice.write_bytes(b"wav")
|
| 25 |
+
return {
|
| 26 |
+
"id": f"vqav2_{split}_1",
|
| 27 |
+
"split": split,
|
| 28 |
+
"path": str(body),
|
| 29 |
+
"frontend_root": str(tmp_path / "frontend"),
|
| 30 |
+
"cohort": "vqav2_static",
|
| 31 |
+
"question": {
|
| 32 |
+
"question": "Is this picture in color?",
|
| 33 |
+
"answer": "yes",
|
| 34 |
+
"human_votes": 10,
|
| 35 |
+
},
|
| 36 |
+
"visual_review": {"accepted": accepted},
|
| 37 |
+
"timeline": {"question_voice": str(voice)},
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_vqav2_gate_uses_row_level_blind_review(tmp_path: Path) -> None:
|
| 42 |
+
assert PILOT._quality_gate(_row(tmp_path))[0]
|
| 43 |
+
accepted, reason = PILOT._quality_gate(_row(tmp_path, accepted=False))
|
| 44 |
+
assert not accepted
|
| 45 |
+
assert reason == "vqav2_agreement_or_visual_review_failed"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_pilot_selection_is_split_and_body_disjoint(tmp_path: Path) -> None:
|
| 49 |
+
rows = [_row(tmp_path, split="train"), _row(tmp_path, split="val")]
|
| 50 |
+
selected, audit = PILOT.select_hfd_rows(rows, train_limit=1, val_limit=1)
|
| 51 |
+
assert len(selected) == 2
|
| 52 |
+
assert audit["formal_source_plan_changed"] is False
|
| 53 |
+
assert {row["split"] for row in selected} == {"train", "val"}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_gqa_gate_rejects_ambiguous_questions() -> None:
|
| 57 |
+
base = {
|
| 58 |
+
"isBalanced": True,
|
| 59 |
+
"types": {"structural": "verify"},
|
| 60 |
+
"question": "Is the person holding a cup?",
|
| 61 |
+
"answer": "yes",
|
| 62 |
+
}
|
| 63 |
+
assert PILOT.conservative_gqa_row(base)[0]
|
| 64 |
+
ambiguous = {**base, "question": "Why might the person be there?"}
|
| 65 |
+
accepted, reason = PILOT.conservative_gqa_row(ambiguous)
|
| 66 |
+
assert not accepted and reason == "speculative_or_text_question"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@pytest.mark.skipif(not __import__("shutil").which("ffmpeg"), reason="ffmpeg unavailable")
|
| 70 |
+
def test_review_answer_waveform_is_separate_from_input(tmp_path: Path) -> None:
|
| 71 |
+
spec = importlib.util.spec_from_file_location(
|
| 72 |
+
"hfd_gt_render", ROOT / "scripts/data/render_hfd_unified_multimodal_gt.py"
|
| 73 |
+
)
|
| 74 |
+
assert spec is not None and spec.loader is not None
|
| 75 |
+
module = importlib.util.module_from_spec(spec)
|
| 76 |
+
spec.loader.exec_module(module)
|
| 77 |
+
output = tmp_path / "answer.wav"
|
| 78 |
+
assert module._synthesize_review_answer("Camera lens", output)
|
| 79 |
+
import wave
|
| 80 |
+
|
| 81 |
+
with wave.open(str(output), "rb") as handle:
|
| 82 |
+
assert handle.getframerate() == 16_000
|
| 83 |
+
assert handle.getnchannels() == 1
|
| 84 |
+
assert handle.getnframes() > 0
|
| 85 |
+
|
tests/test_hfdv2_qwen_streaming.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tests/test_listen_hold_targets.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Listen hold changes targets only, while preserving legacy recipes/RNG."""
|
| 2 |
+
import random
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
from psi.data.seed.full_duplex_audio_command_dataset import (
|
| 9 |
+
FullDuplexAudioCommandDataset as Dataset, StationaryMotionSource,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def fixture():
|
| 14 |
+
anchor = np.zeros(36, np.float32); anchor[31] = .82; anchor[32] = 1.
|
| 15 |
+
motion = np.repeat(anchor[None], 160, axis=0)
|
| 16 |
+
# Real listen primitive: enter, hold, exit. Preserve its own matched z/legs.
|
| 17 |
+
motion[:, 22] = np.r_[np.linspace(0., -1., 30), np.full(100, -1.), np.linspace(-1., 0., 30)]
|
| 18 |
+
motion[:, 31] = .84
|
| 19 |
+
source = StationaryMotionSource('listen', Path('/unused/listen'), len(motion), 'listen')
|
| 20 |
+
ds = Dataset.__new__(Dataset)
|
| 21 |
+
ds.stationary_motion_pools = {'idle': (source,), 'listen': (source,)}
|
| 22 |
+
ds.stationary_blend_frames = ds.turn_transition_frames = 50
|
| 23 |
+
ds.stationary_heading_alignment = True
|
| 24 |
+
ds.dynamic_task_entry_blend = True
|
| 25 |
+
ds._load_motion = lambda _: motion.copy()
|
| 26 |
+
return ds, anchor, motion
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@pytest.mark.parametrize('frames', [1, 20, 60, 80, 200])
|
| 30 |
+
def test_listen_enters_then_holds_without_exit_dip(frames):
|
| 31 |
+
ds, anchor, _ = fixture(); ds.stationary_listen_hold = True
|
| 32 |
+
result, _ = ds._sample_stationary_sequence('listen', frame_count=frames, anchor_pose=anchor)
|
| 33 |
+
np.testing.assert_array_equal(result[0], anchor)
|
| 34 |
+
assert np.all(np.diff(result[:, 22]) <= 1e-6)
|
| 35 |
+
if frames >= 50:
|
| 36 |
+
np.testing.assert_allclose(result[49:, 22], -1., atol=1e-6)
|
| 37 |
+
np.testing.assert_allclose(result[49:, 31], .84, atol=1e-6)
|
| 38 |
+
assert np.isfinite(result).all()
|
| 39 |
+
np.testing.assert_allclose(np.linalg.norm(result[:, 32:36], axis=1), 1., atol=1e-6)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_interruption_enters_from_actual_pose_and_motion_starts_at_listen_end():
|
| 43 |
+
ds, anchor, motion = fixture(); ds.stationary_listen_hold = True
|
| 44 |
+
entry = anchor.copy(); entry[22] = .3; entry[31] = .85
|
| 45 |
+
listen, _ = ds._sample_stationary_sequence('listen', frame_count=80, anchor_pose=anchor, entry_pose=entry)
|
| 46 |
+
np.testing.assert_array_equal(listen[0], entry)
|
| 47 |
+
task, _ = ds._build_task_sequence(motion, stationary_anchor=listen[-1], transition_frames=50)
|
| 48 |
+
np.testing.assert_allclose(task[0], listen[-1], atol=1e-6)
|
| 49 |
+
assert len(task) == len(motion)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_flag_retains_legacy_rng_and_does_not_change_idle():
|
| 53 |
+
ds, anchor, _ = fixture()
|
| 54 |
+
for phase in ['listen', 'idle']:
|
| 55 |
+
random.seed(73); ds.stationary_listen_hold = False
|
| 56 |
+
old, name = ds._sample_stationary_sequence(phase, frame_count=80, anchor_pose=anchor)
|
| 57 |
+
state = random.getstate()
|
| 58 |
+
random.seed(73); ds.stationary_listen_hold = True
|
| 59 |
+
new, new_name = ds._sample_stationary_sequence(phase, frame_count=80, anchor_pose=anchor)
|
| 60 |
+
assert name == new_name and state == random.getstate()
|
| 61 |
+
if phase == 'idle': np.testing.assert_array_equal(old, new)
|
| 62 |
+
else:
|
| 63 |
+
np.testing.assert_allclose(old[-1], anchor)
|
| 64 |
+
assert abs(float(new[-1, 22] - anchor[22])) > .9
|
tests/test_native_visual.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import SimpleNamespace
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
from psi.data.seed.native_visual import request_frames, resolve_visual
|
| 8 |
+
from psi.data.seed.live_multimodal_overlay import attach_live_packets, camera_count
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_native_image_uses_same_pad_repeat(tmp_path):
|
| 12 |
+
from PIL import ImageOps
|
| 13 |
+
path = tmp_path/'image.png'
|
| 14 |
+
Image.fromarray(np.arange(32*48*3, dtype=np.uint8).reshape(32,48,3)).save(path)
|
| 15 |
+
ref = np.asarray(ImageOps.pad(Image.open(path).convert('RGB'), (224,224), color=(0,0,0)))
|
| 16 |
+
for count in (3,4,5):
|
| 17 |
+
value = request_frames(dict(path=str(path),kind='image',count=count,index=0,duration=None))
|
| 18 |
+
assert np.array_equal(value,np.repeat(ref[None],count,axis=0))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_raw_packets_do_not_open_feature_file(tmp_path):
|
| 22 |
+
image=tmp_path/'input.jpg'
|
| 23 |
+
Image.new('RGB',(224,224)).save(image)
|
| 24 |
+
source = dict(multimodal_overlay=dict(mode='visual-only',visual_input_mode='raw',
|
| 25 |
+
camera_kind='static',image_path=str(image)),
|
| 26 |
+
steps=[dict(update_semantic_cache=True,semantic_window_index=i,
|
| 27 |
+
stream_input_features=torch.ones(2),stream_feature_attention_mask=torch.ones(2)) for i in range(3)])
|
| 28 |
+
attach_live_packets(source)
|
| 29 |
+
for i,p in enumerate(source['swa_packets']):
|
| 30 |
+
assert p['visual_features'] is None
|
| 31 |
+
assert p['native_visual']['count']==camera_count(i)
|
| 32 |
+
assert p['native_visual']['index']==i
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_native_inactive_does_not_decode_or_encode():
|
| 36 |
+
qwen=SimpleNamespace(model=SimpleNamespace(embed_tokens=torch.nn.Embedding(5,2048)))
|
| 37 |
+
p=dict(native_visual=dict(count=5,path='/not/read'),visual_features=None)
|
| 38 |
+
assert resolve_visual(qwen,p,False).shape==(192,2048)
|
| 39 |
+
assert not resolve_visual(qwen,p,False).any()
|
| 40 |
+
p['visual_features']=torch.ones(2,3)
|
| 41 |
+
with pytest.raises(ValueError,match='not both'):resolve_visual(qwen,p)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_raw_short_video_fails_before_missing_cache_access():
|
| 45 |
+
source=dict(multimodal_overlay=dict(mode='visual-only',visual_input_mode='raw',
|
| 46 |
+
camera_kind='dynamic',camera_duration_seconds=2.,session_required_seconds=3.),steps=[])
|
| 47 |
+
with pytest.raises(ValueError,match='cover the complete session'):attach_live_packets(source)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_native_video_phase_and_end(monkeypatch,tmp_path):
|
| 51 |
+
path=tmp_path/'video.mp4';path.touch()
|
| 52 |
+
from psi.data.seed import native_visual
|
| 53 |
+
frames=np.zeros((8,224,224,3),np.uint8)
|
| 54 |
+
monkeypatch.setattr(native_visual,'_rgb',lambda *a:(frames,[[0,1,2,3,4],[5,6,7]],None))
|
| 55 |
+
req=dict(path=str(path),kind='video',index=1,count=3,duration=1.)
|
| 56 |
+
assert request_frames(req).shape[0]==3
|
| 57 |
+
with pytest.raises(ValueError,match='phase'):request_frames({**req,'count':4})
|
| 58 |
+
with pytest.raises(ValueError,match='ended'):request_frames({**req,'index':2})
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_both_modes_prepare_identical_qwen_inputs(monkeypatch):
|
| 62 |
+
from test_causal_av_packing import LiveQwen, live_packet
|
| 63 |
+
from psi.models.causal_av import prepare_av_batch
|
| 64 |
+
from psi.data.seed import native_visual
|
| 65 |
+
qwen=LiveQwen()
|
| 66 |
+
cached=live_packet(3)
|
| 67 |
+
raw={**cached,'visual_features':None,'native_visual':{'count':5}}
|
| 68 |
+
monkeypatch.setattr(native_visual,'request_frames',lambda r:np.zeros((5,224,224,3),np.uint8))
|
| 69 |
+
monkeypatch.setattr(native_visual,'encode_frames',lambda *a:cached['visual_features'])
|
| 70 |
+
qwen._hfd_native_visual_processor=object()
|
| 71 |
+
left=prepare_av_batch(qwen,[cached],True)
|
| 72 |
+
right=prepare_av_batch(qwen,[raw],True)
|
| 73 |
+
for name in ('embeds','ids','positions','mask'):
|
| 74 |
+
assert torch.equal(getattr(left,name),getattr(right,name))
|
| 75 |
+
assert left.advances==right.advances
|
| 76 |
+
assert raw['visual_features'] is None # no retained CUDA tensors in source packets
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_native_mode_rejects_invalid_config():
|
| 80 |
+
from psi.config.data_full_duplex_audio_command import FullDuplexAudioCommandDataConfig
|
| 81 |
+
with pytest.raises(ValueError):FullDuplexAudioCommandDataConfig(multimodal_visual_input_mode='auto')
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_raw_mode_is_exposed_by_launcher():
|
| 85 |
+
from pathlib import Path
|
| 86 |
+
from psi.hfd_training_launcher import resolve
|
| 87 |
+
root=Path(__file__).resolve().parents[1]
|
| 88 |
+
options,_=resolve(root,{'HFD_VISUAL_INPUT_MODE':'raw'})
|
| 89 |
+
assert options['data.multimodal-visual-input-mode']=='raw'
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_switching_rollout_mode_does_not_mutate_original(tmp_path):
|
| 93 |
+
from psi.data.seed.native_visual import source_visual_mode
|
| 94 |
+
Image.new('RGB',(224,224)).save(tmp_path/'i.jpg')
|
| 95 |
+
old={'multimodal_overlay':dict(mode='visual-only',camera_kind='static',image_path=str(tmp_path/'i.jpg')),
|
| 96 |
+
'steps':[dict(update_semantic_cache=True,semantic_window_index=0,
|
| 97 |
+
stream_input_features=torch.ones(2),stream_feature_attention_mask=torch.ones(2))],
|
| 98 |
+
'swa_packets':[{'old':True}]}
|
| 99 |
+
new=source_visual_mode(old,'raw')
|
| 100 |
+
assert old['swa_packets']==[{'old':True}]
|
| 101 |
+
assert 'visual_input_mode' not in old['multimodal_overlay']
|
| 102 |
+
assert new['swa_packets'][0]['native_visual']['kind']=='image'
|
tests/test_office_background_candidates.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
import wave
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 15 |
+
SCRIPT = PROJECT_ROOT / "scripts/data/generate_office_background_candidates.py"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _sha256(path: Path) -> str:
|
| 19 |
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_procedural_office_candidates_are_quiet_exact_and_deterministic(
|
| 23 |
+
tmp_path: Path,
|
| 24 |
+
) -> None:
|
| 25 |
+
first = tmp_path / "first"
|
| 26 |
+
second = tmp_path / "second"
|
| 27 |
+
for output in (first, second):
|
| 28 |
+
subprocess.run(
|
| 29 |
+
[
|
| 30 |
+
sys.executable,
|
| 31 |
+
str(SCRIPT),
|
| 32 |
+
"--output-dir",
|
| 33 |
+
str(output),
|
| 34 |
+
"--duration-seconds",
|
| 35 |
+
"1.0",
|
| 36 |
+
"--seed",
|
| 37 |
+
"1234",
|
| 38 |
+
],
|
| 39 |
+
check=True,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
first_manifest = json.loads(
|
| 43 |
+
(first / "candidate_manifest.json").read_text(encoding="utf-8")
|
| 44 |
+
)
|
| 45 |
+
second_manifest = json.loads(
|
| 46 |
+
(second / "candidate_manifest.json").read_text(encoding="utf-8")
|
| 47 |
+
)
|
| 48 |
+
assert first_manifest["candidate_count"] == 5
|
| 49 |
+
assert second_manifest["candidate_count"] == 5
|
| 50 |
+
|
| 51 |
+
hashes = set()
|
| 52 |
+
for first_row, second_row in zip(
|
| 53 |
+
first_manifest["candidates"],
|
| 54 |
+
second_manifest["candidates"],
|
| 55 |
+
strict=True,
|
| 56 |
+
):
|
| 57 |
+
first_path = first / first_row["filename"]
|
| 58 |
+
second_path = second / second_row["filename"]
|
| 59 |
+
assert _sha256(first_path) == _sha256(second_path)
|
| 60 |
+
hashes.add(_sha256(first_path))
|
| 61 |
+
assert first_row["speech_screen"] == "speech-free by construction"
|
| 62 |
+
assert first_row["rms_dbfs"] <= -37.5
|
| 63 |
+
assert first_row["peak_dbfs"] <= -12.0
|
| 64 |
+
with wave.open(str(first_path), "rb") as handle:
|
| 65 |
+
assert handle.getframerate() == 16_000
|
| 66 |
+
assert handle.getnchannels() == 1
|
| 67 |
+
assert handle.getsampwidth() == 2
|
| 68 |
+
assert handle.getnframes() == 16_000
|
| 69 |
+
assert len(hashes) == 5
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_candidate_module_exposes_real_speech_screening() -> None:
|
| 73 |
+
spec = importlib.util.spec_from_file_location("office_background_candidates", SCRIPT)
|
| 74 |
+
assert spec is not None and spec.loader is not None
|
| 75 |
+
module = importlib.util.module_from_spec(spec)
|
| 76 |
+
spec.loader.exec_module(module)
|
| 77 |
+
assert callable(module._speech_ratio)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_speech_free_segments_never_join_across_vad_hits(monkeypatch) -> None:
|
| 81 |
+
spec = importlib.util.spec_from_file_location(
|
| 82 |
+
"office_background_candidates_segments",
|
| 83 |
+
SCRIPT,
|
| 84 |
+
)
|
| 85 |
+
assert spec is not None and spec.loader is not None
|
| 86 |
+
module = importlib.util.module_from_spec(spec)
|
| 87 |
+
spec.loader.exec_module(module)
|
| 88 |
+
decisions = np.zeros(100, dtype=np.bool_)
|
| 89 |
+
decisions[50] = True
|
| 90 |
+
monkeypatch.setattr(module, "_speech_decisions", lambda samples: decisions)
|
| 91 |
+
|
| 92 |
+
samples = np.zeros(100 * int(0.03 * 16_000), dtype=np.float32)
|
| 93 |
+
segments, report = module._speech_free_segments(
|
| 94 |
+
samples,
|
| 95 |
+
margin_seconds=0.03,
|
| 96 |
+
minimum_seconds=0.3,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
assert len(segments) == 2
|
| 100 |
+
assert segments[0][1] < segments[1][0]
|
| 101 |
+
assert report["vad_positive_frames"] == 1
|
tests/test_production_a1_control.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real Transformers micro-Qwen audit of production A1/C topology."""
|
| 2 |
+
from copy import deepcopy
|
| 3 |
+
from types import SimpleNamespace, MethodType
|
| 4 |
+
import pytest
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from transformers import Qwen2_5OmniThinkerTextModel
|
| 8 |
+
from transformers.models.qwen2_5_omni.configuration_qwen2_5_omni import Qwen2_5OmniTextConfig
|
| 9 |
+
from psi.models.swa_qa_branch import BranchLoRALinear, OnlineQaBranch
|
| 10 |
+
from psi.models.full_duplex_psi0 import QwenStreamingKVCache, FullDuplexPsi0Model
|
| 11 |
+
from psi.models.full_duplex_swa import FullDuplexSwaModel
|
| 12 |
+
from psi.models.interaction_arch.runtime import ArchitectureRuntime, ArchitectureSpec
|
| 13 |
+
from psi.models.interaction_arch.control_tokens import VocabularyOverlay, TokenReadout, enable_packet_write
|
| 14 |
+
|
| 15 |
+
class Tokenizer:
|
| 16 |
+
def encode(self, text, add_special_tokens=False):
|
| 17 |
+
return {"a": [7, 8], "b": [9, 10]}.get(text, [5, 6])
|
| 18 |
+
|
| 19 |
+
def decode(self, ids, skip_special_tokens=True):
|
| 20 |
+
return " ".join(map(str, ids))
|
| 21 |
+
|
| 22 |
+
class TinyThinker(nn.Module):
|
| 23 |
+
def __init__(self):
|
| 24 |
+
super().__init__()
|
| 25 |
+
config = Qwen2_5OmniTextConfig(
|
| 26 |
+
vocab_size=32, hidden_size=16, intermediate_size=24,
|
| 27 |
+
num_hidden_layers=10, num_attention_heads=4, num_key_value_heads=2,
|
| 28 |
+
max_position_embeddings=256, attention_dropout=0.0,
|
| 29 |
+
layer_types=["full_attention"] * 10,
|
| 30 |
+
rope_scaling={"rope_type": "default", "mrope_section": [1, 1, 0]},
|
| 31 |
+
)
|
| 32 |
+
config._attn_implementation = "eager"
|
| 33 |
+
self.model = Qwen2_5OmniThinkerTextModel(config)
|
| 34 |
+
self.lm_head = nn.Linear(16, 32, bias=False)
|
| 35 |
+
self.config = SimpleNamespace(text_config=config, vision_start_token_id=11, eos_token_id=2)
|
| 36 |
+
|
| 37 |
+
def get_input_embeddings(self):
|
| 38 |
+
return self.model.embed_tokens
|
| 39 |
+
|
| 40 |
+
def model_and_optimizer():
|
| 41 |
+
torch.manual_seed(831)
|
| 42 |
+
torch.set_num_threads(1)
|
| 43 |
+
model = nn.Module()
|
| 44 |
+
body = TinyThinker().eval().requires_grad_(False)
|
| 45 |
+
qa = OnlineQaBranch.__new__(OnlineQaBranch)
|
| 46 |
+
nn.Module.__init__(qa)
|
| 47 |
+
qa.vlm_model = deepcopy(body)
|
| 48 |
+
for layer in qa.vlm_model.model.layers[-8:]:
|
| 49 |
+
for owner, names in (("self_attn", ("q_proj", "k_proj", "v_proj", "o_proj")),
|
| 50 |
+
("mlp", ("gate_proj", "up_proj", "down_proj"))):
|
| 51 |
+
for name in names:
|
| 52 |
+
module = getattr(layer, owner)
|
| 53 |
+
setattr(module, name, BranchLoRALinear(getattr(module, name)))
|
| 54 |
+
for layer in body.model.layers[-8:]:
|
| 55 |
+
layer.requires_grad_(True)
|
| 56 |
+
# Match the formal staged body: its final norm is trainable and belongs
|
| 57 |
+
# to the body optimizer, even when the QA branch must be isolated.
|
| 58 |
+
body.model.norm.requires_grad_(True)
|
| 59 |
+
qa.vlm_processor = SimpleNamespace(tokenizer=Tokenizer())
|
| 60 |
+
qa.av_context_limit = 256
|
| 61 |
+
qa.memory_seconds = 4.0
|
| 62 |
+
qa.eval()
|
| 63 |
+
model.vlm_model = body
|
| 64 |
+
model.qa_model = qa
|
| 65 |
+
model.reply_head = nn.Linear(16, 2)
|
| 66 |
+
optimizer = torch.optim.AdamW([
|
| 67 |
+
dict(params=[p for p in body.parameters() if p.requires_grad], group_name="vlm_model"),
|
| 68 |
+
dict(params=[p for p in qa.parameters() if p.requires_grad], group_name="swa_qa",
|
| 69 |
+
qa_updates=0, qa_base_lr=5e-5, qa_warmup_updates=40),
|
| 70 |
+
dict(params=list(model.reply_head.parameters()), group_name="other"),
|
| 71 |
+
])
|
| 72 |
+
return model, optimizer
|
| 73 |
+
|
| 74 |
+
def packets(lengths, seed=91):
|
| 75 |
+
generator = torch.Generator().manual_seed(seed)
|
| 76 |
+
return [dict(ids=torch.tensor([11] + [12] * (n - 1)),
|
| 77 |
+
embeds=torch.randn(n, 16, generator=generator),
|
| 78 |
+
positions=torch.arange(n)[None].expand(3, -1).clone(),
|
| 79 |
+
next_position=n) for n in lengths]
|
| 80 |
+
|
| 81 |
+
def setup_model():
|
| 82 |
+
# Reuse the actual HF micro-Qwen fixture, not mocked attention/cache layers.
|
| 83 |
+
model, _unused_optimizer = model_and_optimizer()
|
| 84 |
+
model.swa_packets = None
|
| 85 |
+
model.qwen_memory_window_seconds = 4.0
|
| 86 |
+
model.av_context_limit = 256
|
| 87 |
+
model.vlm_processor = model.qa_model.vlm_processor
|
| 88 |
+
model.keep_tape = False
|
| 89 |
+
model.swa_reply_detach_body = True
|
| 90 |
+
model.motion_duration_head = nn.Linear(16, 1)
|
| 91 |
+
model._encode_qwen_stream_input = MethodType(FullDuplexSwaModel._encode_qwen_stream_input, model)
|
| 92 |
+
model._reply_summary_for_loss = MethodType(FullDuplexSwaModel._reply_summary_for_loss, model)
|
| 93 |
+
def predict(_self, hidden, **kwargs):
|
| 94 |
+
return hidden[:, :3]
|
| 95 |
+
def condition(_self, logits, mode=None):
|
| 96 |
+
probs = logits.softmax(-1)
|
| 97 |
+
token = torch.zeros(logits.shape[0], 1, 16, device=logits.device)
|
| 98 |
+
return probs, probs, -(probs * probs.log()).sum(-1), token, "test"
|
| 99 |
+
model._predict_control_logits = MethodType(predict, model)
|
| 100 |
+
model._build_control_condition = MethodType(condition, model)
|
| 101 |
+
model.motion_duration_quantile_log1p = lambda output, quantile: output[:, 0]
|
| 102 |
+
return model
|
| 103 |
+
|
| 104 |
+
def formal_optimizer(model):
|
| 105 |
+
# Exercise the actual trainer name-based grouping; no adapter-only shortcut.
|
| 106 |
+
from psi.trainers.posttrain_v1 import PosttrainV1Trainer
|
| 107 |
+
config = SimpleNamespace(
|
| 108 |
+
control_head_lr_multiplier=1., learning_rate=1e-3,
|
| 109 |
+
lr_scheduler_kwargs=dict(lr=1e-3, weight_decay=.01), optimizer_foreach=False,
|
| 110 |
+
swa_qa_learning_rate=1e-3, swa_qa_warmup_updates=1,
|
| 111 |
+
)
|
| 112 |
+
trainer = SimpleNamespace(model=model, cfg=SimpleNamespace(train=config),
|
| 113 |
+
model_cfg=SimpleNamespace(tune_vlm=True, lang_backbone_lr=1e-3))
|
| 114 |
+
PosttrainV1Trainer.create_optimizers(trainer)
|
| 115 |
+
return trainer.optimizer
|
| 116 |
+
|
| 117 |
+
def window(model, cache, batch, targets=None, active=None):
|
| 118 |
+
model.swa_packets = batch
|
| 119 |
+
model.swa_answer_targets = targets or [""] * len(batch)
|
| 120 |
+
return model._encode_qwen_stream_input(
|
| 121 |
+
cache=cache, source_ids=cache.source_ids,
|
| 122 |
+
update_semantic_cache=active or [True] * len(batch))
|
| 123 |
+
|
| 124 |
+
def model_fixture():
|
| 125 |
+
model = setup_model()
|
| 126 |
+
# Make two pretrained-style tails genuinely different, not copies whose
|
| 127 |
+
# duplicate K/V accidentally make the joint branch numerically redundant.
|
| 128 |
+
with torch.no_grad():
|
| 129 |
+
for module in model.qa_model.modules():
|
| 130 |
+
if isinstance(module, BranchLoRALinear):
|
| 131 |
+
module.up.weight.normal_(0, .03)
|
| 132 |
+
model.vlm_model.model.layers[-2].mlp.up_proj.weight.add_(.006)
|
| 133 |
+
return model
|
| 134 |
+
|
| 135 |
+
def empty(batch=1):
|
| 136 |
+
return QwenStreamingKVCache.empty([f"source-{i}" for i in range(batch)])
|
| 137 |
+
|
| 138 |
+
def fixture(arm):
|
| 139 |
+
model = model_fixture()
|
| 140 |
+
rows = nn.Embedding(3, 16)
|
| 141 |
+
with torch.no_grad():
|
| 142 |
+
rows.weight.copy_(torch.arange(48).reshape(3, 16) / 1000)
|
| 143 |
+
model.control_condition_embedding = rows
|
| 144 |
+
model.control_head = TokenReadout(rows)
|
| 145 |
+
model.control_condition_temperature = 1.0
|
| 146 |
+
model.control_condition_train_mode = model.control_condition_inference_mode = "hard"
|
| 147 |
+
model.state_aware_serial_control = False
|
| 148 |
+
for name in ("_predict_control_logits", "_build_control_condition", "_active_control_condition_mode"):
|
| 149 |
+
setattr(model, name, MethodType(getattr(FullDuplexPsi0Model, name), model))
|
| 150 |
+
model.vlm_model.model.embed_tokens = VocabularyOverlay(model.vlm_model.model.embed_tokens, rows, (29, 30, 31))
|
| 151 |
+
model.vlm_model.lm_head = VocabularyOverlay(model.vlm_model.lm_head, rows, (29, 30, 31), output=True)
|
| 152 |
+
model.control_token_arm = arm
|
| 153 |
+
model.control_token_ids = (29, 30, 31)
|
| 154 |
+
model.control_token_append_trace = []
|
| 155 |
+
spec = ArchitectureSpec("a1", "cross", prefix_layers=2, cross_layer=8, bridge_dim=16, heads=4, control_token_arm=arm)
|
| 156 |
+
runtime = ArchitectureRuntime(model, spec)
|
| 157 |
+
optimizer = formal_optimizer(model)
|
| 158 |
+
runtime.install(optimizer=optimizer, prepared=True)
|
| 159 |
+
enable_packet_write(model)
|
| 160 |
+
return model, runtime, optimizer
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def test_tied_embedding_lm_head_only_three_rows_receive_gradient():
|
| 164 |
+
rows = nn.Embedding(3, 8)
|
| 165 |
+
embed = VocabularyOverlay(nn.Embedding(32, 8), rows, (29, 30, 31))
|
| 166 |
+
head = VocabularyOverlay(nn.Linear(8, 32, bias=False), rows, (29, 30, 31), output=True)
|
| 167 |
+
h = torch.randn(2, 8, requires_grad=True)
|
| 168 |
+
torch.testing.assert_close(head(h)[:, 29:], h @ rows.weight.T)
|
| 169 |
+
torch.testing.assert_close(embed(torch.tensor([29, 30, 31])), rows.weight)
|
| 170 |
+
(head(h).sum() + embed(torch.tensor([5, 30])).sum()).backward()
|
| 171 |
+
assert rows.weight.grad is not None
|
| 172 |
+
assert embed.base.weight.grad is None and head.base.weight.grad is None
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def test_control_ce_optimizable_without_changing_frozen_vocabulary():
|
| 176 |
+
torch.manual_seed(19)
|
| 177 |
+
rows = nn.Embedding(3, 16)
|
| 178 |
+
head = TokenReadout(rows)
|
| 179 |
+
hidden = torch.randn(12, 16)
|
| 180 |
+
labels = torch.arange(12) % 3
|
| 181 |
+
optimizer = torch.optim.AdamW(rows.parameters(), lr=.05)
|
| 182 |
+
before = torch.nn.functional.cross_entropy(head(hidden), labels).item()
|
| 183 |
+
for _ in range(80):
|
| 184 |
+
optimizer.zero_grad()
|
| 185 |
+
loss = torch.nn.functional.cross_entropy(head(hidden), labels)
|
| 186 |
+
loss.backward(); optimizer.step()
|
| 187 |
+
assert loss.item() < before * .1
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_answer_gradient_does_not_update_state_rows_or_body():
|
| 191 |
+
model, runtime, optimizer = fixture("B")
|
| 192 |
+
try:
|
| 193 |
+
output = window(model, empty(2), packets([4, 3]), targets=["a", "b"])
|
| 194 |
+
loss = model.qa_model.qa_loss(output.kv_cache.qa_cache, ["a", "b"])[0]
|
| 195 |
+
loss.backward()
|
| 196 |
+
assert model.control_condition_embedding.weight.grad is None
|
| 197 |
+
assert all(p.grad is None for p in model.vlm_model.parameters())
|
| 198 |
+
finally:
|
| 199 |
+
runtime.close()
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def test_action_condition_updates_shared_rows_but_not_argmax_input():
|
| 203 |
+
model, runtime, optimizer = fixture("A")
|
| 204 |
+
try:
|
| 205 |
+
h = torch.randn(2,16,requires_grad=True)
|
| 206 |
+
logits = model.control_head(h)
|
| 207 |
+
token = model._build_control_condition(logits)[3]
|
| 208 |
+
token.square().sum().backward()
|
| 209 |
+
assert h.grad is None
|
| 210 |
+
assert model.control_condition_embedding.weight.grad is not None
|
| 211 |
+
finally:
|
| 212 |
+
runtime.close()
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def test_semantic_anchor_keeps_action_loss_out_of_vocabulary_rows():
|
| 216 |
+
model = model_fixture()
|
| 217 |
+
rows = nn.Embedding(3, 16)
|
| 218 |
+
model.control_condition_embedding = rows
|
| 219 |
+
model.control_head = TokenReadout(rows)
|
| 220 |
+
model.control_condition_temperature = 1.0
|
| 221 |
+
model.control_condition_train_mode = model.control_condition_inference_mode = "hard"
|
| 222 |
+
for name in ("_predict_control_logits", "_build_control_condition", "_active_control_condition_mode"):
|
| 223 |
+
setattr(model, name, MethodType(getattr(FullDuplexPsi0Model, name), model))
|
| 224 |
+
original = model._build_control_condition
|
| 225 |
+
def protected(logits, *, mode=None):
|
| 226 |
+
values = list(original(logits, mode=mode)); values[3] = values[3].detach(); return tuple(values)
|
| 227 |
+
model._build_control_condition = protected
|
| 228 |
+
hidden = torch.randn(2, 16, requires_grad=True)
|
| 229 |
+
logits = model.control_head(hidden)
|
| 230 |
+
action_token = model._build_control_condition(logits)[3]
|
| 231 |
+
assert not action_token.requires_grad
|
| 232 |
+
torch.nn.functional.cross_entropy(logits, torch.tensor([0, 2])).backward()
|
| 233 |
+
assert rows.weight.grad is not None
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def test_deferred_state_is_source_keyed_across_train_eval_batch_sizes():
|
| 237 |
+
model, runtime, optimizer = fixture("C")
|
| 238 |
+
try:
|
| 239 |
+
train = window(model, empty(2), packets([4, 3]), active=[True, True])
|
| 240 |
+
assert len(model.control_token_pending_ids) == 2
|
| 241 |
+
# A validation batch with a different source and batch size must begin
|
| 242 |
+
# clean instead of inheriting a physical training slot.
|
| 243 |
+
validation = window(model, empty(1), packets([3], seed=9), active=[True])
|
| 244 |
+
assert validation.kv_cache.token_count == 3
|
| 245 |
+
assert model.control_token_append_trace[-1]["deferred_state_ids"] == [None]
|
| 246 |
+
finally:
|
| 247 |
+
runtime.close()
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
@pytest.mark.parametrize("arm", ["A", "B", "C"])
|
| 251 |
+
def test_real_qwen_three_packets_backward_reset_expiration_and_qa_isolation(arm):
|
| 252 |
+
model, runtime, optimizer = fixture(arm)
|
| 253 |
+
cache = empty(2)
|
| 254 |
+
lengths = []
|
| 255 |
+
try:
|
| 256 |
+
for step in range(5):
|
| 257 |
+
if step == 3:
|
| 258 |
+
cache.rebind_rows(("source-0", "replacement"), (False, True))
|
| 259 |
+
out = window(model, cache, packets([4, 3], seed=step), active=[True, step != 2])
|
| 260 |
+
lengths.append((out.kv_cache.token_count, out.kv_cache.qa_cache.token_count))
|
| 261 |
+
torch.nn.functional.cross_entropy(out.control_logits, torch.tensor([0, 2])).backward()
|
| 262 |
+
assert model.control_condition_embedding.weight.grad.isfinite().all()
|
| 263 |
+
optimizer.step(); optimizer.zero_grad()
|
| 264 |
+
cache = out.kv_cache.detach()
|
| 265 |
+
assert cache.past_key_values.get_seq_length() == cache.token_count
|
| 266 |
+
assert cache.token_birth_windows.shape == cache.attention_mask.shape
|
| 267 |
+
print(arm, lengths)
|
| 268 |
+
expected = {
|
| 269 |
+
"A": [(4, 4), (8, 8), (12, 12)],
|
| 270 |
+
"B": [(5, 4), (10, 8), (15, 12)],
|
| 271 |
+
# Packet 0 has no preceding decision. Every later packet fuses
|
| 272 |
+
# one predicted state with its AV tokens in both shared branches.
|
| 273 |
+
"C": [(4, 4), (9, 9), (14, 14)],
|
| 274 |
+
}
|
| 275 |
+
assert lengths[:3] == expected[arm]
|
| 276 |
+
if arm == "C":
|
| 277 |
+
assert model.control_token_append_trace[0]["deferred_state_ids"] == [None, None]
|
| 278 |
+
assert all(value is not None for value in
|
| 279 |
+
model.control_token_append_trace[1]["deferred_state_ids"])
|
| 280 |
+
# Row 1 is inactive at packet 2 and is then rebound. Its pending
|
| 281 |
+
# state must not leak from the old source into the replacement.
|
| 282 |
+
assert model.control_token_append_trace[2]["deferred_state_ids"][1] is None
|
| 283 |
+
assert model.control_token_append_trace[3]["deferred_state_ids"][1] is None
|
| 284 |
+
assert cache.logical_window_counts == (5,2)
|
| 285 |
+
cache.expire_audio_windows(1)
|
| 286 |
+
cache.compact_invalid_tokens()
|
| 287 |
+
assert cache.past_key_values.get_seq_length() == cache.token_count
|
| 288 |
+
assert not torch.any(cache.token_birth_windows[cache.attention_mask.bool()] < 3)
|
| 289 |
+
finally:
|
| 290 |
+
runtime.close()
|
tests/test_speech_runtime_contract.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from queue import Full
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from psi.runtime import (
|
| 8 |
+
BoundedSpeechQueue,
|
| 9 |
+
PCMClockPackets,
|
| 10 |
+
SpeechChunk,
|
| 11 |
+
SpeechGenerationContext,
|
| 12 |
+
SpeechRuntimeConfig,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_verified_speech_defaults_and_geometry():
|
| 17 |
+
config = SpeechRuntimeConfig().validate()
|
| 18 |
+
assert config.solver == "euler"
|
| 19 |
+
assert config.solver_steps == 6
|
| 20 |
+
assert config.codec_chunk_codes == 36
|
| 21 |
+
assert config.first_chunk_codes == 36
|
| 22 |
+
assert config.playback_buffer_samples == 4_800
|
| 23 |
+
assert config.action_packet_samples == 9_600
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_context_positions_and_stale_result_gate():
|
| 27 |
+
context = SpeechGenerationContext("session")
|
| 28 |
+
assert context.begin_utterance() == 1
|
| 29 |
+
context.mark_generated_text(3)
|
| 30 |
+
context.mark_generated_codec(7)
|
| 31 |
+
context.mark_pcm_queued(100)
|
| 32 |
+
chunk = SpeechChunk(torch.zeros(100), "session", 1, 0)
|
| 33 |
+
queue = BoundedSpeechQueue(context, maxsize=1)
|
| 34 |
+
assert queue.submit(chunk)
|
| 35 |
+
assert queue.get().utterance_id == 1
|
| 36 |
+
queue.task_done()
|
| 37 |
+
context.cancel("user_interrupt")
|
| 38 |
+
assert not queue.submit(chunk)
|
| 39 |
+
assert context.snapshot()["generated_text_pos"] == 3
|
| 40 |
+
assert context.snapshot()["generated_codec_pos"] == 7
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_queue_is_bounded_and_never_silently_drops_current_audio():
|
| 44 |
+
context = SpeechGenerationContext("session")
|
| 45 |
+
context.begin_utterance()
|
| 46 |
+
queue = BoundedSpeechQueue(context, maxsize=1)
|
| 47 |
+
first = SpeechChunk(torch.zeros(2), "session", 1, 0)
|
| 48 |
+
second = SpeechChunk(torch.zeros(2), "session", 1, 0)
|
| 49 |
+
assert queue.submit(first)
|
| 50 |
+
try:
|
| 51 |
+
queue.submit(second, block=False)
|
| 52 |
+
except Full:
|
| 53 |
+
pass
|
| 54 |
+
else:
|
| 55 |
+
raise AssertionError("a full queue must apply backpressure")
|
| 56 |
+
assert queue.qsize() == 1
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_pcm_clock_reblocks_without_loss_or_duplication():
|
| 60 |
+
clock = PCMClockPackets(samples_per_packet=4)
|
| 61 |
+
assert [x.tolist() for x in clock.push(torch.arange(3))] == []
|
| 62 |
+
packets = clock.push(torch.arange(3, 8))
|
| 63 |
+
packets += clock.finish()
|
| 64 |
+
assert [x.tolist() for x in packets] == [[0, 1, 2, 3], [4, 5, 6, 7]]
|
| 65 |
+
assert clock.received_samples == clock.emitted_samples == 8
|
tests/test_swa_formal_integration.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import importlib.util
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from types import SimpleNamespace
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from psi.data.seed.swa_visual_qa_dataset import SwaVisualQaDataset
|
| 13 |
+
from psi.data.seed.swa_visual_qa_dataset import bind_swa_batch, modality_batches
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@pytest.mark.parametrize("auxiliary", [False, True])
|
| 20 |
+
def test_swa_losses_survive_accelerate_wrapper_and_backprop(monkeypatch, auxiliary):
|
| 21 |
+
from accelerate.utils import convert_outputs_to_fp32
|
| 22 |
+
from psi.models.full_duplex_psi0 import FullDuplexPsi0Model, FullDuplexPsi0Output
|
| 23 |
+
from psi.models.full_duplex_swa import FullDuplexSwaModel, swa_auxiliary_losses
|
| 24 |
+
|
| 25 |
+
model = FullDuplexSwaModel.__new__(FullDuplexSwaModel)
|
| 26 |
+
torch.nn.Module.__init__(model)
|
| 27 |
+
model.reply_head = torch.nn.Linear(4, 2)
|
| 28 |
+
model.qa_parameter = torch.nn.Parameter(torch.tensor(3.0))
|
| 29 |
+
model.swa_packets = [{}]
|
| 30 |
+
model.swa_compute_auxiliary = auxiliary
|
| 31 |
+
model.swa_reply_targets = torch.tensor([1])
|
| 32 |
+
model.swa_answer_targets = ["yes"]
|
| 33 |
+
model.reply_logits = model.reply_head(torch.ones(1, 4))
|
| 34 |
+
model.qa_loss = lambda cache, targets: (
|
| 35 |
+
model.qa_parameter.square(), torch.tensor(1.0), torch.tensor(2.0)
|
| 36 |
+
)
|
| 37 |
+
monkeypatch.setattr(FullDuplexPsi0Model, "forward", lambda *a, **kw:
|
| 38 |
+
FullDuplexPsi0Output(action=torch.zeros(1, dtype=torch.bfloat16)))
|
| 39 |
+
wrapped = convert_outputs_to_fp32(model.forward)
|
| 40 |
+
output = wrapped(source_ids=["source"])
|
| 41 |
+
values = swa_auxiliary_losses(output, output.action, required=True)
|
| 42 |
+
assert all(name in output for name in values)
|
| 43 |
+
assert output.action.dtype == torch.float32
|
| 44 |
+
objective = values["swa_reply_loss"].sum() + values["swa_qa_loss_sum"]
|
| 45 |
+
objective.backward()
|
| 46 |
+
if auxiliary:
|
| 47 |
+
assert values["swa_qa_token_count"].item() == 2
|
| 48 |
+
assert model.reply_head.weight.grad.abs().sum() > 0
|
| 49 |
+
assert model.qa_parameter.grad.abs() > 0
|
| 50 |
+
else:
|
| 51 |
+
assert values["swa_qa_token_count"].item() == 0
|
| 52 |
+
assert model.qa_parameter.grad is None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_swa_missing_loss_fails_closed_but_audio_only_is_compatible():
|
| 56 |
+
from psi.models.full_duplex_psi0 import FullDuplexPsi0Output
|
| 57 |
+
from psi.models.full_duplex_swa import swa_auxiliary_losses
|
| 58 |
+
output = FullDuplexPsi0Output(action=torch.zeros(2))
|
| 59 |
+
with pytest.raises(RuntimeError, match="was lost"):
|
| 60 |
+
swa_auxiliary_losses(output, output.action, required=True)
|
| 61 |
+
assert all(value.eq(0).all() for value in
|
| 62 |
+
swa_auxiliary_losses(output, output.action, required=False).values())
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@pytest.mark.parametrize("swa", [False, True])
|
| 66 |
+
def test_training_attaches_loaded_processor_before_first_forward(monkeypatch, swa):
|
| 67 |
+
from psi.trainers import posttrain_full_duplex as trainer_module
|
| 68 |
+
from psi.models import full_duplex_swa as swa_module
|
| 69 |
+
|
| 70 |
+
processor = SimpleNamespace(tokenizer=object())
|
| 71 |
+
|
| 72 |
+
class InitializationReached(Exception):
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
class Model:
|
| 76 |
+
def __init__(self, **kwargs):
|
| 77 |
+
pass
|
| 78 |
+
|
| 79 |
+
def enable_full_source_gradient_checkpointing(self):
|
| 80 |
+
assert self.vlm_processor is processor
|
| 81 |
+
raise InitializationReached
|
| 82 |
+
|
| 83 |
+
monkeypatch.setattr(trainer_module, "FullDuplexPsi0Model", Model)
|
| 84 |
+
monkeypatch.setattr(swa_module, "FullDuplexSwaModel", Model)
|
| 85 |
+
trainer = trainer_module.PosttrainFullDuplexTrainer.__new__(
|
| 86 |
+
trainer_module.PosttrainFullDuplexTrainer
|
| 87 |
+
)
|
| 88 |
+
trainer.cfg = SimpleNamespace(
|
| 89 |
+
train=SimpleNamespace(full_duplex_semantics_version=9),
|
| 90 |
+
data=SimpleNamespace(),
|
| 91 |
+
model=SimpleNamespace(swa_visual_qa_enabled=swa),
|
| 92 |
+
)
|
| 93 |
+
trainer.vlm_processor = processor
|
| 94 |
+
trainer.init_vlm_models = lambda: object()
|
| 95 |
+
with pytest.raises(InitializationReached):
|
| 96 |
+
trainer.init_models()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_swa_binding_masks_padding_and_clears_audio_transition():
|
| 100 |
+
model = SimpleNamespace()
|
| 101 |
+
source = {"source_modality": "swa_visual_qa", "swa_packets": [
|
| 102 |
+
{"reply_label": 1, "answer_target": "yes"},
|
| 103 |
+
{"reply_label": 0, "answer_target": ""},
|
| 104 |
+
]}
|
| 105 |
+
assert bind_swa_batch(model, [source, None], [0, None], device="cpu", auxiliary=True)
|
| 106 |
+
assert model.swa_reply_targets.tolist() == [1, 0]
|
| 107 |
+
assert model.swa_answer_targets == ["yes", ""]
|
| 108 |
+
assert model.swa_compute_auxiliary
|
| 109 |
+
assert bind_swa_batch(model, [source], [1], device="cpu", auxiliary=False)
|
| 110 |
+
assert model.swa_packets == [source["swa_packets"][1]]
|
| 111 |
+
assert not model.swa_compute_auxiliary
|
| 112 |
+
assert not bind_swa_batch(model, [{}], [0], device="cpu")
|
| 113 |
+
assert model.swa_packets is None and model.swa_answer_targets is None
|
| 114 |
+
with pytest.raises(RuntimeError, match="outside"):
|
| 115 |
+
bind_swa_batch(model, [source], [2], device="cpu")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_eval_modality_seams_preserve_every_source_and_order():
|
| 119 |
+
rows = [{"id": "a"}, {"id": "b"},
|
| 120 |
+
{"id": "c", "source_modality": "swa_visual_qa"},
|
| 121 |
+
{"id": "d", "source_modality": "swa_visual_qa"}]
|
| 122 |
+
batches = list(modality_batches([{"sources": rows}]))
|
| 123 |
+
assert [len(batch["sources"]) for batch in batches] == [2, 2]
|
| 124 |
+
assert [row for batch in batches for row in batch["sources"]] == rows
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def test_all_padding_swa_rank_retains_modality_without_targets():
|
| 128 |
+
model = SimpleNamespace()
|
| 129 |
+
shape_source = {"source_modality": "swa_visual_qa", "swa_packets": [
|
| 130 |
+
{"reply_label": 1, "answer_target": "do not supervise padding"}]}
|
| 131 |
+
assert bind_swa_batch(model, [None, None], [0, 0], device="cpu", auxiliary=True,
|
| 132 |
+
padding_source=shape_source)
|
| 133 |
+
assert model.swa_answer_targets == ["", ""]
|
| 134 |
+
assert model.swa_reply_targets.tolist() == [0, 0]
|
| 135 |
+
assert len(model.swa_packets) == 2
|
| 136 |
+
assert not bind_swa_batch(model, [None], [0], device="cpu", padding_source={})
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _load_infer_suite():
|
| 140 |
+
path = PROJECT_ROOT / "scripts/infer/run_multiturn_infer_suite.py"
|
| 141 |
+
spec = importlib.util.spec_from_file_location("hfd_swa_infer_suite_test", path)
|
| 142 |
+
assert spec is not None and spec.loader is not None
|
| 143 |
+
module = importlib.util.module_from_spec(spec)
|
| 144 |
+
sys.modules[spec.name] = module
|
| 145 |
+
spec.loader.exec_module(module)
|
| 146 |
+
return module
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _load_charades_builder():
|
| 150 |
+
path = PROJECT_ROOT / "scripts/data/build_swa_charades_ego.py"
|
| 151 |
+
spec = importlib.util.spec_from_file_location("hfd_charades_builder_test", path)
|
| 152 |
+
assert spec is not None and spec.loader is not None
|
| 153 |
+
module = importlib.util.module_from_spec(spec)
|
| 154 |
+
spec.loader.exec_module(module)
|
| 155 |
+
return module
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _load_charades_filter():
|
| 159 |
+
path = PROJECT_ROOT / "scripts/data/filter_swa_charades_reviews.py"
|
| 160 |
+
spec = importlib.util.spec_from_file_location("hfd_charades_filter_test", path)
|
| 161 |
+
assert spec is not None and spec.loader is not None
|
| 162 |
+
module = importlib.util.module_from_spec(spec)
|
| 163 |
+
spec.loader.exec_module(module)
|
| 164 |
+
return module
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _load_plan_merger():
|
| 168 |
+
path = PROJECT_ROOT / "scripts/data/merge_swa_source_plans.py"
|
| 169 |
+
spec = importlib.util.spec_from_file_location("hfd_swa_plan_merger_test", path)
|
| 170 |
+
assert spec is not None and spec.loader is not None
|
| 171 |
+
module = importlib.util.module_from_spec(spec)
|
| 172 |
+
spec.loader.exec_module(module)
|
| 173 |
+
return module
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def test_formal_defaults_use_unique_swa_sources_and_one_inference_queue():
|
| 177 |
+
from psi.hfd_training_launcher import resolve
|
| 178 |
+
recipe, _ = resolve(PROJECT_ROOT, {})
|
| 179 |
+
infer_script = (PROJECT_ROOT / "infer_render_auto.sh").read_text(
|
| 180 |
+
encoding="utf-8"
|
| 181 |
+
)
|
| 182 |
+
assert recipe["data.swa-train-repeat"] == 1
|
| 183 |
+
assert "run_multiturn_infer_suite.py" in infer_script
|
| 184 |
+
assert "watch_swa_visual_qa.sh" not in infer_script
|
| 185 |
+
assert "HFD_INCLUDE_AUDIO_SUITE" not in infer_script
|
| 186 |
+
assert recipe["data.swa-source-plan"].endswith("hfd_swa_vqav2_v1/source_plan_5x.json")
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def test_swa_queue_keeps_video_and_adds_static_train_val(tmp_path):
|
| 190 |
+
module = _load_infer_suite()
|
| 191 |
+
plan = tmp_path / "plan.json"
|
| 192 |
+
plan.write_text(json.dumps([
|
| 193 |
+
{"split": "train", "cohort": "video"},
|
| 194 |
+
{"split": "val", "cohort": "video"},
|
| 195 |
+
{"split": "train", "cohort": "vqav2_static"},
|
| 196 |
+
{"split": "val", "cohort": "vqav2_static"},
|
| 197 |
+
]))
|
| 198 |
+
cases = module.swa_cases_for_run({"data": {"swa_source_plan": str(plan)}})
|
| 199 |
+
assert [(c.data_split, c.index) for c in cases] == [("train", 0), ("val", 0), ("train", 1), ("val", 1)]
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def test_explicit_none_checkpoint_still_uses_fresh_run_warmup():
|
| 203 |
+
from psi.hfd_training_launcher import resolve
|
| 204 |
+
for value in ("", "None"):
|
| 205 |
+
config, _ = resolve(PROJECT_ROOT, {"HFD_RESUME_FROM_CHECKPOINT": value,
|
| 206 |
+
"HFD_MAX_TRAINING_STEPS": "10000"})
|
| 207 |
+
assert config["train.warmup-steps"] == 100
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def test_swa_jobs_share_dynamic_gpu_queue_without_faking_video_completion(monkeypatch, tmp_path):
|
| 211 |
+
module = _load_infer_suite()
|
| 212 |
+
(tmp_path / "argv.txt").write_text("fixture arguments")
|
| 213 |
+
(tmp_path / "run_config.json").write_text("{}")
|
| 214 |
+
launches = []
|
| 215 |
+
|
| 216 |
+
class CompleteProcess:
|
| 217 |
+
returncode = 0
|
| 218 |
+
|
| 219 |
+
def __init__(self, command, *, cwd, env, start_new_session, pass_fds):
|
| 220 |
+
assert start_new_session
|
| 221 |
+
assert len(pass_fds) == 1
|
| 222 |
+
launches.append((command, cwd, env))
|
| 223 |
+
output = Path(command[command.index("--output") + 1])
|
| 224 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 225 |
+
(output / "metrics.json").write_text(
|
| 226 |
+
json.dumps({"id": "fixture", "events": [{"seconds": .6}]}), encoding="utf-8"
|
| 227 |
+
)
|
| 228 |
+
for name in ("generated_abs.npy", "body_pos.csv", "body_quat.csv", "joint_pos.csv"):
|
| 229 |
+
(output / name).write_text("fixture")
|
| 230 |
+
|
| 231 |
+
def poll(self):
|
| 232 |
+
return self.returncode
|
| 233 |
+
|
| 234 |
+
monkeypatch.setattr(module.subprocess, "Popen", CompleteProcess)
|
| 235 |
+
checkpoint = tmp_path / "checkpoints" / "ckpt_5000"
|
| 236 |
+
checkpoint.mkdir(parents=True)
|
| 237 |
+
for name in ("model.safetensors", "hfd_fused_delta_manifest.json"):
|
| 238 |
+
(checkpoint / name).write_text("fixture")
|
| 239 |
+
(checkpoint / "full_duplex_source_boundary.json").write_text(
|
| 240 |
+
json.dumps({"source_group_complete": True})
|
| 241 |
+
)
|
| 242 |
+
case = module.SwaInferenceCase(data_split="val", index=3)
|
| 243 |
+
module.run_dynamic_queue(tmp_path, [case], step=5000, gpus=["2"])
|
| 244 |
+
|
| 245 |
+
result = module.case_result_dir(tmp_path, case, 5000)
|
| 246 |
+
assert (result / ".inferred").is_file()
|
| 247 |
+
assert not (result / ".complete").exists()
|
| 248 |
+
assert not (result / ".failed").exists()
|
| 249 |
+
command, cwd, environment = launches[0]
|
| 250 |
+
assert command[0].endswith("/.venv-psi/bin/python")
|
| 251 |
+
assert command[command.index("--split") + 1] == "val"
|
| 252 |
+
assert command[command.index("--index") + 1] == "3"
|
| 253 |
+
assert environment["CUDA_VISIBLE_DEVICES"] == "2"
|
| 254 |
+
assert cwd == PROJECT_ROOT
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def test_unique_swa_source_keeps_qa_and_explicit_negative_removes_it(tmp_path):
|
| 258 |
+
from psi.runtime.swa_rollout import inplace_future_progress
|
| 259 |
+
body = {
|
| 260 |
+
"source": {
|
| 261 |
+
"source_id": "body",
|
| 262 |
+
"steps": [{"source_id": "body", "phase": "motion", "frame_id": 0,
|
| 263 |
+
"motion_duration_target_seconds": 2.,
|
| 264 |
+
"future_progress": inplace_future_progress(0, 100)}],
|
| 265 |
+
}
|
| 266 |
+
}
|
| 267 |
+
body_path = tmp_path / "body.pt"
|
| 268 |
+
torch.save(body, body_path)
|
| 269 |
+
frontend_root = tmp_path / "frontend-root"
|
| 270 |
+
frontend_dir = frontend_root / "data/frontend"
|
| 271 |
+
frontend_dir.mkdir(parents=True)
|
| 272 |
+
packet = {
|
| 273 |
+
"embeds": torch.tensor([[1.0], [2.0]]),
|
| 274 |
+
"ordinary_audio": torch.tensor([[9.0]]),
|
| 275 |
+
"audio_mask": torch.tensor([False, True]),
|
| 276 |
+
"reply_label": 1,
|
| 277 |
+
"answer_target": "visible answer",
|
| 278 |
+
}
|
| 279 |
+
rows = []
|
| 280 |
+
for source_id, has_question in (("qa", None), ("negative", False)):
|
| 281 |
+
row = {
|
| 282 |
+
"id": source_id,
|
| 283 |
+
"split": "train",
|
| 284 |
+
"path": str(body_path),
|
| 285 |
+
"frontend_root": str(frontend_root),
|
| 286 |
+
}
|
| 287 |
+
if has_question is not None:
|
| 288 |
+
row["swa_has_question"] = has_question
|
| 289 |
+
rows.append(row)
|
| 290 |
+
torch.save({"packets": [packet]}, frontend_dir / f"{source_id}.pt")
|
| 291 |
+
plan = tmp_path / "plan.json"
|
| 292 |
+
plan.write_text(json.dumps(rows), encoding="utf-8")
|
| 293 |
+
|
| 294 |
+
dataset = SwaVisualQaDataset(str(plan), "train", repeat=1)
|
| 295 |
+
qa = dataset[0]["swa_packets"][0]
|
| 296 |
+
negative = dataset[1]["swa_packets"][0]
|
| 297 |
+
assert qa["reply_label"] == 1
|
| 298 |
+
assert qa["answer_target"] == "visible answer"
|
| 299 |
+
assert negative["reply_label"] == 0
|
| 300 |
+
assert negative["answer_target"] == ""
|
| 301 |
+
assert negative["embeds"][1, 0].item() == 9.0
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def test_charades_builder_parses_official_intervals_conservatively():
|
| 305 |
+
module = _load_charades_builder()
|
| 306 |
+
actions = module.parse_actions(
|
| 307 |
+
"c001 1.0 4.5;c002 4.0 3.0;c999 0.0 2.0",
|
| 308 |
+
{"c001": "Someone is opening a door.", "c002": "Someone sits."},
|
| 309 |
+
)
|
| 310 |
+
assert actions == [
|
| 311 |
+
{
|
| 312 |
+
"action_id": "c001",
|
| 313 |
+
"start": 1.0,
|
| 314 |
+
"end": 4.5,
|
| 315 |
+
"label": "Someone is opening a door.",
|
| 316 |
+
}
|
| 317 |
+
]
|
| 318 |
+
assert module.natural_action(actions[0]["label"]) == "opening a door"
|
| 319 |
+
assert module.interval_distance(2.0, actions[0]) == 0.0
|
| 320 |
+
assert module.interval_distance(7.0, actions[0]) == 2.5
|
| 321 |
+
assert module.words("Someone is opening a door") == {"opening", "door"}
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def test_charades_review_filter_requires_support_for_qa_but_keeps_ordinary():
|
| 325 |
+
module = _load_charades_filter()
|
| 326 |
+
candidates = [
|
| 327 |
+
{"id": "yes", "swa_has_question": True},
|
| 328 |
+
{"id": "bad", "swa_has_question": True},
|
| 329 |
+
{"id": "ordinary", "swa_has_question": False},
|
| 330 |
+
]
|
| 331 |
+
reviews = {
|
| 332 |
+
"yes": {
|
| 333 |
+
"model": "qwen3",
|
| 334 |
+
"mode": "verify",
|
| 335 |
+
"decoded": {"supported": True, "answer": "Yes", "reason": "visible"},
|
| 336 |
+
},
|
| 337 |
+
"bad": {
|
| 338 |
+
"model": "qwen3",
|
| 339 |
+
"mode": "verify",
|
| 340 |
+
"decoded": {"supported": False, "answer": "No", "reason": "unclear"},
|
| 341 |
+
},
|
| 342 |
+
}
|
| 343 |
+
accepted, rejected = module.admit(candidates, reviews)
|
| 344 |
+
assert [row["id"] for row in accepted] == ["yes", "ordinary"]
|
| 345 |
+
assert rejected == {"reference_not_visually_supported": 1}
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def test_swa_plan_merge_propagates_explicit_unique_negative_contract():
|
| 349 |
+
module = _load_plan_merger()
|
| 350 |
+
merged = module.merge(
|
| 351 |
+
[
|
| 352 |
+
[{"id": "legacy", "split": "train"}],
|
| 353 |
+
[
|
| 354 |
+
{
|
| 355 |
+
"id": "new-negative",
|
| 356 |
+
"split": "train",
|
| 357 |
+
"question": {"swa_has_question": False},
|
| 358 |
+
}
|
| 359 |
+
],
|
| 360 |
+
]
|
| 361 |
+
)
|
| 362 |
+
assert merged[0]["swa_has_question"] is True
|
| 363 |
+
assert merged[1]["swa_has_question"] is False
|
tests/test_swa_manifest_contract.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import importlib.util
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
_MODULE_PATH = Path(__file__).parents[1] / "scripts" / "data" / "validate_swa_manifest.py"
|
| 12 |
+
_SPEC = importlib.util.spec_from_file_location("validate_swa_manifest", _MODULE_PATH)
|
| 13 |
+
assert _SPEC is not None and _SPEC.loader is not None
|
| 14 |
+
_MODULE = importlib.util.module_from_spec(_SPEC)
|
| 15 |
+
_SPEC.loader.exec_module(_MODULE)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _write_entry(root: Path, split: str, name: str) -> dict[str, str]:
|
| 19 |
+
source = root / "camera8" / "data" / "sources" / f"{name}.pt"
|
| 20 |
+
frontend = root / "camera8" / "data" / "frontend" / f"{name}.pt"
|
| 21 |
+
source.parent.mkdir(parents=True, exist_ok=True)
|
| 22 |
+
frontend.parent.mkdir(parents=True, exist_ok=True)
|
| 23 |
+
torch.save({"source": {"id": name}}, source)
|
| 24 |
+
packet = {
|
| 25 |
+
"ids": torch.arange(4),
|
| 26 |
+
"embeds": torch.zeros(4, 2048, dtype=torch.bfloat16),
|
| 27 |
+
"positions": torch.zeros(3, 4, dtype=torch.long),
|
| 28 |
+
"video_grid": torch.tensor([1, 1, 1]),
|
| 29 |
+
"camera_indices": [0, 1],
|
| 30 |
+
}
|
| 31 |
+
torch.save(
|
| 32 |
+
{
|
| 33 |
+
"packets": [packet],
|
| 34 |
+
"timeline": {"camera_fps": 8.0},
|
| 35 |
+
"frozen_frontend_only": True,
|
| 36 |
+
},
|
| 37 |
+
frontend,
|
| 38 |
+
)
|
| 39 |
+
return {"id": name, "split": split, "path": str(source)}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_swa_plan_checks_split_disjointness_and_frontend(tmp_path: Path):
|
| 43 |
+
plan_path = tmp_path / "source_plan.json"
|
| 44 |
+
plan_path.write_text(
|
| 45 |
+
json.dumps(
|
| 46 |
+
[
|
| 47 |
+
_write_entry(tmp_path, "train", "train_0"),
|
| 48 |
+
_write_entry(tmp_path, "val", "val_0"),
|
| 49 |
+
]
|
| 50 |
+
),
|
| 51 |
+
encoding="utf-8",
|
| 52 |
+
)
|
| 53 |
+
result = _MODULE.validate_manifest(
|
| 54 |
+
plan_path,
|
| 55 |
+
sample_frontends=2,
|
| 56 |
+
require_visual=True,
|
| 57 |
+
)
|
| 58 |
+
assert result["entries"] == 2
|
| 59 |
+
assert result["splits"] == {"train": 1, "val": 1}
|
| 60 |
+
assert result["frontend_packets_checked"] == 2
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_swa_plan_rejects_cross_split_source_leakage(tmp_path: Path):
|
| 64 |
+
entry = _write_entry(tmp_path, "train", "shared_0")
|
| 65 |
+
other = dict(entry, id="shared_0_copy", split="val")
|
| 66 |
+
plan_path = tmp_path / "source_plan.json"
|
| 67 |
+
plan_path.write_text(json.dumps([entry, other]), encoding="utf-8")
|
| 68 |
+
with pytest.raises(ValueError, match="leakage"):
|
| 69 |
+
_MODULE.validate_manifest(plan_path)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_swa_plan_rejects_bad_visual_shape(tmp_path: Path):
|
| 73 |
+
entry = _write_entry(tmp_path, "train", "bad_0")
|
| 74 |
+
source = Path(entry["path"])
|
| 75 |
+
frontend = source.parent.parent / "frontend" / source.name
|
| 76 |
+
frontend.parent.mkdir(parents=True, exist_ok=True)
|
| 77 |
+
torch.save(
|
| 78 |
+
{
|
| 79 |
+
"packets": [
|
| 80 |
+
{
|
| 81 |
+
"ids": torch.arange(4),
|
| 82 |
+
"embeds": torch.zeros(4, 1024),
|
| 83 |
+
"positions": torch.zeros(3, 4, dtype=torch.long),
|
| 84 |
+
"video_grid": torch.tensor([1, 1, 1]),
|
| 85 |
+
"camera_indices": [0],
|
| 86 |
+
}
|
| 87 |
+
]
|
| 88 |
+
},
|
| 89 |
+
frontend,
|
| 90 |
+
)
|
| 91 |
+
plan_path = tmp_path / "source_plan.json"
|
| 92 |
+
plan_path.write_text(json.dumps([entry]), encoding="utf-8")
|
| 93 |
+
with pytest.raises(ValueError, match=r"\[N,2048\]"):
|
| 94 |
+
_MODULE.validate_manifest(plan_path, sample_frontends=1, require_visual=True)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_swa_plan_validates_row_specific_frontend_not_reused_body_frontend(
|
| 98 |
+
tmp_path: Path,
|
| 99 |
+
):
|
| 100 |
+
entry = _write_entry(tmp_path, "train", "shared_body")
|
| 101 |
+
entry["id"] = "unique_qa"
|
| 102 |
+
entry["frontend_root"] = str(tmp_path / "qa_frontends")
|
| 103 |
+
qa_frontend = tmp_path / "qa_frontends/data/frontend/unique_qa.pt"
|
| 104 |
+
qa_frontend.parent.mkdir(parents=True)
|
| 105 |
+
torch.save(
|
| 106 |
+
{
|
| 107 |
+
"packets": [
|
| 108 |
+
{
|
| 109 |
+
"ids": torch.arange(2),
|
| 110 |
+
"embeds": torch.zeros(2, 1024),
|
| 111 |
+
"positions": torch.zeros(3, 2, dtype=torch.long),
|
| 112 |
+
"video_grid": torch.tensor([1, 1, 1]),
|
| 113 |
+
"camera_indices": [0],
|
| 114 |
+
}
|
| 115 |
+
]
|
| 116 |
+
},
|
| 117 |
+
qa_frontend,
|
| 118 |
+
)
|
| 119 |
+
plan_path = tmp_path / "source_plan.json"
|
| 120 |
+
plan_path.write_text(json.dumps([entry]), encoding="utf-8")
|
| 121 |
+
with pytest.raises(ValueError, match=r"\[N,2048\]"):
|
| 122 |
+
_MODULE.validate_manifest(plan_path, sample_frontends=1, require_visual=True)
|
tests/test_swa_native_speech.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Native answer provenance and playback, without loading multi-GB weights."""
|
| 2 |
+
from types import SimpleNamespace
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from psi.runtime.swa_speech import schedule_speech
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def answer(**updates):
|
| 11 |
+
value = dict(seconds=1., samples=7200, audio_path='answer_000_24k.wav',
|
| 12 |
+
playback_buffer_seconds=.2,
|
| 13 |
+
pcm_releases=[dict(sample_start=0, sample_end=4800, available_seconds=1.3),
|
| 14 |
+
dict(sample_start=4800, sample_end=7200, available_seconds=1.4)])
|
| 15 |
+
value.update(updates)
|
| 16 |
+
return value
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_fifo_keeps_all_pcm_and_does_not_backdate_or_overlap_replies():
|
| 20 |
+
segments = schedule_speech([answer(), answer(audio_path='answer_001_24k.wav')])
|
| 21 |
+
assert segments[0]['start'] == 36000
|
| 22 |
+
assert segments[1]['start'] == segments[0]['end']
|
| 23 |
+
assert all(b['start'] >= a['end'] for a, b in zip(segments, segments[1:]))
|
| 24 |
+
assert sum(s['end'] - s['start'] for s in segments) == 14400
|
| 25 |
+
stalled = answer(pcm_releases=[dict(sample_start=0, sample_end=7200, available_seconds=9.)])
|
| 26 |
+
assert schedule_speech([stalled])[0]['start'] >= 220800
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@pytest.mark.parametrize('change', [
|
| 30 |
+
dict(samples=7201),
|
| 31 |
+
dict(pcm_releases=[dict(sample_start=1, sample_end=7200, available_seconds=1.3)]),
|
| 32 |
+
dict(pcm_releases=[dict(sample_start=0, sample_end=7200, available_seconds=.5)]),
|
| 33 |
+
])
|
| 34 |
+
def test_invalid_pcm_is_not_silently_rendered(change):
|
| 35 |
+
with pytest.raises(ValueError):
|
| 36 |
+
schedule_speech([answer(**change)])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_native_voice_consumes_only_arrived_model_tokens(monkeypatch):
|
| 40 |
+
import psi.runtime.native_streaming_speech as module
|
| 41 |
+
class Learner:
|
| 42 |
+
def __init__(self, *_):
|
| 43 |
+
self.device = 'cpu'
|
| 44 |
+
self.done = False
|
| 45 |
+
self.thinker = SimpleNamespace(config=SimpleNamespace(eos_token_id=99))
|
| 46 |
+
self.i = 0
|
| 47 |
+
def pop(self):
|
| 48 |
+
self.i += 1
|
| 49 |
+
if self.i == 3:
|
| 50 |
+
self.done = True
|
| 51 |
+
return None
|
| 52 |
+
# Deliberately extreme learned features must NOT reach frozen voice.
|
| 53 |
+
return torch.tensor([[self.i]]), torch.full((1, 1, 2), -999.), torch.full((1, 1, 2), -888.)
|
| 54 |
+
def result(self):
|
| 55 |
+
return dict(ids=[1, 2, 99], text='model words')
|
| 56 |
+
monkeypatch.setattr(module, 'IncrementalAnswer', Learner)
|
| 57 |
+
seen = []
|
| 58 |
+
class Voice:
|
| 59 |
+
def get_input_embeddings(self):
|
| 60 |
+
return lambda ids: ids.float().unsqueeze(-1).expand(-1, -1, 2)
|
| 61 |
+
def model(self, **kwargs):
|
| 62 |
+
seen.append(kwargs['inputs_embeds'].clone())
|
| 63 |
+
length = kwargs['attention_mask'].shape[1]
|
| 64 |
+
return SimpleNamespace(last_hidden_state=kwargs['inputs_embeds'] + 10,
|
| 65 |
+
past_key_values=SimpleNamespace(get_seq_length=lambda: length))
|
| 66 |
+
model = SimpleNamespace(vlm_processor=SimpleNamespace(tokenizer=SimpleNamespace(
|
| 67 |
+
apply_chat_template=lambda *args, **kwargs: [7, 8])))
|
| 68 |
+
branch = module.NativeTextConditionAnswer(model, None, Voice())
|
| 69 |
+
assert len(seen) == 1
|
| 70 |
+
a = branch.pop()
|
| 71 |
+
assert a[2][0, 0, 0] == 11
|
| 72 |
+
branch.pop()
|
| 73 |
+
assert branch.pop() is None
|
| 74 |
+
assert branch.result()['voice_arrived_ids'] == [1, 2]
|
| 75 |
+
assert [x[0, :, 0].tolist() for x in seen] == [[7., 8.], [1.], [2.]]
|
tests/test_swa_pipeline_queue.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
SCRIPTS = Path(__file__).resolve().parents[1] / "scripts/data"
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def load(name):
|
| 11 |
+
sys.path.insert(0, str(SCRIPTS))
|
| 12 |
+
spec = importlib.util.spec_from_file_location(name, SCRIPTS / f"{name}.py")
|
| 13 |
+
module = importlib.util.module_from_spec(spec)
|
| 14 |
+
spec.loader.exec_module(module)
|
| 15 |
+
return module
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def queue(tmp_path, rows, **kw):
|
| 19 |
+
return load("swa_pipeline_queue").ready_batches(rows,
|
| 20 |
+
output_path=lambda r: tmp_path / "outputs" / f"{r}.json",
|
| 21 |
+
input_paths=lambda r: [tmp_path / "inputs" / f"{r}.json"], batch_size=2, **kw)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def publish(tmp_path, folder, names):
|
| 25 |
+
path = tmp_path / folder
|
| 26 |
+
path.mkdir(exist_ok=True)
|
| 27 |
+
for name in names:
|
| 28 |
+
(path / f"{name}.json").write_text("{}")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_consume_ready_before_upstream_finishes_and_resume(tmp_path):
|
| 32 |
+
publish(tmp_path, "inputs", [0, 1])
|
| 33 |
+
publish(tmp_path, "outputs", [0])
|
| 34 |
+
gen = queue(tmp_path, [0, 1, 2], follow=True, upstream_done=[tmp_path / "done"])
|
| 35 |
+
assert next(gen) == [1]
|
| 36 |
+
publish(tmp_path, "inputs", [2])
|
| 37 |
+
(tmp_path / "done").touch()
|
| 38 |
+
assert next(gen) == [2]
|
| 39 |
+
with pytest.raises(StopIteration):
|
| 40 |
+
next(gen)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_partial_receipt_is_never_consumed(tmp_path):
|
| 44 |
+
publish(tmp_path, "inputs", [1])
|
| 45 |
+
(tmp_path / "inputs/2.json.partial").write_text("{")
|
| 46 |
+
gen = queue(tmp_path, [1, 2])
|
| 47 |
+
assert next(gen) == [1]
|
| 48 |
+
with pytest.raises(RuntimeError, match="Upstream inputs missing"):
|
| 49 |
+
next(gen)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_finished_upstream_missing_receipt_fails_closed(tmp_path):
|
| 53 |
+
(tmp_path / "done").touch()
|
| 54 |
+
with pytest.raises(RuntimeError, match="Upstream inputs missing"):
|
| 55 |
+
list(queue(tmp_path, [1], follow=True, upstream_done=[tmp_path / "done"]))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_corrupt_receipt_not_silently_skipped(tmp_path):
|
| 59 |
+
# Queue ensures atomic publication; consumers must still parse/hash-check.
|
| 60 |
+
publish(tmp_path, "inputs", [1])
|
| 61 |
+
(tmp_path / "inputs/1.json").write_text("broken")
|
| 62 |
+
assert list(queue(tmp_path, [1])) == [[1]]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_two_independent_reviews_required(tmp_path):
|
| 66 |
+
m = load("swa_pipeline_queue")
|
| 67 |
+
publish(tmp_path, "asr", [1, 2])
|
| 68 |
+
publish(tmp_path, "visual", [1])
|
| 69 |
+
gen = m.ready_batches([1, 2], output_path=lambda r: tmp_path / "out" / str(r),
|
| 70 |
+
input_paths=lambda r: [tmp_path / "asr" / f"{r}.json", tmp_path / "visual" / f"{r}.json"],
|
| 71 |
+
batch_size=2, follow=True, upstream_done=[tmp_path / "done"])
|
| 72 |
+
assert next(gen) == [1]
|
| 73 |
+
publish(tmp_path, "visual", [2])
|
| 74 |
+
assert next(gen) == [2]
|
| 75 |
+
assert list(gen) == []
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_timeout_without_producer_progress(tmp_path, monkeypatch):
|
| 79 |
+
m = load("swa_pipeline_queue")
|
| 80 |
+
ticks = iter([0., 2.])
|
| 81 |
+
monkeypatch.setattr(m.time, "monotonic", lambda: next(ticks))
|
| 82 |
+
with pytest.raises(TimeoutError):
|
| 83 |
+
list(m.ready_batches([1], output_path=lambda r: tmp_path / "out", input_paths=lambda r: [tmp_path / "missing"],
|
| 84 |
+
batch_size=1, follow=True, upstream_done=[tmp_path / "done"], timeout_seconds=1))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_follow_requires_completion_markers(tmp_path):
|
| 88 |
+
with pytest.raises(ValueError, match="completion markers"):
|
| 89 |
+
list(queue(tmp_path, [1], follow=True))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_duplicate_outputs_fail_closed(tmp_path):
|
| 93 |
+
with pytest.raises(ValueError, match="Duplicate"):
|
| 94 |
+
list(queue(tmp_path, [1, 1]))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_no_per_row_stat_storm(tmp_path, monkeypatch):
|
| 98 |
+
publish(tmp_path, "inputs", range(100))
|
| 99 |
+
def forbidden(*args, **kwargs):
|
| 100 |
+
raise AssertionError("Per-row stat would overload shared filesystem")
|
| 101 |
+
monkeypatch.setattr(Path, "exists", forbidden)
|
| 102 |
+
monkeypatch.setattr(Path, "is_file", forbidden)
|
| 103 |
+
assert len(list(queue(tmp_path, list(range(100))))) == 50
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_dag_overlaps_independent_stages_without_global_barrier():
|
| 107 |
+
m = load("run_swa_vqav2_pipeline")
|
| 108 |
+
assert m.launchable(set(), set(), 0, True) == ["voices", "asr", "review", "encode"]
|
| 109 |
+
assert m.launchable(set(), set(), 0, False) == ["voices", "asr"]
|
| 110 |
+
assert m.launchable(set(), set(), 0, True, overlap_all=False) == ["voices", "asr"]
|
| 111 |
+
started = {("voices", 0), ("asr", 0)}
|
| 112 |
+
# GPU0 starts large downstream models before other TTS shards finish.
|
| 113 |
+
assert m.launchable({("voices", 0)}, started, 0, True, overlap_all=False) == ["review", "encode"]
|
| 114 |
+
assert m.launchable(set(), {("voices", 0), ("asr", 0), ("review", 0), ("encode", 0)}, 0, True) == []
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_memory_preflight_rejects_conflicting_jobs(monkeypatch):
|
| 118 |
+
m = load("run_swa_vqav2_pipeline")
|
| 119 |
+
fractions = dict(voices=.45, asr=.04, review=.20, encode=.15)
|
| 120 |
+
monkeypatch.setattr(m.subprocess, "check_output", lambda *a, **kw: "143771, 125939\n")
|
| 121 |
+
m.check_memory(["0"], fractions, True)
|
| 122 |
+
monkeypatch.setattr(m.subprocess, "check_output", lambda *a, **kw: "143771, 10000\n")
|
| 123 |
+
with pytest.raises(RuntimeError, match="free.*budget"):
|
| 124 |
+
m.check_memory(["0"], fractions, True)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def test_streaming_and_serial_cover_same_rows_exactly_once(tmp_path):
|
| 128 |
+
rows = list(range(9))
|
| 129 |
+
publish(tmp_path, "inputs", [8, 0, 3])
|
| 130 |
+
gen = queue(tmp_path, rows, follow=True, upstream_done=[tmp_path / "done"])
|
| 131 |
+
streamed = next(gen) + next(gen)
|
| 132 |
+
publish(tmp_path, "inputs", [1, 2, 4, 5, 6, 7])
|
| 133 |
+
(tmp_path / "done").touch()
|
| 134 |
+
streamed += [r for batch in gen for r in batch]
|
| 135 |
+
serial = [r for batch in queue(tmp_path, rows) for r in batch]
|
| 136 |
+
assert sorted(streamed) == serial == rows
|
| 137 |
+
assert len(set(streamed)) == len(rows)
|
tests/test_swa_regressions.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regressions for actual module devices and modality-aware source prefetch."""
|
| 2 |
+
from types import SimpleNamespace
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from psi.runtime.motion_rollout import _flow_action, _model_device
|
| 8 |
+
from psi.trainers.posttrain_full_duplex import SourceBatchingLoader
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@pytest.mark.parametrize("dynamic", [False, True])
|
| 12 |
+
@pytest.mark.parametrize("pattern", ["aaaaaaaa", "avavavav", "aavvaaav"])
|
| 13 |
+
def test_prefetch_never_truncates_at_modality_seams(dynamic, pattern):
|
| 14 |
+
rows = [
|
| 15 |
+
{"sources": [{"source_id": str(i), "source_modality": mode,
|
| 16 |
+
"steps": list(range(i % 5 + 1))}]}
|
| 17 |
+
for i, mode in enumerate(mode for mode in pattern for _ in range(2))
|
| 18 |
+
]
|
| 19 |
+
def loader(prefetch):
|
| 20 |
+
return SourceBatchingLoader(
|
| 21 |
+
rows, batch_size=2, length_lookahead_batches=4,
|
| 22 |
+
dynamic_source_refill=dynamic, prefetch_source_batches=prefetch,
|
| 23 |
+
)
|
| 24 |
+
direct, prefetched = list(loader(False)), list(loader(True))
|
| 25 |
+
assert prefetched == direct
|
| 26 |
+
assert sorted(s["source_id"] for b in prefetched for s in b["sources"]) == sorted(
|
| 27 |
+
row["sources"][0]["source_id"] for row in rows)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_prefetch_empty_and_producer_error_are_not_silently_dropped():
|
| 31 |
+
loader = SourceBatchingLoader([], batch_size=2, dynamic_source_refill=True,
|
| 32 |
+
prefetch_source_batches=True)
|
| 33 |
+
assert list(loader) == []
|
| 34 |
+
class Broken(list):
|
| 35 |
+
def __iter__(self):
|
| 36 |
+
raise ValueError("source construction failed")
|
| 37 |
+
loader.source_loader = Broken([None] * 4)
|
| 38 |
+
with pytest.raises(ValueError, match="source construction failed"):
|
| 39 |
+
list(loader)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_solver_uses_module_device_and_preserves_per_slot_rtc():
|
| 43 |
+
class Scheduler:
|
| 44 |
+
def set_timesteps(self, count, device):
|
| 45 |
+
self.timesteps = torch.linspace(1, .1, count, device=device)
|
| 46 |
+
def step(self, *, model_output, timestep, sample):
|
| 47 |
+
return SimpleNamespace(prev_sample=sample + .1)
|
| 48 |
+
class Model(torch.nn.Module):
|
| 49 |
+
action_dim = 4
|
| 50 |
+
def __init__(self):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.weight = torch.nn.Parameter(torch.ones(1))
|
| 53 |
+
self.noise_scheduler = Scheduler()
|
| 54 |
+
self.calls = []
|
| 55 |
+
def forward_action_conditioned(self, **kwargs):
|
| 56 |
+
self.calls.append((kwargs["action_samples"].clone(), kwargs["timestep"].clone()))
|
| 57 |
+
return torch.zeros_like(kwargs["action_samples"])
|
| 58 |
+
model = Model()
|
| 59 |
+
assert not hasattr(model, "device")
|
| 60 |
+
prefix = torch.full((2, 10, 4), 123.)
|
| 61 |
+
output = _flow_action(
|
| 62 |
+
model, None, known_prefix=prefix, prefix_present=torch.tensor([True, False]),
|
| 63 |
+
states=torch.zeros(2, 1, 4), future_progress=torch.zeros(2, 30, 5),
|
| 64 |
+
num_inference_steps=10, generator=torch.Generator().manual_seed(42),
|
| 65 |
+
)
|
| 66 |
+
assert output.shape == (2, 30, 4) and len(model.calls) == 10
|
| 67 |
+
torch.testing.assert_close(output[0, :10], prefix[0])
|
| 68 |
+
assert not torch.equal(output[1, :10], prefix[1])
|
| 69 |
+
for samples, times in model.calls:
|
| 70 |
+
torch.testing.assert_close(samples[0, :10], prefix[0])
|
| 71 |
+
assert times[0, :10].eq(0).all() and times[1].gt(0).all()
|
| 72 |
+
model.device = torch.device("cuda:99") # obsolete ad-hoc attribute must not win
|
| 73 |
+
assert _model_device(model) == torch.device("cpu")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_removed_history_still_loads_old_config_but_cannot_silently_train():
|
| 77 |
+
from psi.config.train.posttrain_full_duplex_audio_command_psi0_config import FullDuplexTrainConfig
|
| 78 |
+
from psi.trainers.posttrain_full_duplex import PosttrainFullDuplexTrainer
|
| 79 |
+
legacy = FullDuplexTrainConfig(swa_generated_history_probability=.25)
|
| 80 |
+
trainer = PosttrainFullDuplexTrainer.__new__(PosttrainFullDuplexTrainer)
|
| 81 |
+
trainer.cfg = SimpleNamespace(train=legacy)
|
| 82 |
+
with pytest.raises(ValueError, match="generated-history training was removed"):
|
| 83 |
+
trainer.init_models()
|
tests/test_swa_scaleup.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_script(name):
|
| 12 |
+
sys.path.insert(0, str(ROOT / "scripts/data"))
|
| 13 |
+
spec = importlib.util.spec_from_file_location(name, ROOT / "scripts/data" / f"{name}.py")
|
| 14 |
+
module = importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
|
| 15 |
+
return module
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_vqa_candidate_gate_requires_nine_human_votes_and_visual_question():
|
| 19 |
+
m = load_script("prepare_swa_vqav2")
|
| 20 |
+
questions = [{"question_id": i, "image_id": i, "question": q} for i, q in enumerate(
|
| 21 |
+
["What color is this shirt?", "What color is this shirt?", "Why is she wearing this shirt?"])]
|
| 22 |
+
annotations = [{"question_id": i, "image_id": i, "multiple_choice_answer": "red", "answer_type": "other",
|
| 23 |
+
"answers": [{"answer": "red"}] * n + [{"answer": "blue"}] * (10 - n)}
|
| 24 |
+
for i, n in enumerate([9, 8, 10])]
|
| 25 |
+
rows, rejected = m.select(questions, annotations, split="train", limit=10)
|
| 26 |
+
assert [r["question_id"] for r in rows] == [0]
|
| 27 |
+
assert rejected["human_agreement_below_threshold"] == 1
|
| 28 |
+
assert rejected["question_not_conservative_visible_state"] == 1
|
| 29 |
+
assert not m.conservative_question("Can this boy get injured easily?")
|
| 30 |
+
assert not m.conservative_question("Was this taken in the United States?")
|
| 31 |
+
assert not m.conservative_question("Is this scene in Paris?")
|
| 32 |
+
assert m.conservative_question("What is the horse doing?")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_speech_gate_does_not_hide_omitted_words():
|
| 36 |
+
m = load_script("encode_swa_vqav2")
|
| 37 |
+
assert m.canonical_speech("Are there two dogs?") == m.canonical_speech("Are there 2 dogs.")
|
| 38 |
+
assert m.canonical_speech("Is the dog red?") != m.canonical_speech("Is dog red?")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_camera_packet_grouping_causal_and_same_cadence():
|
| 42 |
+
m = load_script("encode_swa_vqav2")
|
| 43 |
+
available, groups = m.camera_groups(45)
|
| 44 |
+
assert groups[0] == [0, 1, 2, 3, 4]
|
| 45 |
+
assert set(map(len, groups)) == {3, 4, 5}
|
| 46 |
+
flat = [i for group in groups for i in group]
|
| 47 |
+
assert flat == list(range(len(flat)))
|
| 48 |
+
assert all(max(group) / 8 <= deadline + 1e-6 for group, deadline in zip(groups, available))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_factorized_packets_reconstruct_without_mutating_shared_bases(tmp_path):
|
| 52 |
+
from psi.data.seed.swa_frontend import load_swa_frontend
|
| 53 |
+
packet = {"embeds": torch.tensor([[0., 0.], [1., 1.]]), "visual_mask": torch.tensor([True, False]),
|
| 54 |
+
"audio_mask": torch.tensor([False, True]), "camera_indices": [0, 1, 2], "answer_target": ""}
|
| 55 |
+
base = tmp_path / "base.pt";visual = tmp_path / "visual.pt";front = tmp_path / "front.pt"
|
| 56 |
+
torch.save({"packets": [packet, packet], "system": "test"}, base)
|
| 57 |
+
torch.save({"3": torch.tensor([[3., 3.]])}, visual)
|
| 58 |
+
torch.save({"format": "static_factorized_v1", "base_frontend_path": str(base), "visual_features_path": str(visual),
|
| 59 |
+
"audio_patches": {1: torch.tensor([[4., 4.]])}, "reply_windows": [1], "answer_target": "yes", "timeline": {}}, front)
|
| 60 |
+
first = load_swa_frontend(front)["packets"]
|
| 61 |
+
assert first[0]["embeds"].tolist() == [[3., 3.], [1., 1.]]
|
| 62 |
+
assert first[1]["embeds"].tolist() == [[3., 3.], [4., 4.]]
|
| 63 |
+
assert first[0]["answer_target"] == "" and first[1]["answer_target"] == "yes"
|
| 64 |
+
first[0]["embeds"].zero_()
|
| 65 |
+
assert load_swa_frontend(front)["packets"][0]["embeds"].tolist() == [[3., 3.], [1., 1.]]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_swa_eval_indices_cover_entire_manifest_without_repeats():
|
| 69 |
+
from psi.trainers.swa_validation import validation_indices
|
| 70 |
+
assert validation_indices(0) == []
|
| 71 |
+
assert validation_indices(3) == [0, 1, 2]
|
| 72 |
+
indices = validation_indices(1000)
|
| 73 |
+
assert len(indices) == len(set(indices)) == 16
|
| 74 |
+
assert indices[-1] > 900
|
tests/test_swa_speech_failures.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from concurrent.futures import Future, ThreadPoolExecutor
|
| 2 |
+
import pytest
|
| 3 |
+
from psi.runtime.swa_speech import SwaSpeechWorker, IncompleteSpeechError
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def worker(error):
|
| 7 |
+
result=SwaSpeechWorker.__new__(SwaSpeechWorker)
|
| 8 |
+
result.pool=ThreadPoolExecutor(1)
|
| 9 |
+
good,bad=Future(),Future()
|
| 10 |
+
good.set_result({'text':'complete answer'})
|
| 11 |
+
bad.set_exception(error)
|
| 12 |
+
result.jobs=[good,bad]
|
| 13 |
+
return result
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_keep_completed_answers_but_explicitly_report_codec_limit():
|
| 17 |
+
speech=worker(IncompleteSpeechError('codec limit'))
|
| 18 |
+
assert speech.finish(allow_incomplete=True)==[{'text':'complete answer'}]
|
| 19 |
+
assert speech.failures==[{'ordinal':1,'error':'codec limit'}]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_legacy_strict_behavior_remains():
|
| 23 |
+
speech=worker(IncompleteSpeechError('codec limit'))
|
| 24 |
+
with pytest.raises(IncompleteSpeechError):speech.finish()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_model_or_cache_failure_is_never_swallowed():
|
| 28 |
+
speech=worker(RuntimeError('bad KV'))
|
| 29 |
+
with pytest.raises(RuntimeError,match='bad KV'):speech.finish(allow_incomplete=True)
|
tests/test_third_party_dataset.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import json
|
| 3 |
+
import random
|
| 4 |
+
import wave
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from psi.data.seed.third_party_dataset import contained, file_hash, replace_microphone
|
| 11 |
+
from psi.data.seed.live_multimodal_overlay import continuous_audio, interaction_task
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def fixture(tmp_path):
|
| 15 |
+
pcm = np.arange(16000, dtype=np.int16)
|
| 16 |
+
audio = tmp_path / 'input.wav'
|
| 17 |
+
with wave.open(str(audio), 'wb') as f:
|
| 18 |
+
f.setnchannels(1); f.setsampwidth(2); f.setframerate(16000)
|
| 19 |
+
f.writeframes(pcm.tobytes())
|
| 20 |
+
steps = [dict(step_index=i, states=np.zeros(36), control_label=1,
|
| 21 |
+
update_semantic_cache=i in (0,20), semantic_window_index=i//20)
|
| 22 |
+
for i in range(21)]
|
| 23 |
+
item = dict(steps=steps, microphone_speech_intervals=[dict(start_seconds=.2,end_seconds=.4)],
|
| 24 |
+
interaction_mode='turn-taking')
|
| 25 |
+
path = tmp_path/'timeline.npz'
|
| 26 |
+
np.savez(path, states=np.zeros((21,36)), control_label=np.ones(21,dtype=np.uint8))
|
| 27 |
+
recipe = dict(session_id='example', session_type='mixed_short', background_language='en',
|
| 28 |
+
interference_intervals=[dict(start_seconds=.1,end_seconds=.7)],
|
| 29 |
+
timeline=dict(path=path.name,file_sha256=file_hash(path),action_steps=21),
|
| 30 |
+
audio=dict(path=audio.name,sha256=file_hash(audio),sample_rate=16000,channels=1,
|
| 31 |
+
sample_width_bytes=2,window_samples=9600,stride_samples=6400,
|
| 32 |
+
window_count=2,sample_count=16000),
|
| 33 |
+
supervision_targets=[], target_speech_events=[dict(start_sample=3200,end_sample=6400)])
|
| 34 |
+
return item,recipe,pcm
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_exact_pcm_overlap_and_current_pose_preserved(tmp_path):
|
| 38 |
+
item,recipe,pcm=fixture(tmp_path)
|
| 39 |
+
item['steps'][0]['states'][15]=.8 # Latest raised-arm pose need not match old archive.
|
| 40 |
+
actual=replace_microphone(item,recipe,tmp_path)
|
| 41 |
+
np.testing.assert_array_equal(continuous_audio(actual),pcm.astype(np.float32)/32768.)
|
| 42 |
+
assert actual['steps'][0]['states'][15]==.8
|
| 43 |
+
assert interaction_task(actual)=='third-party'
|
| 44 |
+
assert actual['interaction_mode']=='turn-taking'
|
| 45 |
+
assert 'audio_waveform' not in actual['steps'][1]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_reject_timing_drift(tmp_path):
|
| 49 |
+
item,recipe,_=fixture(tmp_path)
|
| 50 |
+
item['steps'][3]['control_label']=0
|
| 51 |
+
with pytest.raises(ValueError,match='timing/supervision drift'):
|
| 52 |
+
replace_microphone(item,recipe,tmp_path)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_reject_changed_speech_and_audio(tmp_path):
|
| 56 |
+
item,recipe,_=fixture(tmp_path)
|
| 57 |
+
item['microphone_speech_intervals'][0]['start_seconds']=.3
|
| 58 |
+
with pytest.raises(ValueError,match='speech shifted'):
|
| 59 |
+
replace_microphone(item,recipe,tmp_path)
|
| 60 |
+
item['microphone_speech_intervals'][0]['start_seconds']=.2
|
| 61 |
+
recipe['audio']['sha256']='bad'
|
| 62 |
+
with pytest.raises(ValueError,match='audio corrupted'):
|
| 63 |
+
replace_microphone(item,recipe,tmp_path)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_reject_escape(tmp_path):
|
| 67 |
+
with pytest.raises(ValueError,match='escapes'):
|
| 68 |
+
contained(tmp_path,'../outside.wav')
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_appended_source_keeps_rng_and_base_membership(monkeypatch,tmp_path):
|
| 72 |
+
import psi.data.seed.third_party_dataset as module
|
| 73 |
+
recipe=dict(session_id='x',session_type='single_short',timeline_seed=123,
|
| 74 |
+
composition_variant_id=4,composition_salt=5,
|
| 75 |
+
turns=[dict(row_id=1,motion_filename='motion',audio_dir='audio',voice_name='voice',
|
| 76 |
+
motion_dir=str(tmp_path),motion_sha256='unused')],
|
| 77 |
+
timeline=dict(action_steps=31))
|
| 78 |
+
class Raw:
|
| 79 |
+
records=[dict(row_id=1,filename='motion',audio_dir='audio',motion_dir=str(tmp_path))]
|
| 80 |
+
sessions=((records[0],),)
|
| 81 |
+
def __len__(self):return 1
|
| 82 |
+
def __getitem__(self,index):return {'original':index}
|
| 83 |
+
def estimated_stream_steps(self,index):return 10
|
| 84 |
+
def _build_source(self,index):return {'random':random.random()}
|
| 85 |
+
monkeypatch.setattr(module,'read_recipes',lambda *a:(recipe,))
|
| 86 |
+
monkeypatch.setattr(module,'replace_microphone',lambda item,*a:item)
|
| 87 |
+
monkeypatch.setattr(module,'verify_primitive',lambda *a:None)
|
| 88 |
+
for name in ('joint_pos.csv','body_pos.csv','body_quat.csv'):
|
| 89 |
+
(tmp_path/name).touch()
|
| 90 |
+
raw=Raw(); ds=module.ThirdPartyAugmentedDataset(raw,tmp_path,'unused','train')
|
| 91 |
+
state=random.getstate()
|
| 92 |
+
assert ds[1]==ds[1]
|
| 93 |
+
assert random.getstate()==state
|
| 94 |
+
assert ds[0]==raw[0]
|
| 95 |
+
assert len(raw.sessions)==1 and len(ds)==2
|
| 96 |
+
assert ds.estimated_stream_steps(1)==31
|
tests/test_training_dashboard.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import pytest
|
| 4 |
+
from psi.runtime.local_metrics import append_metrics
|
| 5 |
+
from scripts.training_dashboard import media_path, snapshot
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_metrics_sparse_and_eval(tmp_path):
|
| 9 |
+
append_metrics(tmp_path, 1, {"train/loss": 1.})
|
| 10 |
+
assert not (tmp_path / "dashboard_metrics.jsonl").exists()
|
| 11 |
+
append_metrics(tmp_path, 20, {"train/loss": .5, "bad": float("nan")})
|
| 12 |
+
append_metrics(tmp_path, 21, {"eval/loss": .4})
|
| 13 |
+
rows = [json.loads(x) for x in (tmp_path / "dashboard_metrics.jsonl").read_text().splitlines()]
|
| 14 |
+
assert [r["step"] for r in rows] == [20, 21]
|
| 15 |
+
assert "bad" not in rows[0]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_sparse_control_and_qa_not_lost_between_twenty_steps(tmp_path):
|
| 19 |
+
append_metrics(tmp_path, 21, {"train/control_accuracy": .7})
|
| 20 |
+
append_metrics(tmp_path, 22, {"train/swa_qa_target_tokens": 8., "train/swa_qa_token_accuracy": .5})
|
| 21 |
+
append_metrics(tmp_path, 40, {"train/swa_qa_target_tokens": 0., "train/swa_qa_token_accuracy": 0.})
|
| 22 |
+
rows = [json.loads(x) for x in (tmp_path / "dashboard_metrics.jsonl").read_text().splitlines()]
|
| 23 |
+
assert [r["step"] for r in rows] == [21, 22, 40]
|
| 24 |
+
assert "train/swa_qa_token_accuracy" not in rows[-1]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_metrics_io_failure_does_not_abort(tmp_path):
|
| 28 |
+
with pytest.warns(UserWarning):
|
| 29 |
+
append_metrics(tmp_path / "missing", 20, {"train/loss": .5})
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_media_scope(tmp_path):
|
| 33 |
+
with pytest.raises(ValueError):
|
| 34 |
+
media_path(tmp_path, "../.env")
|
| 35 |
+
with pytest.raises(ValueError):
|
| 36 |
+
media_path(tmp_path, "checkpoints/model.safetensors")
|
| 37 |
+
d = tmp_path / "unified_overlay/ckpt_5/val/01_turn-taking"
|
| 38 |
+
d.mkdir(parents=True)
|
| 39 |
+
p = d / "reference_motion_with_audio.mp4"
|
| 40 |
+
p.touch()
|
| 41 |
+
with pytest.raises(ValueError):
|
| 42 |
+
media_path(tmp_path, str(p.relative_to(tmp_path)))
|
| 43 |
+
(d / ".rendered").touch()
|
| 44 |
+
assert media_path(tmp_path, str(p.relative_to(tmp_path))) == p
|
| 45 |
+
outside = tmp_path.parent / "outside_dashboard_media"
|
| 46 |
+
outside.mkdir(exist_ok=True)
|
| 47 |
+
(tmp_path / "escape").symlink_to(outside, target_is_directory=True)
|
| 48 |
+
with pytest.raises(ValueError):
|
| 49 |
+
media_path(tmp_path, "escape/reference_motion_with_audio.mp4")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_validation_curves_use_held_out_rollouts(tmp_path, monkeypatch):
|
| 53 |
+
import scripts.training_dashboard as dashboard
|
| 54 |
+
monkeypatch.setattr(dashboard.subprocess, "check_output", lambda *a, **k: "gpu")
|
| 55 |
+
monkeypatch.setattr(dashboard, "WANDB_ROWS", [])
|
| 56 |
+
for split in ("train", "val"):
|
| 57 |
+
d = tmp_path / "unified_overlay/ckpt_5000" / split / "01_turn-taking"
|
| 58 |
+
d.mkdir(parents=True)
|
| 59 |
+
(d / "metrics.json").write_text(json.dumps({"control_accuracy": .7,
|
| 60 |
+
"body_metrics": {"joint_rmse_rad": .1, "joint_velocity_error_rad_s": .8}}))
|
| 61 |
+
rows = snapshot(tmp_path)["validation_rows"]
|
| 62 |
+
assert len(rows) == 1
|
| 63 |
+
assert rows[0] == dict(step=5000, case="01_turn-taking", control_accuracy=.7,
|
| 64 |
+
joint_rmse_rad=.1, joint_velocity_error_rad_s=.8)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_remote_dashboard_never_reads_local_gpu(tmp_path, monkeypatch):
|
| 68 |
+
import scripts.training_dashboard as dashboard
|
| 69 |
+
def forbidden(*args, **kwargs):
|
| 70 |
+
raise AssertionError("Remote run must not read local GPU status")
|
| 71 |
+
monkeypatch.setattr(dashboard.subprocess, "check_output", forbidden)
|
| 72 |
+
assert "远端 DLC" in snapshot(tmp_path, remote=True)["gpu"]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_remote_render_requires_valid_receipt_and_video(tmp_path, monkeypatch):
|
| 76 |
+
import scripts.training_dashboard as dashboard
|
| 77 |
+
path = tmp_path / "reference_motion_with_audio.mp4"
|
| 78 |
+
path.write_bytes(b"test")
|
| 79 |
+
assert not dashboard.render_ready(path, remote=True)
|
| 80 |
+
meta = tmp_path / "infer_meta.json"
|
| 81 |
+
meta.write_text(json.dumps(dict(swa_render_version=2, total_frames=30)))
|
| 82 |
+
monkeypatch.setattr(dashboard.subprocess, "check_output", lambda *a, **k: '{"streams":[{"nb_frames":"30"}]}')
|
| 83 |
+
assert dashboard.render_ready(path, remote=True)
|
| 84 |
+
assert not dashboard.render_ready(path)
|
| 85 |
+
assert dashboard.media_path(tmp_path, path.name, remote=True) == path
|
| 86 |
+
meta.write_text(json.dumps(dict(swa_render_version=2, total_frames=31)))
|
| 87 |
+
assert not dashboard.render_ready(path, remote=True)
|
| 88 |
+
with pytest.raises(ValueError):
|
| 89 |
+
dashboard.media_path(tmp_path, "../reference_motion_with_audio.mp4", remote=True)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_dashboard_javascript_parses():
|
| 93 |
+
import shutil
|
| 94 |
+
import subprocess
|
| 95 |
+
from scripts.training_dashboard import PAGE
|
| 96 |
+
if not shutil.which("node"):
|
| 97 |
+
pytest.skip("node unavailable")
|
| 98 |
+
script = PAGE.split("<script>")[1].split("</script>")[0]
|
| 99 |
+
subprocess.run(["node", "--check"], input=script, text=True, check=True, capture_output=True)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_video_catalog_separates_checkpoint_split_task_kind(tmp_path, monkeypatch):
|
| 103 |
+
import scripts.training_dashboard as dashboard
|
| 104 |
+
monkeypatch.setattr(dashboard.subprocess, 'check_output', lambda *a, **k: 'gpu')
|
| 105 |
+
monkeypatch.setattr(dashboard, 'WANDB_ROWS', [])
|
| 106 |
+
for step, split, task, kind, rendered in [
|
| 107 |
+
(10, 'train', '01_turn-taking', 'image', True),
|
| 108 |
+
(10, 'val', '02_interruption/stop', 'video', True),
|
| 109 |
+
(20, 'val', '03_backchannel', 'video', False),
|
| 110 |
+
]:
|
| 111 |
+
folder = tmp_path / f'unified_overlay/ckpt_{step}' / split / task
|
| 112 |
+
folder.mkdir(parents=True)
|
| 113 |
+
(folder / 'metrics.json').write_text(json.dumps(dict(
|
| 114 |
+
overlay={kind+'_path': '/input', 'question': '<b>question</b>', 'answer': 'GT'},
|
| 115 |
+
answers=[{'text': 'prediction'}], control_accuracy=.8)))
|
| 116 |
+
(folder / 'reference_motion_with_audio.mp4').touch()
|
| 117 |
+
if rendered:
|
| 118 |
+
(folder / '.rendered').touch()
|
| 119 |
+
result = dashboard.snapshot(tmp_path)
|
| 120 |
+
assert result['video_catalog'] == [dict(step=20, inferred=1, rendered=0),
|
| 121 |
+
dict(step=10, inferred=2, rendered=2)]
|
| 122 |
+
assert len(result['videos']) == 2
|
| 123 |
+
assert {(v['split'],v['task'],v['visual_kind']) for v in result['videos']} == {
|
| 124 |
+
('train','01_turn-taking','image'), ('val','02_interruption/stop','video')}
|
| 125 |
+
assert all(v['question'] == '<b>question</b>' for v in result['videos'])
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_video_filter_javascript():
|
| 129 |
+
import shutil, subprocess
|
| 130 |
+
from scripts.training_dashboard import PAGE
|
| 131 |
+
if not shutil.which('node'):
|
| 132 |
+
pytest.skip('node unavailable')
|
| 133 |
+
function = 'function videoSelection'+PAGE.split('function videoSelection',1)[1].split('\nfunction options',1)[0]
|
| 134 |
+
js = function + '''
|
| 135 |
+
const assert=require('node:assert/strict');
|
| 136 |
+
const a={step:10,split:'val',task:'02_interruption/stop',visual_kind:'video',path:'a'};
|
| 137 |
+
const b={step:10,split:'train',task:'01_turn-taking',visual_kind:'image',path:'b'};
|
| 138 |
+
const c={...a,step:20,path:'c'};
|
| 139 |
+
assert.deepEqual(videoSelection([c,b,a],'10','val','',''),[a]);
|
| 140 |
+
assert.deepEqual(videoSelection([c,b,a],'10','','','image'),[b]);
|
| 141 |
+
assert.deepEqual(videoSelection([c,b,a],'20','','02_interruption/stop','video'),[c]);
|
| 142 |
+
assert.deepEqual(videoSelection([c,b,a],'30','','',''),[]);
|
| 143 |
+
'''
|
| 144 |
+
subprocess.run(['node','-e',js],check=True,capture_output=True,text=True)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def qa_fixture(answers):
|
| 148 |
+
return dict(overlay=dict(question="Is it raining?", answer="yes"),
|
| 149 |
+
events=[dict(seconds=s, reply_gt=positive) for s, positive in
|
| 150 |
+
[(1., 0), (1.4, 1), (1.8, 1), (2.2, 1), (2.6, 0)]], answers=answers)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def test_qa_on_time_first_not_best_and_audio(tmp_path):
|
| 154 |
+
from scripts.training_dashboard import qa_case
|
| 155 |
+
(tmp_path / "answer.wav").write_bytes(b'x'*100)
|
| 156 |
+
metric = qa_fixture([dict(seconds=1., text="yes"),
|
| 157 |
+
dict(seconds=1.8, text="no", audio_path="answer.wav"),
|
| 158 |
+
dict(seconds=2.2, text="YES!")])
|
| 159 |
+
result = qa_case(metric, tmp_path)
|
| 160 |
+
assert result["questions"] == result["on_time"] == 1
|
| 161 |
+
assert result["extra_answers"] == 2
|
| 162 |
+
assert result["audio_files"] == 1
|
| 163 |
+
assert result["text_em"] == result["text_f1"] == 0
|
| 164 |
+
result = qa_case(qa_fixture([dict(seconds=1.8, text=" YES! ")]), tmp_path)
|
| 165 |
+
assert result["text_em"] == result["text_f1"] == 1
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_qa_missing_late_and_missing_labels(tmp_path):
|
| 169 |
+
from scripts.training_dashboard import qa_case
|
| 170 |
+
for answers in ([], [dict(seconds=3., text="yes")]):
|
| 171 |
+
result = qa_case(qa_fixture(answers), tmp_path)
|
| 172 |
+
assert result["on_time"] == result["text_em"] == result["text_f1"] == 0
|
| 173 |
+
assert result["extra_answers"] == len(answers)
|
| 174 |
+
assert qa_case(dict(overlay={}, events=[dict(seconds=1.)]), tmp_path) is None
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_qa_silent_and_multiple_questions(tmp_path):
|
| 178 |
+
from scripts.training_dashboard import qa_case, qa_summary, answer_tokens
|
| 179 |
+
metric = qa_fixture([dict(seconds=1.8, text="yes")])
|
| 180 |
+
for event in metric["events"]:
|
| 181 |
+
event["reply_gt"] = 0
|
| 182 |
+
result = qa_case(metric, tmp_path)
|
| 183 |
+
assert result["questions"] == 0 and result["extra_answers"] == 1
|
| 184 |
+
assert "text_em" not in result
|
| 185 |
+
metric = qa_fixture([dict(seconds=1.8, text="yes"), dict(seconds=3.4, text="yes")])
|
| 186 |
+
metric['events'].extend([dict(seconds=3.4, reply_gt=1), dict(seconds=3.8, reply_gt=0)])
|
| 187 |
+
result = qa_case(metric, tmp_path)
|
| 188 |
+
assert result["questions"] == result["on_time"] == 2
|
| 189 |
+
assert "text_em" not in result # No fabricated per-question references.
|
| 190 |
+
assert answer_tokens("蓝色,汽车。") == answer_tokens("蓝色 汽车")
|
| 191 |
+
rows = qa_summary([dict(result, step=5, split="val"),
|
| 192 |
+
dict(qa_case(qa_fixture([]), tmp_path), step=5, split="val")])
|
| 193 |
+
assert rows[0]["reply_recall"] == pytest.approx(2/3)
|
| 194 |
+
assert rows[0]["sessions"] == 2 and rows[0]["text_samples"] == 1
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def test_history_qa_zeros_are_not_supervision(tmp_path):
|
| 198 |
+
from scripts.training_dashboard import MetricHistory
|
| 199 |
+
path = tmp_path / "dashboard_metrics.jsonl"
|
| 200 |
+
path.write_text('\n'.join(json.dumps(row) for row in [
|
| 201 |
+
{"step": 1, "train/swa_qa_loss": 0, "train/swa_qa_token_accuracy": 0,
|
| 202 |
+
"train/swa_qa_target_tokens": 0},
|
| 203 |
+
{"step": 2, "train/swa_qa_loss": 0, "train/swa_qa_token_accuracy": 1,
|
| 204 |
+
"train/swa_qa_target_tokens": 5}])+'\n')
|
| 205 |
+
rows = MetricHistory(path).read()
|
| 206 |
+
assert 'train/swa_qa_loss' not in rows[0]
|
| 207 |
+
assert rows[1]['train/swa_qa_loss'] == 0
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def test_dashboard_collects_qa_train_val_and_range(tmp_path, monkeypatch):
|
| 211 |
+
import scripts.training_dashboard as dashboard
|
| 212 |
+
monkeypatch.setattr(dashboard.subprocess, "check_output", lambda *a, **k: "gpu")
|
| 213 |
+
monkeypatch.setattr(dashboard, "WANDB_ROWS", [])
|
| 214 |
+
for step in [100, 20000]:
|
| 215 |
+
for split in ['train', 'val']:
|
| 216 |
+
directory = tmp_path / f'unified_overlay/ckpt_{step}/{split}/case'
|
| 217 |
+
directory.mkdir(parents=True)
|
| 218 |
+
(directory/'metrics.json').write_text(json.dumps(qa_fixture([dict(seconds=1.8, text='yes')])))
|
| 219 |
+
data = dashboard.snapshot(tmp_path)
|
| 220 |
+
assert len(data['qa_rows']) == 4
|
| 221 |
+
assert len(data['validation_rows']) == 2
|
| 222 |
+
view = dashboard.curve_view(data, 'local', 10000)
|
| 223 |
+
assert len(view['qa_rows']) == len(view['qa_cases']) == 2
|
| 224 |
+
assert all(row['step'] == 20000 for row in view['qa_cases'])
|
| 225 |
+
assert {row['split'] for row in view['qa_cases']} == {'train','val'}
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def test_full_history_incremental_partial_and_rotation(tmp_path):
|
| 229 |
+
from scripts.training_dashboard import MetricHistory
|
| 230 |
+
path = tmp_path / "dashboard_metrics.jsonl"
|
| 231 |
+
# Larger than both former tail limits; early records must survive.
|
| 232 |
+
with path.open("w") as stream:
|
| 233 |
+
for step in range(5001):
|
| 234 |
+
stream.write(json.dumps({"step": step, "train/loss": step / 5001, "unused": "x"*1000})+'\n')
|
| 235 |
+
history = MetricHistory(path)
|
| 236 |
+
assert len(history.read()) == 5001
|
| 237 |
+
assert history.rows[0]["step"] == 0
|
| 238 |
+
assert "unused" not in history.rows[0]
|
| 239 |
+
old_offset = history.offset
|
| 240 |
+
with path.open("a") as stream:
|
| 241 |
+
stream.write('{"step": 5001, "train/loss":')
|
| 242 |
+
assert len(history.read()) == 5001 and history.offset == old_offset
|
| 243 |
+
with path.open("a") as stream:
|
| 244 |
+
stream.write('0.1}\n')
|
| 245 |
+
assert len(history.read()) == 5002
|
| 246 |
+
assert len(history.read()) == 5002 # No duplicate reads.
|
| 247 |
+
path.write_text('{"step": 2, "train/loss": 0.2}\n')
|
| 248 |
+
assert history.read() == [{"step": 2, "train/loss": .2}]
|
| 249 |
+
replacement = tmp_path / "new.jsonl"
|
| 250 |
+
replacement.write_text('{"step": 3, "train/loss": 0.3}\n')
|
| 251 |
+
replacement.replace(path)
|
| 252 |
+
assert history.read() == [{"step": 3, "train/loss": .3}]
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def test_global_local_preserve_extrema_and_sparse_metrics():
|
| 256 |
+
from scripts.training_dashboard import curve_view
|
| 257 |
+
rows = [{"step": step*20, "train/loss": .1} for step in range(6001)]
|
| 258 |
+
rows[10]["train/loss"] = 99
|
| 259 |
+
rows[11]["train/loss"] = -1
|
| 260 |
+
rows[19]["eval/loss"] = .2
|
| 261 |
+
data = dict(rows=rows, semantic_rows=[{"step": 21, "train/control_accuracy": .8}],
|
| 262 |
+
validation_rows=[{"step": 5000, "case": "a", "control_accuracy": .7}])
|
| 263 |
+
full = curve_view(data)
|
| 264 |
+
assert full["step_range"] == [0, 120000]
|
| 265 |
+
assert full["rows"][0]["step"] == 0 and full["rows"][-1]["step"] == 120000
|
| 266 |
+
assert len(full["rows"]) < 1000
|
| 267 |
+
assert {r["train/loss"] for r in full["rows"]} == {99, -1, .1}
|
| 268 |
+
assert any("eval/loss" in r for r in full["rows"])
|
| 269 |
+
assert full["semantic_rows"] == data["semantic_rows"]
|
| 270 |
+
local = curve_view(data, "local", 10000)
|
| 271 |
+
assert local["step_range"] == [110000, 120000]
|
| 272 |
+
assert all(r["step"] >= 110000 for r in local["rows"])
|
| 273 |
+
assert local["semantic_rows"] == local["validation_rows"] == []
|
| 274 |
+
assert local["latest"]["step"] == 120000
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def test_current_range_starts_at_local_resume_not_old_wandb():
|
| 278 |
+
from scripts.training_dashboard import curve_view
|
| 279 |
+
data = dict(rows=[{"step": 1005984, "train/loss": .4}, {"step": 1007000, "train/loss": .2}],
|
| 280 |
+
semantic_rows=[{"step": 100, "train/control_accuracy": .5},
|
| 281 |
+
{"step": 1006000, "train/control_accuracy": .9}],
|
| 282 |
+
validation_rows=[])
|
| 283 |
+
view = curve_view(data, "current")
|
| 284 |
+
assert view["step_range"] == [1005984, 1007000]
|
| 285 |
+
assert len(view["semantic_rows"]) == 1
|
| 286 |
+
assert view["first_step"] == 1005984
|
| 287 |
+
assert curve_view(data, "local", 1000)["step_range"] == [1006000, 1007000]
|
| 288 |
+
assert curve_view(data, "global")["step_range"] == [0, 1007000]
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def test_step_range_http_toggle(tmp_path, monkeypatch):
|
| 292 |
+
import threading
|
| 293 |
+
from urllib.request import urlopen
|
| 294 |
+
from urllib.error import HTTPError
|
| 295 |
+
from http.server import ThreadingHTTPServer
|
| 296 |
+
import scripts.training_dashboard as dashboard
|
| 297 |
+
monkeypatch.setattr(dashboard.subprocess, "check_output", lambda *a, **k: "gpu")
|
| 298 |
+
monkeypatch.setattr(dashboard, "WANDB_ROWS", [])
|
| 299 |
+
(tmp_path / "dashboard_metrics.jsonl").write_text(
|
| 300 |
+
'\n'.join(json.dumps({"step": s, "train/loss": .2}) for s in [20, 100000])+'\n')
|
| 301 |
+
server = ThreadingHTTPServer(("127.0.0.1", 0), dashboard.handler(tmp_path))
|
| 302 |
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
| 303 |
+
thread.start()
|
| 304 |
+
try:
|
| 305 |
+
base = f"http://127.0.0.1:{server.server_port}/api/status"
|
| 306 |
+
with urlopen(base) as response:
|
| 307 |
+
assert json.load(response)["rows"][0]["step"] == 20
|
| 308 |
+
with urlopen(base+'?view=local&window=10000') as response:
|
| 309 |
+
result = json.load(response)
|
| 310 |
+
assert result["step_range"] == [90000, 100000]
|
| 311 |
+
assert len(result["rows"]) == 1
|
| 312 |
+
with pytest.raises(HTTPError) as error:
|
| 313 |
+
urlopen(base+'?view=local&window=bogus')
|
| 314 |
+
assert error.value.code == 400
|
| 315 |
+
finally:
|
| 316 |
+
server.shutdown()
|
| 317 |
+
server.server_close()
|
| 318 |
+
thread.join()
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def test_infer_checks_saved_unified_manifest(tmp_path, monkeypatch):
|
| 322 |
+
from scripts.infer.check_run_visual_data import check_run
|
| 323 |
+
import scripts.data.check_hfd_overlay_manifest as check_module
|
| 324 |
+
(tmp_path / "run_config.json").write_text(json.dumps({
|
| 325 |
+
"data": {"multimodal_overlay_manifests": ["/unified"], "swa_source_plan": "/deleted",
|
| 326 |
+
"multimodal_visual_input_mode": "raw"},
|
| 327 |
+
"model": {"model_name_or_path": "/qwen"}}))
|
| 328 |
+
monkeypatch.delenv("HFD_VISUAL_INPUT_MODE", raising=False)
|
| 329 |
+
def fake(paths, model, **kwargs):
|
| 330 |
+
assert paths == ["/unified"] and model == "/qwen"
|
| 331 |
+
assert kwargs == dict(require_eight_voices=True, require_live_video_qa=True, visual_input_mode="raw")
|
| 332 |
+
return {"ok": True}
|
| 333 |
+
monkeypatch.setattr(check_module, "check", fake)
|
| 334 |
+
assert check_run(tmp_path) == {"ok": True}
|
tests/test_unified_overlay_review.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
ROOT=Path(__file__).parents[1]
|
| 9 |
+
sys.path.insert(0,str(ROOT))
|
| 10 |
+
from scripts.infer.run_multiturn_infer_suite import OverlayInferenceCase,case_result_dir,case_label
|
| 11 |
+
from psi.async_render_queue import swa_outputs_ready,render_complete
|
| 12 |
+
from psi.runtime.overlay_cases import CASE_PATHS
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_visual_type_is_not_an_extra_task(tmp_path):
|
| 16 |
+
tasks=['turn-taking','interruption','stop','backchannel','hesitation','pause']
|
| 17 |
+
for split in ('val','train'):
|
| 18 |
+
for i,task in enumerate(tasks):
|
| 19 |
+
index=i+(6 if split=='train' else 0)
|
| 20 |
+
case=OverlayInferenceCase(split,index,task,str(tmp_path))
|
| 21 |
+
p=case_result_dir(tmp_path,case,5000)
|
| 22 |
+
assert p==tmp_path/'unified_overlay/ckpt_5000'/split/CASE_PATHS[task]
|
| 23 |
+
assert 'video' not in case_label(case)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_overlay_fixture_list_contract(tmp_path):
|
| 27 |
+
from scripts.infer.run_multiturn_infer_suite import load_overlay_rows
|
| 28 |
+
path = tmp_path / 'sources.json'
|
| 29 |
+
rows = [dict(index=i, split=split, task=task)
|
| 30 |
+
for i, (split, task) in enumerate(
|
| 31 |
+
(s, t) for s in ('train', 'val') for t in CASE_PATHS)]
|
| 32 |
+
path.write_text(json.dumps(rows))
|
| 33 |
+
assert load_overlay_rows(path) == rows
|
| 34 |
+
for bad in ({'rows': rows}, [], [rows[0], rows[0]], [dict(rows[0], index=4)]):
|
| 35 |
+
path.write_text(json.dumps(bad))
|
| 36 |
+
with pytest.raises(ValueError):
|
| 37 |
+
load_overlay_rows(path)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_async_overlay_requires_actual_speech_and_fixture(tmp_path):
|
| 41 |
+
fixture=tmp_path/'sources.pt';fixture.write_bytes(b'fixture')
|
| 42 |
+
(tmp_path/'generated_abs.npy').write_bytes(b'motion')
|
| 43 |
+
meta=dict(source_id='source',events=[dict(control=1)],answers=[],native_speech_version=1,
|
| 44 |
+
overlay_fixture_file=str(fixture))
|
| 45 |
+
(tmp_path/'metrics.json').write_text(json.dumps(meta))
|
| 46 |
+
assert swa_outputs_ready(tmp_path)
|
| 47 |
+
assert not render_complete(tmp_path)
|
| 48 |
+
(tmp_path/'reference_motion_with_audio.mp4').write_bytes(b'video')
|
| 49 |
+
(tmp_path/'infer_meta.json').write_text(json.dumps(dict(swa_render_version=2)))
|
| 50 |
+
(tmp_path/'.complete').touch()
|
| 51 |
+
assert render_complete(tmp_path)
|
| 52 |
+
meta['answers']=[dict(audio_path='missing.wav',native_speech=True,samples=200)]
|
| 53 |
+
(tmp_path/'metrics.json').write_text(json.dumps(meta))
|
| 54 |
+
assert not swa_outputs_ready(tmp_path)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_short_video_rejected_before_robot_render(monkeypatch,tmp_path):
|
| 58 |
+
from scripts.data import render_hfd_unified_multimodal_gt as m
|
| 59 |
+
monkeypatch.setattr(m.subprocess,'check_output',lambda *a,**kw:'3.0')
|
| 60 |
+
monkeypatch.setattr(m.subprocess,'run',lambda *a,**kw:pytest.fail('GPU renderer must not start'))
|
| 61 |
+
with pytest.raises(ValueError,match='before robot session'):
|
| 62 |
+
m.render_video(tmp_path,dict(camera_video_path='short.mp4',motion_seconds=12.,camera_video_offset=0.))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_egl_device_enumeration_is_not_cuda_ordinal():
|
| 66 |
+
from scripts.infer.run_egl_renderer import selected_device
|
| 67 |
+
assert selected_device(1, '3') == '0' # Single Mesa EGL device, four CUDA GPUs.
|
| 68 |
+
assert selected_device(4, '3') == '3'
|
| 69 |
+
assert selected_device(4, None) is None
|
| 70 |
+
with pytest.raises(ValueError):
|
| 71 |
+
selected_device(2, '3')
|
| 72 |
+
with pytest.raises(RuntimeError):
|
| 73 |
+
selected_device(0, None)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_caption_mux_has_exact_duration(monkeypatch,tmp_path):
|
| 77 |
+
from scripts.data import render_hfd_unified_multimodal_gt as m
|
| 78 |
+
commands=[]
|
| 79 |
+
monkeypatch.setattr(m.subprocess,'run',lambda command,**kw:commands.append(command))
|
| 80 |
+
m.render_video(tmp_path,dict(camera_video_path='image.jpg',motion_seconds=12.,
|
| 81 |
+
camera_video_offset=0.,review_kind='GT',task='interruption',question='What?',answer='Red.'))
|
| 82 |
+
mux=commands[-1]
|
| 83 |
+
assert mux[mux.index('-t')+1]=='12.0'
|
| 84 |
+
assert '-filter_complex' in mux
|
| 85 |
+
assert (tmp_path/'review_panel.png').is_file()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_answer_postroll_is_labelled_not_frozen_or_future_video(monkeypatch,tmp_path):
|
| 89 |
+
from scripts.data import render_hfd_unified_multimodal_gt as m
|
| 90 |
+
commands=[]
|
| 91 |
+
monkeypatch.setattr(m.subprocess,'check_output',lambda *a,**kw:'23.0')
|
| 92 |
+
monkeypatch.setattr(m.subprocess,'run',lambda command,**kw:commands.append(command))
|
| 93 |
+
m.render_video(tmp_path,dict(camera_video_path='video.mp4',motion_seconds=25.,
|
| 94 |
+
input_duration_seconds=19., camera_video_offset=0.,review_kind='MODEL INFERENCE'))
|
| 95 |
+
camera=next(c for c in commands if '-vf' in c)
|
| 96 |
+
assert camera[camera.index('-t')+1]=='19.0'
|
| 97 |
+
filt=camera[camera.index('-vf')+1]
|
| 98 |
+
assert 'tpad=stop_mode=add:stop_duration=6.0' in filt
|
| 99 |
+
assert 'INPUT ENDED' in filt and 'clone' not in filt
|
| 100 |
+
assert commands[-1][commands[-1].index('-t')+1]=='25.0'
|
| 101 |
+
with pytest.raises(ValueError,match='before robot session'):
|
| 102 |
+
m.render_video(tmp_path,dict(camera_video_path='video.mp4',motion_seconds=30.,
|
| 103 |
+
input_duration_seconds=25.,camera_video_offset=0.))
|
tests/test_video_asset_admission.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import errno
|
| 2 |
+
import importlib.util
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from types import SimpleNamespace
|
| 5 |
+
from unittest.mock import patch
|
| 6 |
+
from unittest.mock import MagicMock
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
PATH=Path(__file__).resolve().parents[1]/'scripts/data/prepare_hfd_video_assets.py'
|
| 10 |
+
SPEC=importlib.util.spec_from_file_location('video_admission',PATH)
|
| 11 |
+
M=importlib.util.module_from_spec(SPEC);SPEC.loader.exec_module(M)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_transient_retry_is_bounded_and_other_errors_fail():
|
| 15 |
+
with patch.object(M.time,'sleep'):
|
| 16 |
+
with patch.object(M,'sha',side_effect=[OSError(errno.ESTALE,'stale'),'ok']) as f:
|
| 17 |
+
assert M.retry(lambda:f('path'))=='ok'
|
| 18 |
+
assert f.call_count==2
|
| 19 |
+
with patch.object(M,'sha',side_effect=OSError(errno.ESTALE,'stale')) as f:
|
| 20 |
+
with pytest.raises(OSError):M.retry(lambda:f('path'))
|
| 21 |
+
assert f.call_count==4
|
| 22 |
+
with patch.object(M,'sha',side_effect=OSError(errno.ENOSPC,'full')) as f:
|
| 23 |
+
with pytest.raises(OSError):M.retry(lambda:f('path'))
|
| 24 |
+
assert f.call_count==1
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_optional_progress_estale_never_stops_real_workers():
|
| 28 |
+
old={'pid':123,'done':42}
|
| 29 |
+
with patch.object(M,'read',side_effect=OSError(errno.ESTALE,'stale')):
|
| 30 |
+
assert M.optional_progress(lambda:M.read('status'),old) is old
|
| 31 |
+
with patch.object(M,'read',side_effect=PermissionError(errno.EACCES,'denied')):
|
| 32 |
+
with pytest.raises(PermissionError):M.optional_progress(lambda:M.read('status'),old)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_failed_encoder_is_not_hidden_by_cpu_stage():
|
| 36 |
+
a=SimpleNamespace(_workers=[MagicMock(poll=lambda:1)])
|
| 37 |
+
with pytest.raises(RuntimeError,match='worker failed'):M.check_workers(a)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_one_generic_frame_is_not_a_temporal_duplicate():
|
| 41 |
+
assert not M.similar([0,2**64-1,0xAAAAAAAAAAAAAAAA],[0])
|
| 42 |
+
assert M.similar([0,0xAAAAAAAAAAAAAAAA,2**64-1],[1,0xAAAAAAAAAAAAAAAA,2**64-2])
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_cached_fingerprint_checks_identity(tmp_path):
|
| 46 |
+
row=dict(asset_id='one',video_sha256='sha')
|
| 47 |
+
p=tmp_path/'fp.json'
|
| 48 |
+
receipt=dict(signature=dict(video_sha256='sha',format='video_dhash8_v1'),accepted=True,hashes=[1,2])
|
| 49 |
+
M.atomic(p,receipt)
|
| 50 |
+
assert M.fingerprint_job((row,p))==receipt
|
| 51 |
+
row['video_sha256']='changed'
|
| 52 |
+
with pytest.raises(ValueError,match='changed'):M.fingerprint_job((row,p))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_unaccepted_manifest_cannot_be_published(tmp_path):
|
| 56 |
+
pending=tmp_path/'admission/overlay_assets.pending.json';M.atomic(pending,dict(format='hfd_overlay_assets_v1',assets=[{'asset_id':'x'}]))
|
| 57 |
+
report=tmp_path/'admission/acceptance.json';M.atomic(report,dict(passed=True,manifest_sha256='wrong'))
|
| 58 |
+
with pytest.raises(RuntimeError,match='acceptance'):M.publish(SimpleNamespace(root=tmp_path))
|
| 59 |
+
assert not (tmp_path/'overlay_assets.json').exists()
|
| 60 |
+
M.atomic(report,dict(passed=True,manifest_sha256=M.sha(pending)))
|
| 61 |
+
M.publish(SimpleNamespace(root=tmp_path))
|
| 62 |
+
assert M.sha(tmp_path/'overlay_assets.json')==M.sha(pending)
|
| 63 |
+
assert M.read(tmp_path/'admission/status.json')['training_ready']==1
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_multivoice_publish_counts_unique_videos(tmp_path):
|
| 67 |
+
pending=tmp_path/'admission/overlay_assets.pending.json'
|
| 68 |
+
M.atomic(pending,dict(format='hfd_overlay_assets_v1',assets=[{'asset_id':'same_video','voice':str(i)} for i in range(8)]))
|
| 69 |
+
M.atomic(tmp_path/'admission/acceptance.json',dict(passed=True,manifest_sha256=M.sha(pending)))
|
| 70 |
+
M.publish(SimpleNamespace(root=tmp_path))
|
| 71 |
+
status=M.read(tmp_path/'admission/status.json')
|
| 72 |
+
assert status['training_ready']==1 and status['voice_variants']==8
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@pytest.mark.parametrize('text',['','0,0','-1','0,x'])
|
| 76 |
+
def test_gpu_selection_rejects_invalid(text):
|
| 77 |
+
with pytest.raises(M.argparse.ArgumentTypeError):M.parse_gpus(text)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_four_gpu_worker_layout():
|
| 81 |
+
layout=M.worker_layout(M.parse_gpus('0,1,2,3'),4)
|
| 82 |
+
assert layout['ranks']==list(range(16))
|
| 83 |
+
assert layout['rank_gpus']==[0,1,2,3]*4
|
| 84 |
+
assert M.worker_layout([2,3],2)['rank_gpus']==[2,3,2,3]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@pytest.mark.parametrize('exit_code',[0,7])
|
| 88 |
+
def test_local_supervisor_restores_keeper_and_preserves_exit(tmp_path,exit_code):
|
| 89 |
+
import subprocess
|
| 90 |
+
import os
|
| 91 |
+
scripts=tmp_path/'project/scripts/data';scripts.mkdir(parents=True)
|
| 92 |
+
wrapper=scripts/'complete_video_vqa_with_keeper.sh'
|
| 93 |
+
wrapper.write_text((M.HFD/'scripts/data/complete_video_vqa_with_keeper.sh').read_text())
|
| 94 |
+
(scripts/'complete_video_vqa.sh').write_text(f'echo pipeline >> "$TRACE"\nexit {exit_code}\n')
|
| 95 |
+
keeper=tmp_path/'keeper';keeper.mkdir()
|
| 96 |
+
(keeper/'stop.sh').write_text('echo stop >> "$TRACE"\n')
|
| 97 |
+
(keeper/'cmd.sh').write_text('echo "restore:$MONITOR_GPU_INDICES" >> "$TRACE"\n')
|
| 98 |
+
trace=tmp_path/'trace'
|
| 99 |
+
result=subprocess.run(['bash',str(wrapper)],env={**os.environ,'HFD_VIDEO_DATA_ROOT':str(tmp_path/'data'),
|
| 100 |
+
'HFD_VIDEO_MONITOR_ROOT':str(keeper),'HFD_VIDEO_GPUS':'0,1,2,3','TRACE':str(trace)},timeout=10)
|
| 101 |
+
assert result.returncode==exit_code
|
| 102 |
+
assert trace.read_text().splitlines()==['stop','pipeline','restore:0,1,2,3']
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@pytest.mark.parametrize('returncode',[0,1])
|
| 106 |
+
def test_acceptance_heartbeat_and_owned_process_group_cleanup(tmp_path,returncode):
|
| 107 |
+
child=MagicMock(pid=987654,returncode=returncode,args=['validator'])
|
| 108 |
+
child.poll.side_effect=[None,returncode]
|
| 109 |
+
with patch.object(M.subprocess,'Popen',return_value=child) as start,patch.object(M.os,'killpg') as kill:
|
| 110 |
+
args=SimpleNamespace(root=tmp_path,body_run=tmp_path)
|
| 111 |
+
if returncode:
|
| 112 |
+
with pytest.raises(M.subprocess.CalledProcessError):M.run_acceptance(args)
|
| 113 |
+
else:M.run_acceptance(args)
|
| 114 |
+
assert start.call_args.kwargs['start_new_session'] is True
|
| 115 |
+
assert start.call_args.kwargs['env']['CUDA_VISIBLE_DEVICES']=='0'
|
| 116 |
+
assert M.read(tmp_path/'admission/status.json')['acceptance_pid']==987654
|
| 117 |
+
kill.assert_called_once_with(987654,M.signal.SIGTERM)
|
tests/test_video_overlay.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pytest
|
| 4 |
+
import torch
|
| 5 |
+
from psi.data.seed.video_overlay import camera_plan,FORMAT,dynamic_features,packet_feature
|
| 6 |
+
from psi.data.seed.live_multimodal_overlay import camera_count,attach_live_packets,LiveMultimodalOverlayDataset
|
| 7 |
+
from test_live_multimodal_overlay import dataset,source
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def feature_file(path,duration=5.):
|
| 11 |
+
ticks,groups=camera_plan(duration)
|
| 12 |
+
payload=dict(format=FORMAT,duration_seconds=duration,frame_pts=ticks.tolist(),
|
| 13 |
+
packets=[torch.full(((len(g)+1)//2*64,4),float(i)) for i,g in enumerate(groups)],
|
| 14 |
+
tail={str(n):torch.full(((n+1)//2*64,4),99.) for n in (3,4,5)})
|
| 15 |
+
torch.save(payload,path);return payload
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@pytest.mark.parametrize('duration',[.3,.6,1.,3.001,15.047,30.999])
|
| 19 |
+
def test_camera_grid_matches_training(duration):
|
| 20 |
+
ticks,groups=camera_plan(duration)
|
| 21 |
+
assert sum(groups,[])==list(range(len(ticks)))
|
| 22 |
+
for i,g in enumerate(groups):
|
| 23 |
+
assert len(g)==camera_count(i)
|
| 24 |
+
assert max(ticks[g])<=.6+.4*i+1e-7
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_dynamic_overlay_preserves_body_and_waits_for_full_evidence(tmp_path):
|
| 28 |
+
ds=dataset(tmp_path);p=tmp_path/'dynamic.pt';feature_file(p,20.)
|
| 29 |
+
row=ds.by_voice['female_01_en'][0]
|
| 30 |
+
row.pop('image_path');row.pop('image_sha256')
|
| 31 |
+
row.update(video_path='clip.mp4',video_sha256='video_sha',parent_video_id='parent',
|
| 32 |
+
visual_features_path=str(p),earliest_answer_video_seconds=5.,duration_seconds=20.,
|
| 33 |
+
live_qa_windows=[dict(start_seconds=4.,end_seconds=10.,accepted=True)])
|
| 34 |
+
out=ds.compose(source(),'qa')
|
| 35 |
+
assert out['multimodal_overlay']['question_end']>=5.
|
| 36 |
+
for before,after in zip(source()['steps'],out['steps']):
|
| 37 |
+
for k in ('actions','states','control_label','future_progress'):np.testing.assert_array_equal(before[k],after[k])
|
| 38 |
+
if after['update_semantic_cache']:
|
| 39 |
+
after['stream_input_features']=np.zeros((128,63),np.float32)
|
| 40 |
+
after['stream_feature_attention_mask']=np.ones(63,np.int64)
|
| 41 |
+
attach_live_packets(out)
|
| 42 |
+
packets=out['swa_packets']
|
| 43 |
+
assert packets[1]['visual_features'][0,0]==1
|
| 44 |
+
assert packets[-1]['visual_features'][0,0]==len(packets)-1
|
| 45 |
+
assert all(p['available_seconds']>=5 for p in packets if p['reply_label'])
|
| 46 |
+
row['earliest_answer_video_seconds']=30
|
| 47 |
+
assert ds.compose(source(),'qa')['multimodal_overlay']['mode']=='audio-only'
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_short_or_full_clip_only_video_is_not_silently_frozen(tmp_path):
|
| 51 |
+
ds=dataset(tmp_path);row=ds.by_voice['female_01_en'][0]
|
| 52 |
+
row.update(video_path='short.mp4',duration_seconds=5.,
|
| 53 |
+
live_qa_windows=[dict(start_seconds=0.,end_seconds=20.,accepted=True)])
|
| 54 |
+
assert ds.compose(source(),'qa')['multimodal_overlay']['mode']=='audio-only'
|
| 55 |
+
assert ds.compose(source(),'visual-only')['multimodal_overlay']['mode']=='audio-only'
|
| 56 |
+
row['duration_seconds']=20.;row.pop('live_qa_windows')
|
| 57 |
+
assert ds.compose(source(),'qa')['multimodal_overlay']['mode']=='audio-only'
|
| 58 |
+
assert ds.compose(source(),'visual-only')['multimodal_overlay']['mode']=='visual-only'
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_no_frozen_feature_tail(tmp_path):
|
| 62 |
+
data=feature_file(tmp_path/'short.pt')
|
| 63 |
+
with pytest.raises(ValueError,match='frozen'):
|
| 64 |
+
packet_feature(data,len(data['packets']),4)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_parent_split_leak_rejected(tmp_path):
|
| 68 |
+
ds=dataset(tmp_path);row=ds.by_voice['female_01_en'][0]
|
| 69 |
+
row.update(parent_video_id='same_parent')
|
| 70 |
+
other={**row,'asset_id':'two','split':'val','image_sha256':'different'}
|
| 71 |
+
p=tmp_path/'leak.json';p.write_text(json.dumps(dict(format='hfd_overlay_assets_v1',assets=[row,other])))
|
| 72 |
+
with pytest.raises(ValueError,match='overlap'):LiveMultimodalOverlayDataset([], [p], 'train')
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_bad_dynamic_pts_and_nonfinite_rejected(tmp_path):
|
| 76 |
+
p=tmp_path/'bad.pt';data=feature_file(p);data['frame_pts'][0]=.1;torch.save(data,p)
|
| 77 |
+
with pytest.raises(ValueError,match='PTS'):dynamic_features(str(p))
|
| 78 |
+
p=tmp_path/'nan.pt';data=feature_file(p);data['packets'][0][0,0]=float('nan');torch.save(data,p)
|
| 79 |
+
with pytest.raises(ValueError,match='Malformed'):dynamic_features(str(p))
|
tests/test_visual_dataset_bundle.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import wave
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
from psi.data.seed.visual_dataset import VOICES, overlay_rows, records, resolve_file
|
| 11 |
+
|
| 12 |
+
SPEC = importlib.util.spec_from_file_location("consolidator", Path(__file__).parents[1] / "scripts/data/consolidate_visual_dataset.py")
|
| 13 |
+
mod = importlib.util.module_from_spec(SPEC)
|
| 14 |
+
SPEC.loader.exec_module(mod)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def source(tmp_path, *, video=False):
|
| 18 |
+
p = tmp_path / "source"
|
| 19 |
+
p.mkdir()
|
| 20 |
+
media = p / ("sample.mp4" if video else "sample.png")
|
| 21 |
+
if video:
|
| 22 |
+
media.write_bytes(b"fake video bytes - metadata tests only")
|
| 23 |
+
else:
|
| 24 |
+
Image.new("RGB", (5, 8), (100, 20, 45)).save(media)
|
| 25 |
+
feature = p / "feature.pt"
|
| 26 |
+
feature.write_bytes(b"feature-fixture-not-a-torch-test")
|
| 27 |
+
receipt = p / "review.json"
|
| 28 |
+
receipt.write_text('{"accepted":true}')
|
| 29 |
+
rows = []
|
| 30 |
+
for voice in VOICES:
|
| 31 |
+
wav_path = p / (voice + ".wav")
|
| 32 |
+
with wave.open(str(wav_path), "wb") as wav:
|
| 33 |
+
wav.setparams((1, 2, 16000, 0, "NONE", "not compressed"))
|
| 34 |
+
wav.writeframes(b"\0\0" * 160)
|
| 35 |
+
key = "video" if video else "image"
|
| 36 |
+
rows.append(dict(asset_id="one", split="train", voice=voice, question="What?", answer="Red.",
|
| 37 |
+
question_audio_path=str(wav_path), question_audio_sha256=mod.digest(wav_path),
|
| 38 |
+
visual_features_path=str(feature), asr_receipt=str(receipt),
|
| 39 |
+
**{key + "_path": str(media), key + "_sha256": mod.digest(media)},
|
| 40 |
+
**(dict(duration_seconds=15.) if video else {})))
|
| 41 |
+
manifest = p / "overlay_assets.json"
|
| 42 |
+
manifest.write_text(json.dumps(dict(format="hfd_overlay_assets_v1", assets=rows)))
|
| 43 |
+
(p / "admission").mkdir()
|
| 44 |
+
(p / "admission/acceptance.json").write_text(json.dumps(dict(passed=True, manifest_sha256=mod.digest(manifest))))
|
| 45 |
+
return manifest, rows
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def save(manifest, rows):
|
| 49 |
+
manifest.write_text(json.dumps(dict(format="hfd_overlay_assets_v1", assets=rows)))
|
| 50 |
+
(manifest.parent / "admission/acceptance.json").write_text(json.dumps(dict(passed=True, manifest_sha256=mod.digest(manifest))))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_hardlinked_portable_eight_voice_roundtrip(tmp_path):
|
| 54 |
+
manifest, rows = source(tmp_path)
|
| 55 |
+
dest = tmp_path / "bundle"
|
| 56 |
+
result = mod.consolidate([manifest], dest, workers=2)
|
| 57 |
+
assert sorted(p.name for p in dest.iterdir()) == ["images", "videos"]
|
| 58 |
+
assert result["images"]["counts"]["voice_rows"] == 8
|
| 59 |
+
data = list(records(dest))
|
| 60 |
+
assert len(data) == 1 and len(data[0]["questions"]) == 1
|
| 61 |
+
loaded = list(overlay_rows(dest))
|
| 62 |
+
assert len(loaded) == 8
|
| 63 |
+
assert os.path.samefile(rows[0]["image_path"], loaded[0]["image_path"])
|
| 64 |
+
# Original package name no longer required for reading.
|
| 65 |
+
manifest.parent.rename(tmp_path / "old-location-hidden")
|
| 66 |
+
assert all(Path(r["question_audio_path"]).is_file() for r in overlay_rows(dest))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_formal_overlay_accepts_bundle_without_original_package(tmp_path):
|
| 70 |
+
from psi.data.seed.live_multimodal_overlay import LiveMultimodalOverlayDataset
|
| 71 |
+
manifest, _ = source(tmp_path)
|
| 72 |
+
dest = tmp_path / 'bundle'
|
| 73 |
+
mod.consolidate([manifest], dest, workers=1)
|
| 74 |
+
manifest.parent.rename(tmp_path / 'old-package-hidden')
|
| 75 |
+
ds = LiveMultimodalOverlayDataset([], [dest], 'train')
|
| 76 |
+
assert set(ds.by_voice) == set(VOICES)
|
| 77 |
+
assert all(len(rows) == 1 for rows in ds.by_voice.values())
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_lazy_overlay_matches_eager_and_checks_before_use(tmp_path):
|
| 81 |
+
from psi.data.seed.visual_dataset import resolve_overlay_row, resolve_file
|
| 82 |
+
manifest, _ = source(tmp_path)
|
| 83 |
+
dest = tmp_path / 'bundle'
|
| 84 |
+
mod.consolidate([manifest], dest, workers=1)
|
| 85 |
+
eager = list(overlay_rows(dest))
|
| 86 |
+
lazy = list(overlay_rows(dest, lazy_paths=True))
|
| 87 |
+
assert [resolve_overlay_row(r) for r in lazy] == eager
|
| 88 |
+
# A metadata read does not dereference files; selecting this corrupted
|
| 89 |
+
# dependency must fail before question_wave/visual loading can open it.
|
| 90 |
+
chosen = Path(lazy[0]['question_audio_path'])
|
| 91 |
+
chosen.unlink()
|
| 92 |
+
chosen.symlink_to(manifest) # Outside the bundle.
|
| 93 |
+
resolve_file.cache_clear()
|
| 94 |
+
with pytest.raises(ValueError, match='escapes'):
|
| 95 |
+
resolve_overlay_row(lazy[0])
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@pytest.mark.parametrize('mode', ['cached', 'raw'])
|
| 99 |
+
def test_formal_bundle_preflight_and_manifest_integrity(tmp_path, mode):
|
| 100 |
+
import torch
|
| 101 |
+
from scripts.data.check_hfd_overlay_manifest import check
|
| 102 |
+
manifest, rows = source(tmp_path)
|
| 103 |
+
torch.save({str(n): torch.zeros(((n+1)//2*64, 4)) for n in (3,4,5)}, rows[0]['visual_features_path'])
|
| 104 |
+
dest = tmp_path / 'bundle'
|
| 105 |
+
mod.consolidate([manifest], dest, workers=1)
|
| 106 |
+
manifest.parent.rename(tmp_path / 'old-package-hidden')
|
| 107 |
+
if mode == 'raw':
|
| 108 |
+
# Raw admission must not require an existing feature file.
|
| 109 |
+
Path(next(overlay_rows(dest))['visual_features_path']).unlink()
|
| 110 |
+
result = check([dest], require_eight_voices=True, require_live_video_qa=True, visual_input_mode=mode)
|
| 111 |
+
assert result['counts'] == {'unified_images:train': 8}
|
| 112 |
+
with (dest / 'images/manifest.jsonl').open('a') as f:
|
| 113 |
+
f.write('\n')
|
| 114 |
+
with pytest.raises(ValueError, match='changed after publication'):
|
| 115 |
+
check([dest], visual_input_mode=mode)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_bundle_encoder_contract_mismatch_fails(tmp_path):
|
| 119 |
+
manifest, rows = source(tmp_path, video=True)
|
| 120 |
+
audit = make_audit(tmp_path, manifest, rows, True)
|
| 121 |
+
dest = tmp_path / 'bundle'
|
| 122 |
+
mod.consolidate([manifest], dest, workers=1, audit_root=audit)
|
| 123 |
+
base = tmp_path / 'qwen'
|
| 124 |
+
base.mkdir()
|
| 125 |
+
(base / 'config.json').write_text('{}')
|
| 126 |
+
(base / 'model.safetensors.index.json').write_text('{}')
|
| 127 |
+
(dest / 'videos/inputs.json').write_text(json.dumps([{'provenance': {'contract': {'format': 'wrong'}}}]))
|
| 128 |
+
with pytest.raises(ValueError, match='frontend does not match'):
|
| 129 |
+
list(overlay_rows(dest, verify=True, base_model=base))
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def test_duplicate_qa_and_multiple_questions_one_visual(tmp_path):
|
| 133 |
+
manifest, rows = source(tmp_path)
|
| 134 |
+
more = [dict(r, asset_id="two", question="Where?") for r in rows]
|
| 135 |
+
duplicate = [dict(r, asset_id="copy", question=" WHAT? ") for r in rows]
|
| 136 |
+
save(manifest, rows + more + duplicate)
|
| 137 |
+
result = mod.consolidate([manifest], tmp_path / "out", workers=2)
|
| 138 |
+
assert result["images"]["counts"]["media"] == 1
|
| 139 |
+
assert result["images"]["counts"]["questions"] == 2
|
| 140 |
+
assert result["images"]["duplicate_qa_removed"] == 1
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_decoded_image_dedup(tmp_path):
|
| 144 |
+
manifest, rows = source(tmp_path)
|
| 145 |
+
image2 = manifest.parent / "same.bmp"
|
| 146 |
+
Image.open(rows[0]["image_path"]).save(image2)
|
| 147 |
+
more = [dict(r, asset_id="two", image_path=str(image2), image_sha256=mod.digest(image2)) for r in rows]
|
| 148 |
+
save(manifest, rows + more)
|
| 149 |
+
result = mod.consolidate([manifest], tmp_path / "out", workers=2)
|
| 150 |
+
assert result["images"]["counts"]["media"] == 1
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@pytest.mark.parametrize("change", ["missing", "duplicate", "texts", "checksum"])
|
| 154 |
+
def test_bad_voice_set_or_integrity_fails(tmp_path, change):
|
| 155 |
+
manifest, rows = source(tmp_path)
|
| 156 |
+
if change == "missing":
|
| 157 |
+
rows.pop()
|
| 158 |
+
elif change == "duplicate":
|
| 159 |
+
rows[-1]["voice"] = rows[0]["voice"]
|
| 160 |
+
elif change == "texts":
|
| 161 |
+
rows[0]["answer"] = "Green."
|
| 162 |
+
else:
|
| 163 |
+
rows[0]["question_audio_sha256"] = "0" * 64
|
| 164 |
+
save(manifest, rows)
|
| 165 |
+
with pytest.raises(ValueError):
|
| 166 |
+
mod.consolidate([manifest], tmp_path / "out", workers=2)
|
| 167 |
+
assert not (tmp_path / "out/images/summary.json").exists()
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def test_pending_video_never_read_by_default(tmp_path):
|
| 171 |
+
manifest, _ = source(tmp_path, video=True)
|
| 172 |
+
mod.consolidate([manifest], tmp_path / "out", workers=1)
|
| 173 |
+
assert list(records(tmp_path / "out")) == []
|
| 174 |
+
assert len(list(records(tmp_path / "out", accepted_only=False))) == 1
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_unpublished_image_not_admitted(tmp_path):
|
| 178 |
+
manifest, _ = source(tmp_path)
|
| 179 |
+
(manifest.parent / "admission/acceptance.json").unlink()
|
| 180 |
+
mod.consolidate([manifest], tmp_path / "out", workers=1)
|
| 181 |
+
assert list(records(tmp_path / "out")) == []
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def test_conflicting_splits_excluded(tmp_path):
|
| 185 |
+
manifest, rows = source(tmp_path)
|
| 186 |
+
save(manifest, rows + [dict(r, asset_id="other", split="val") for r in rows])
|
| 187 |
+
mod.consolidate([manifest], tmp_path / "out", workers=1)
|
| 188 |
+
assert list(records(tmp_path / "out")) == []
|
| 189 |
+
assert json.loads((tmp_path / "out/images/excluded.json").read_text())[0]["reason"] == "split_conflict"
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_resume_and_path_escape(tmp_path):
|
| 193 |
+
manifest, rows = source(tmp_path)
|
| 194 |
+
mod.consolidate([manifest], tmp_path / "out", workers=2)
|
| 195 |
+
first = list(overlay_rows(tmp_path / "out"))
|
| 196 |
+
mod.consolidate([manifest], tmp_path / "out", workers=2)
|
| 197 |
+
assert first == list(overlay_rows(tmp_path / "out"))
|
| 198 |
+
with pytest.raises(ValueError, match="escapes"):
|
| 199 |
+
resolve_file(tmp_path / "out/images", "../../source/sample.png")
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
@pytest.mark.parametrize('directory_link', [False, True])
|
| 203 |
+
def test_optimized_resolver_rejects_symlink_escape(tmp_path, directory_link):
|
| 204 |
+
folder = tmp_path / 'package'
|
| 205 |
+
folder.mkdir()
|
| 206 |
+
outside = tmp_path / 'outside'
|
| 207 |
+
outside.mkdir()
|
| 208 |
+
(outside / 'file').write_text('private')
|
| 209 |
+
if directory_link:
|
| 210 |
+
(folder / 'link').symlink_to(outside, target_is_directory=True)
|
| 211 |
+
relative = 'link/file'
|
| 212 |
+
else:
|
| 213 |
+
(folder / 'link').symlink_to(outside / 'file')
|
| 214 |
+
relative = 'link'
|
| 215 |
+
with pytest.raises(ValueError, match='escapes'):
|
| 216 |
+
resolve_file(folder, relative)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def test_optimized_resolver_allows_internal_symlink(tmp_path):
|
| 220 |
+
(tmp_path / 'real').mkdir()
|
| 221 |
+
(tmp_path / 'real/file').write_text('data')
|
| 222 |
+
(tmp_path / 'link').symlink_to(tmp_path / 'real', target_is_directory=True)
|
| 223 |
+
assert resolve_file(tmp_path, 'link/file') == str(tmp_path / 'real/file')
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def test_duration_bins():
|
| 227 |
+
result = mod.durations([1., 10., 20., 30., 60., 120.])
|
| 228 |
+
assert sum(result["bins"].values()) == 6
|
| 229 |
+
assert set(result["bins"].values()) == {1}
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def make_audit(tmp_path, manifest, rows, accepted):
|
| 233 |
+
from psi.data.seed.causal_video_qa import point
|
| 234 |
+
folder = tmp_path / "audit/shard0"
|
| 235 |
+
folder.mkdir(parents=True)
|
| 236 |
+
(folder / "reviews").mkdir()
|
| 237 |
+
contract = folder / "contract.json"
|
| 238 |
+
contract.write_text(json.dumps(dict(version="causal_prefix_qa_v2", source_sha256=mod.digest(manifest))))
|
| 239 |
+
review = dict(asset_id="one", video_sha256=rows[0]["video_sha256"],
|
| 240 |
+
contract_sha256=mod.digest(contract), accepted=accepted,
|
| 241 |
+
causal_qa_points=[point(2.2)] if accepted else [])
|
| 242 |
+
(folder / "reviews/one.json").write_text(json.dumps(review))
|
| 243 |
+
return folder.parent
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@pytest.mark.parametrize("accepted", [True, False])
|
| 247 |
+
def test_refresh_pending_without_repacking(tmp_path, accepted):
|
| 248 |
+
manifest, rows = source(tmp_path, video=True)
|
| 249 |
+
dest = tmp_path / "out"
|
| 250 |
+
mod.consolidate([manifest], dest, workers=1)
|
| 251 |
+
before = list(records(dest, accepted_only=False))[0]
|
| 252 |
+
inode = (dest / "videos" / before["media_path"]).stat().st_ino
|
| 253 |
+
audit = make_audit(tmp_path, manifest, rows, accepted)
|
| 254 |
+
assert mod.refresh_reviews(dest, audit)["changed"] == 1
|
| 255 |
+
assert len(list(overlay_rows(dest))) == (8 if accepted else 0)
|
| 256 |
+
assert (dest / "videos" / before["media_path"]).stat().st_ino == inode
|
| 257 |
+
assert mod.refresh_reviews(dest, audit)["changed"] == 0
|
| 258 |
+
assert json.loads((dest / "videos/summary.json").read_text())["counts"]["pending_questions"] == 0
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def test_audit_contract_change_rejected(tmp_path):
|
| 262 |
+
manifest, rows = source(tmp_path, video=True)
|
| 263 |
+
audit = make_audit(tmp_path, manifest, rows, True)
|
| 264 |
+
(audit / "shard0/contract.json").write_text('{"version":"old"}')
|
| 265 |
+
with pytest.raises(ValueError, match="policy"):
|
| 266 |
+
mod.consolidate([manifest], tmp_path / "out", audit_root=audit, workers=1)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def test_transient_io_retry_and_full_disk_not_swallowed(monkeypatch):
|
| 270 |
+
import errno
|
| 271 |
+
from unittest.mock import Mock
|
| 272 |
+
monkeypatch.setattr(mod.time, "sleep", lambda _: None)
|
| 273 |
+
action = Mock(side_effect=[OSError(errno.EIO, "backend read"), 7])
|
| 274 |
+
assert mod.retry_io(action, "fixture") == 7
|
| 275 |
+
assert action.call_count == 2
|
| 276 |
+
full = Mock(side_effect=OSError(errno.ENOSPC, "quota"))
|
| 277 |
+
with pytest.raises(OSError, match="quota"):
|
| 278 |
+
mod.retry_io(full, "fixture")
|
| 279 |
+
assert full.call_count == 1
|
| 280 |
+
persistent = Mock(side_effect=OSError(errno.EIO, "broken file"))
|
| 281 |
+
with pytest.raises(OSError, match="broken file"):
|
| 282 |
+
mod.retry_io(persistent, "fixture")
|
| 283 |
+
assert persistent.call_count == 4
|
tests/test_vqa_review_dashboard.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU-only tests; never modify real data or human notes."""
|
| 2 |
+
import importlib.util
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import tempfile
|
| 6 |
+
import threading
|
| 7 |
+
import unittest
|
| 8 |
+
from unittest.mock import patch
|
| 9 |
+
from urllib.error import HTTPError
|
| 10 |
+
from urllib.request import Request, urlopen
|
| 11 |
+
|
| 12 |
+
SCRIPT = Path(__file__).resolve().parents[1] / 'scripts/data/review_dashboard/server.py'
|
| 13 |
+
spec = importlib.util.spec_from_file_location('vqa_dashboard', SCRIPT)
|
| 14 |
+
app = importlib.util.module_from_spec(spec)
|
| 15 |
+
spec.loader.exec_module(app)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ReviewTests(unittest.TestCase):
|
| 19 |
+
def test_progress_assets_do_not_escape_proxy_prefix(self):
|
| 20 |
+
from urllib.parse import urljoin
|
| 21 |
+
base='https://example.test/proxy/8770/progress'
|
| 22 |
+
js=(app.HERE/'progress.js').read_text()
|
| 23 |
+
self.assertIn("fetch('api/audit-progress'",js)
|
| 24 |
+
self.assertNotIn("fetch('/api/",js)
|
| 25 |
+
self.assertEqual(urljoin(base,'api/audit-progress'),'https://example.test/proxy/8770/api/audit-progress')
|
| 26 |
+
self.assertIn('href="./"',(app.HERE/'progress.html').read_text())
|
| 27 |
+
self.assertIn('href="progress"',(app.HERE/'index.html').read_text())
|
| 28 |
+
|
| 29 |
+
def test_range(self):
|
| 30 |
+
self.assertEqual(app.byte_range(None, 10), (0, 9, False))
|
| 31 |
+
self.assertEqual(app.byte_range('bytes=1-4', 10), (1, 4, True))
|
| 32 |
+
self.assertEqual(app.byte_range('bytes=2-', 10), (2, 9, True))
|
| 33 |
+
self.assertEqual(app.byte_range('bytes=-3', 10), (7, 9, True))
|
| 34 |
+
self.assertEqual(app.byte_range('bytes=1-999', 10), (1, 9, True))
|
| 35 |
+
for bad in ['bytes=10-', 'bytes=9-1', 'bytes=-0', 'bytes=-', 'bytes=0-1,4-5', 'nonsense']:
|
| 36 |
+
with self.assertRaises(ValueError): app.byte_range(bad, 10)
|
| 37 |
+
|
| 38 |
+
def test_statuses_not_invented(self):
|
| 39 |
+
self.assertEqual(app.classify('gqa', False, {'accepted':True}, {})[0], 'not_admitted')
|
| 40 |
+
self.assertEqual(app.classify('gqa', False, {'accepted':False}, {})[0], 'excluded')
|
| 41 |
+
self.assertEqual(app.classify('gqa', False, {}, {})[0], 'pending')
|
| 42 |
+
self.assertEqual(app.classify('gqa', True, {}, {'training_ready':False})[0], 'admitted')
|
| 43 |
+
self.assertEqual(app.classify('legacy_video', False, {'accepted':True}, {})[0], 'legacy')
|
| 44 |
+
|
| 45 |
+
def fixture(self, root):
|
| 46 |
+
data, state = root / 'data', root / 'state'
|
| 47 |
+
original, release = data / 'original', data / 'release'
|
| 48 |
+
(original / 'visual_review').mkdir(parents=True)
|
| 49 |
+
(release / 'admission').mkdir(parents=True)
|
| 50 |
+
(original / 'pic.jpg').write_bytes(b'0123456789')
|
| 51 |
+
candidates = [dict(id=str(i), question='Q<script>alert(1)</script>', answer='A', split='train', image_path=str(original / 'pic.jpg')) for i in range(4)]
|
| 52 |
+
(original / 'candidates.json').write_text(json.dumps(candidates))
|
| 53 |
+
for i, accepted in [(0,True), (1,True), (2,False)]:
|
| 54 |
+
(original / 'visual_review' / f'{i}.json').write_text(json.dumps(dict(accepted=accepted)))
|
| 55 |
+
assets = [dict(candidates[0], asset_id='gqa_0', voice=f'voice_{v}') for v in range(8)]
|
| 56 |
+
manifest = release / 'overlay_assets.json'
|
| 57 |
+
manifest.write_text(json.dumps(dict(assets=assets)))
|
| 58 |
+
(release / 'admission/acceptance.json').write_text(json.dumps(dict(passed=True, manifest_sha256=app.digest(manifest))))
|
| 59 |
+
return data, state
|
| 60 |
+
|
| 61 |
+
def test_index_api_and_notes(self):
|
| 62 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 63 |
+
data, state = self.fixture(Path(tmp))
|
| 64 |
+
original_hash = app.digest(data / 'original/candidates.json')
|
| 65 |
+
with patch.object(app, 'SOURCES', {'gqa':('GQA','image','original','release')}):
|
| 66 |
+
app.build(data, state)
|
| 67 |
+
c = app.Catalog(state, data)
|
| 68 |
+
self.assertEqual(c.listing({})['total'], 1)
|
| 69 |
+
self.assertEqual(c.listing({'scope':'candidates'})['total'], 4)
|
| 70 |
+
self.assertEqual(c.listing({'scope':'excluded'})['total'], 2)
|
| 71 |
+
self.assertEqual(c.listing({'scope':'pending'})['total'], 1)
|
| 72 |
+
self.assertEqual(c.listing({'scope':'candidates','review':'yes'})['total'], 2)
|
| 73 |
+
self.assertEqual(c.listing({'q':"' OR 1=1 --"})['total'], 0)
|
| 74 |
+
detail = c.detail('gqa:gqa_0')
|
| 75 |
+
self.assertEqual(len(detail['voices']), 8)
|
| 76 |
+
c.annotate({'id':'gqa:gqa_0','verdict':'reject','note':'对答案存疑'})
|
| 77 |
+
self.assertEqual(c.detail('gqa:gqa_0')['human']['note'], '对答案存疑')
|
| 78 |
+
self.assertEqual(c.listing({'human':'reject'})['total'], 1)
|
| 79 |
+
app.build(data, state)
|
| 80 |
+
self.assertEqual(c.detail('gqa:gqa_0')['human']['verdict'], 'reject')
|
| 81 |
+
self.assertEqual(app.digest(data / 'original/candidates.json'), original_hash)
|
| 82 |
+
with self.assertRaises(KeyError): c.file('../../etc/passwd')
|
| 83 |
+
outside = Path(tmp) / 'secret.jpg'; outside.write_bytes(b'secret')
|
| 84 |
+
(data / 'escape.jpg').symlink_to(outside)
|
| 85 |
+
self.assertIsNone(app.allowed_path(data / 'escape.jpg', data))
|
| 86 |
+
|
| 87 |
+
server = app.ThreadingHTTPServer(('127.0.0.1', 0), app.handler(c))
|
| 88 |
+
thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
|
| 89 |
+
base = f'http://127.0.0.1:{server.server_port}'
|
| 90 |
+
try:
|
| 91 |
+
with urlopen(base+'/') as r: self.assertIn('视觉问答'.encode(), r.read())
|
| 92 |
+
with urlopen(base+'/progress') as r: self.assertIn('审核进度'.encode(),r.read())
|
| 93 |
+
with urlopen(base+'/api/audit-progress') as r: self.assertTrue(json.load(r)['stale'])
|
| 94 |
+
import time
|
| 95 |
+
(state/'audit_progress.json').write_text(json.dumps(dict(updated_at=time.time(),checked=12)))
|
| 96 |
+
with urlopen(base+'/api/audit-progress') as r:
|
| 97 |
+
status=json.load(r); self.assertFalse(status['stale']);self.assertEqual(status['checked'],12)
|
| 98 |
+
req = Request(base+'/media/'+detail['media'], headers={'Range':'bytes=2-5'})
|
| 99 |
+
with urlopen(req) as r:
|
| 100 |
+
self.assertEqual(r.status, 206); self.assertEqual(r.read(), b'2345')
|
| 101 |
+
self.assertEqual(r.headers['Content-Range'], 'bytes 2-5/10')
|
| 102 |
+
with self.assertRaises(HTTPError) as error:
|
| 103 |
+
urlopen(Request(base+'/media/'+detail['media'], headers={'Range':'bytes=999-'}))
|
| 104 |
+
self.assertEqual(error.exception.code, 416)
|
| 105 |
+
with self.assertRaises(HTTPError) as error:
|
| 106 |
+
urlopen(Request(base+'/api/review', data=b'{}', headers={'Content-Type':'application/json','Origin':'http://evil.test'}))
|
| 107 |
+
self.assertEqual(error.exception.code, 403)
|
| 108 |
+
body=json.dumps(dict(id='gqa:gqa_0',verdict='pass',note='checked')).encode()
|
| 109 |
+
with urlopen(Request(base+'/api/review', data=body, headers={'Content-Type':'application/json','Origin':base})) as r:
|
| 110 |
+
self.assertTrue(json.load(r)['saved'])
|
| 111 |
+
finally: server.shutdown(); server.server_close(); thread.join()
|
| 112 |
+
|
| 113 |
+
def test_reject_bad_acceptance(self):
|
| 114 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 115 |
+
data, state = self.fixture(Path(tmp))
|
| 116 |
+
(data / 'release/admission/acceptance.json').write_text('{"passed":true,"manifest_sha256":"wrong"}')
|
| 117 |
+
with patch.object(app, 'SOURCES', {'gqa':('GQA','image','original','release')}):
|
| 118 |
+
with self.assertRaises(ValueError): app.build(data, state)
|
| 119 |
+
self.assertFalse((state/'catalog.sqlite').exists())
|
| 120 |
+
|
| 121 |
+
def test_reject_missing_voice(self):
|
| 122 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 123 |
+
data, state = self.fixture(Path(tmp))
|
| 124 |
+
manifest = data/'release/overlay_assets.json'
|
| 125 |
+
value = json.loads(manifest.read_text()); value['assets'].pop()
|
| 126 |
+
manifest.write_text(json.dumps(value))
|
| 127 |
+
(data/'release/admission/acceptance.json').write_text(json.dumps(dict(passed=True, manifest_sha256=app.digest(manifest))))
|
| 128 |
+
with patch.object(app, 'SOURCES', {'gqa':('GQA','image','original','release')}):
|
| 129 |
+
with self.assertRaisesRegex(ValueError, 'eight unique'): app.build(data, state)
|
| 130 |
+
self.assertFalse((state/'catalog.sqlite').exists())
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
if __name__ == '__main__': unittest.main()
|
train_dlc.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# 八卡:训练 + 自动推理 + 看板;checkpoint 本地保存,后台校验回传 CPFS。
|
| 3 |
+
set -Eeuo pipefail
|
| 4 |
+
# 与本地入口共用40维 + FP32动作输入 recipe,推理读取 checkpoint 同一设置。
|
| 5 |
+
PROJECT_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
| 6 |
+
source "$PROJECT_ROOT/scripts/activate_psi_env.sh"
|
| 7 |
+
export PYTHONPATH="$PROJECT_ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
|
| 8 |
+
# 可调 HFD_TRAIN_BATCH_SIZE(每卡,默认8)、HFD_DLC_LOCAL_ROOT、HFD_DLC_BACKUP_ROOT。
|
| 9 |
+
exec python -u "$PROJECT_ROOT/scripts/launch_hfd_dlc.py" "$@"
|
uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|