diff --git a/.agents/STATUS.md b/.agents/STATUS.md deleted file mode 100644 index 1583abba56..0000000000 --- a/.agents/STATUS.md +++ /dev/null @@ -1,94 +0,0 @@ -# Agent Infrastructure — Status Dashboard - -Developer-maintained overview of all agent components and their maturity. -Use this to understand what exists, how complete it is, and how much to trust it. - -_Last synced: 2026-03-02_ - -> To resync this dashboard, use the workflow: `.agents/workflows/sync-dashboard.md` - ---- - -## Summary - -| Category | Total | ✅ Ready | 🟡 Draft | 🔴 Stub | Trust | -|----------|-------|---------|---------|---------|-------| -| Skills | 8 | 0 | 8 | 0 | Low — newly created, untested | -| Workflows (SOPs) | 4 | 0 | 4 | 0 | Low — newly created, untested | -| Memory files | 4 | 1 | 3 | 0 | Medium — codebase_map is solid | -| Lessons | 0 | — | — | — | N/A — empty | -| Exploration logs | 0 | — | — | — | N/A — empty | - ---- - -## Skills (`.agents/skills/`) - -| Skill | File | Status | Trust | Tested | Notes | -|-------|------|--------|-------|--------|-------| -| Launch Experiment | `launch-experiment.md` | 🟡 Draft | Low | ❌ | Needs dry-run validation | -| Monitor Experiment | `monitor-experiment.md` | 🟡 Draft | Low | ❌ | Requires W&B API access to test | -| Summarize Run | `summarize-run.md` | 🟡 Draft | Low | ❌ | Pattern from existing test infra | -| Log Experiment | `log-experiment.md` | 🟡 Draft | Low | ❌ | Journal formatting only | -| Evaluate Video Quality | `evaluate-video-quality.md` | 🟡 Draft | Low | ❌ | SSIM section most mature | -| Index Related Work | `index-related-work.md` | 🟡 Draft | Low | ❌ | Schema defined, no entries yet | -| Search Related Work | `search-related-work.md` | 🟡 Draft | Low | ❌ | Depends on indexed entries | -| Skill Template | `SKILL_TEMPLATE.md` | ✅ Ready | High | ✅ | Meta-template, stable | - -### Trust Level Definitions -- **High**: Tested in production, validated against real experiments -- **Medium**: Logic is sound, partially tested or based on existing patterns -- **Low**: Newly written, not yet validated -- **None**: Placeholder only - ---- - -## Workflows / SOPs (`.agents/workflows/`) - -| Workflow | File | Status | Trust | Tested | Notes | -|----------|------|--------|-------|--------|-------| -| Experiment Lifecycle | `experiment-lifecycle.md` | 🟡 Draft | Low | ❌ | End-to-end flow, untested | -| Evaluation Development | `evaluation-development.md` | 🟡 Draft | Low | ❌ | Metric dev process | -| Experiment Journaling | `experiment-journaling.md` | 🟡 Draft | Low | ❌ | Journaling cadence | -| Lesson Capture | `lesson-capture.md` | 🟡 Draft | Low | ❌ | Post-experiment reflection | -| Sync Dashboard | `sync-dashboard.md` | 🟡 Draft | Low | ❌ | This dashboard's updater | - ---- - -## Memory (`.agents/memory/`) - -| File | Status | Trust | Notes | -|------|--------|-------|-------| -| `codebase_map.md` | ✅ Ready | High | Synthesized from full repo research | -| `experiment_journal.md` | 🟡 Draft | Medium | Schema defined, no entries yet | -| `evaluation_registry.md` | 🟡 Draft | Medium | SSIM/loss metrics documented | -| `related_work/README.md` | 🟡 Draft | Medium | Schema defined, no entries yet | - ---- - -## Lessons (`.agents/lessons/`) - -| File | Category | Severity | Notes | -|------|----------|----------|-------| - -_No lessons captured yet._ - ---- - -## Exploration Logs (`.agents/exploration/`) - -| File | Status | Topic | Notes | -|------|--------|-------|-------| - -_No exploration logs yet._ - ---- - -## What to Do Next - -1. **Validate skills**: Run a minimal training experiment using the - `experiment-lifecycle` SOP to test `launch-experiment` → `monitor-experiment` - → `summarize-run` end-to-end. -2. **Index first related work**: Use `index-related-work` to add at least one - paper (e.g., the Self-Forcing paper used in the codebase). -3. **Capture first lesson**: After the validation run, capture any findings. -4. **Promote to Ready**: As each skill/SOP is tested, update its status here. diff --git a/.agents/memory/dreamverse-integration/README.md b/.agents/memory/dreamverse-integration/README.md new file mode 100644 index 0000000000..489230c156 --- /dev/null +++ b/.agents/memory/dreamverse-integration/README.md @@ -0,0 +1,201 @@ +# Dreamverse Integration — Memory Index + +Living knowledge base for the FastVideo ↔ Dreamverse ↔ Dynamo integration. +Tracks the public API refactor (PRs 0-17), the LTX-2 streaming server +upstream, the Dreamverse switch from `FastVideo-internal` to public +`FastVideo`, and the NVFP4 quantization landing. + +**Last reconciled:** 2026-05-06 (**D-26** EXECUTED — rebased +`will/dreamverse-monorepo` directly onto `origin/main` (`c17d33bf`) +via `git rebase origin/main`; 66 commits cleanly replayed; force- +pushed via `--force-with-lease`. New tip `83829c5e`. Local backup +branch `will/dreamverse-monorepo-pre-main-rebase-backup-20260506` +preserved at the pre-rebase tip `2ee839a3`. PR #1288 on +`will/ltx2_sr_port` is untouched. The branch is now ready to open +as a single PR against main. + +**Earlier — D-21** EXECUTED — chunk-stutter root cause +analysis + NVENC build path + opt-in `--nvenc` flag + benchmark regression +test. 3 parallel explore agents confirmed apps/dreamverse matches +FastVideo-internal byte-for-byte on NVFP4 + torch.compile coverage; stutter +is NOT a regression. Software libx264 encoding consumes ~22% of segment +wall-time. Built ffmpeg with NVENC support; B200 silicon doesn't have NVENC +encoder hardware so the path is currently moot on this dev host but works +on RTX 50-series / T4 / A10 deploys. Benchmark captured libx264 ultrafast +at 611ms median (8.25x realtime in isolation). Open follow-ups D-22/D-23/D-24. + +**Earlier — D-20** EXECUTED — segment-2 BrokenPipe +root cause was a TWO-direction silent drop of LTX-2 audio kwargs in +public `VideoGenerator` (inbound `SamplingParam.update()` rejected +`audio_num_frames`/`ltx2_audio_clean_latent`/etc. as unknown fields and +`logger.error`'d, outbound result dict didn't surface +`ltx2_audio_latents` from `output_batch.extra`). Ported the +FastVideo-internal extra-overrides routing block + made `update()` +strict + added regression test (7 tests, all pass) + landed 4 commits +on `will/dreamverse-monorepo` @ `5eaf0a13` (11 commits ahead of +`fbd823df`). End-to-end verified on GPU4: `Cached audio latents shape +=(1, 8, 126, 16) for segment 2`, `Segment 2: relayed av chunks=22, +bytes=3.8MB`, no BrokenPipeError. Public-API fix needs cherry-pick to +`will/ltx2_sr_port` for PR #1288 — see open-threads.md item D-20-CP. +**D-19** EXECUTED previously: Dreamverse migration landed on +`will/dreamverse-monorepo` @ `c1fe5d4c` (5 commits ahead of +`will/ltx2_sr_port` HEAD `fbd823df`). 164 files, 53,294 LOC, 31,725 +files under `apps/dreamverse/`. e2e PASSES against migrated code (8/8 +Playwright in 5.1s, `/proc/$PID/cwd` verified). Significant deviation +from [integration-plan.md](integration-plan.md): the plan's "DELETE +generic-merged from Dreamverse, import public substitutes" assumption +was invalid (public APIs aren't drop-ins) — generic-merged files now +carried PRODUCT-LOCAL inside `apps/dreamverse/server/`. Public +`fastvideo.entrypoints.streaming.*` reverts to `fbd823df` state. See +[decisions-log.md D-19](decisions-log.md#d-19) + +[D-20](decisions-log.md#d-20) for full context.). +FastVideo `will/ltx2_sr_port` @ HEAD (post-D-17 STACK.md removal + +integration-review.md addition + integration-plan.md addition + D-18 +reconciliation). Dreamverse `will/integrate-public-fastvideo` @ `ec8ef92`. +PRs #1257 / #1258 / #1284 / #1286 MERGED to main. **PR #1287 CLOSED +(in favor of consolidation); PR #1288 OPEN as the single mega-PR +landing the entire `will/ltx2_sr_port` chain at once** (LTX-2 SR +runtime + NVFP4 + `generate_async`/Dynamo contract + agents memory dir). +Split branches kept as historical bookmarks; STACK.md model **abandoned** — +see [decisions-log.md D-17](decisions-log.md#d-17). Local backup +`will/ltx2_sr_port-pre-1286-rebase` @ `1baa60bb` preserves the +pre-rebase chain. + +## Fresh-context onboarding (read in order) + +If you're an agent picking up this work for the first time, do these +**5 things in this order**. Once done, you have full context to continue +any open thread, commit correctly, push, and propagate to the open PR. + +1. **Confirm worktree state** — run the "First 60 seconds" block in + [runbook.md](runbook.md). Tells you the branch is right, services + are up, and PR #1286's head matches what this dir claims. + +2. **Read [state.md](state.md)** — single-page snapshot of branch tips, + live services, test status, pre-existing failures, "do not pop" + stashes. + +3. **Read [pr-roadmap.md](pr-roadmap.md)** — what PRs landed, what's in + flight, what's planned. Identifies the active open PR (currently + #1286) and where it sits in the dependency chain. + +4. **Read [open-threads.md](open-threads.md)** — prioritized work items + with effort estimates and dependencies. The "Recommended pull order" + section is a ready-made TODO list if you need one. + +5. **Skim [runbook.md](runbook.md) end-to-end** — operational how-to: + verify, commit (with co-author trailers), push, propagate to PR + #1286, maintain the memory dir, and the "Common pitfalls" section + that catches the recurring traps. + +Skip the deep-context docs (design / streaming-server / cross-repo / +quantization / decisions-log) until you need them — they're indexed in +the "Deep-dive reading guide" below. + +Final check: run the "Self-test" block at the bottom of +[runbook.md](runbook.md). If you can answer all 8 questions from this +dir alone, you're ready. If you can't, the gap is a memory-dir bug — +file it in [open-threads.md](open-threads.md) before continuing. + +## Deep-dive reading guide + +| Question / task | File | +|---|---| +| "What's running right now? What just landed?" | [state.md](state.md) | +| "How do I commit / push / propagate to PR #1286?" | [runbook.md](runbook.md) | +| "Why is the schema typed this way? What's the philosophy?" | [design.md](design.md) | +| "What PRs landed? In flight? Planned?" | [pr-roadmap.md](pr-roadmap.md) | +| "Streaming server, `generate_async`, `build_app` routes?" | [streaming-server.md](streaming-server.md) | +| "How does Dreamverse use FastVideo? What about Dynamo?" | [cross-repo-surfaces.md](cross-repo-surfaces.md) | +| "NVFP4? Layer profiles? `LinearBase` fallback? AbsMaxFP8?" | [quantization.md](quantization.md) | +| "Why was decision X made? What's resolved vs. open?" | [decisions-log.md](decisions-log.md) | +| "What should I work on next? Priority order?" | [open-threads.md](open-threads.md) | +| "Who should be co-authored on commits in this scope?" | [authors.md](authors.md) | +| "How do we execute the Dreamverse → FastVideo monorepo merge?" | [integration-plan.md](integration-plan.md) ← **CURRENT** | +| "Historical drift audit + Option-D evaluation (deprecated by D-18)" | [integration-review.md](integration-review.md) (DEPRECATED) | + +## Repo + worktree paths + +| Repo | Path | Active branch | +|---|---|---| +| FastVideo (public) | `/home/william5lin/FastVideo` | `will/ltx2_sr_port` | +| Dreamverse | `/home/william5lin/Dreamverse` | `will/integrate-public-fastvideo` | +| FastVideo-internal (read-only ref) | `/home/william5lin/FastVideo-internal` | their `main` | +| Dynamo (read-only ref) | `/home/william5lin/dynamo` | upstream | + +## Glossary + +- **NVFP4**: NVIDIA's specific block-scaled FP4 (e2m1 mantissa, fp32 alpha, + `layout_128x4` scale layout, group size 16). Distinct from MX-FP4 / OCP-FP4. +- **`GeneratorConfig`**: typed init-time public config (model_path, engine, + pipeline). Replaces flat `from_pretrained(**kwargs)`. +- **`GenerationRequest`**: typed per-call request (prompt, inputs, sampling, + runtime, output, stage_overrides, state, plan, extensions). Replaces flat + `generate_video(**kwargs)`. +- **`ServeConfig`** / **`RunConfig`**: top-level YAML envelopes. ServeConfig + for `fastvideo serve`; RunConfig for offline `fastvideo generate`. +- **`InferencePreset`**: model-owned named preset (e.g. `ltx2_two_stage`) + defining stage topology + per-stage defaults + valid override types. +- **`ContinuationState`**: opaque round-trip state envelope `{kind, payload}`. + Hybrid: server-held for streaming WS, client-round-trip for stateless HTTP. +- **`generate_async`**: future canonical async exec API (PR 7.10) yielding + `VideoProgressEvent` / `VideoPartialEvent` / `VideoFinalEvent`. Substrate + for streaming server, OpenAI server, AND Dynamo backend. +- **`build_app`**: FastAPI app factory in + `fastvideo.entrypoints.streaming.server`. Currently exposes only + `/health` + `/v1/stream`. FE-required `/healthz`+`/readyz`+`/status` + migration is open follow-up #1. +- **`LLMProvider`**: protocol abstraction for prompt enhancer providers + (cerebras, cerebras_ifm, groq). Public schema currently restricts to + `Literal["cerebras", "groq"]`; `cerebras_ifm` is internal-only. +- **`compat.py`**: legacy kwargs translation layer (~370 lines). Scheduled + for death across PRs 14-17. +- **`prepare_for_compile`**: duck-type protocol method called via + `getattr(module, "prepare_for_compile", None)` before `torch.compile`. + Currently only Gemma3 implements it. +- **`SubprocessGpuPool`**: PR 7.6 public replacement for the internal + `realtime/local_runtime.GPUPool`. Per-GPU subprocess workers, typed + `GeneratorConfig` boundary. +- **PR 5.5**: streaming server subpackage skeleton — adds + `fastvideo/entrypoints/streaming/` parallel to `openai/`. +- **PR 7.10**: the unlock PR. Closes Q-5 (audio re-encode), Q-9 (Dynamo + progress), and PR 7.5's mid-segment cancellation TODO simultaneously. + +## Live process map (as of 2026-05-03) + +| Port | Service | Source | +|---|---|---| +| 8009 | `dreamverse-server` | running, `/readyz` 200, 1 warmed GPU worker | +| 5274 | `next-server` (dev) | running | +| 8000 | unknown FastAPI | not in handoff — verify before launching new BE | + +## How this directory is maintained + +- Source of truth for the integration story. Update when state changes. +- Each file has a "Last updated" header; bump when you edit. +- Cross-reference siblings via relative links; do NOT duplicate content. +- New entries: register in `../index.jsonl`. +- These files supersede the untracked source docs in the repo root and + `.agents/exploration/` — see [state.md](state.md) "Untracked but + present" section for disposition. + +## Source documents (archived 2026-05-03) + +The 7 source docs that this directory consolidates have been moved into +[`source-archive/`](source-archive/). They remain available for agents +who want the full unsynthesized rationale, but the synthesized memory +files in this dir are the canonical source of truth. + +| Source doc | Lines | Synthesized into | +|---|---|---| +| [`source-archive/apirefactor.md`](source-archive/apirefactor.md) | 838 | [design.md](design.md) | +| [`source-archive/PR-plan.md`](source-archive/PR-plan.md) | 1145 | [pr-roadmap.md](pr-roadmap.md) | +| [`source-archive/dreamverse_review.md`](source-archive/dreamverse_review.md) | 390 | [state.md](state.md) + [decisions-log.md](decisions-log.md) | +| [`source-archive/handoff-nvfp4-launch-demo.md`](source-archive/handoff-nvfp4-launch-demo.md) | 518 | [state.md](state.md) + [quantization.md](quantization.md) + [open-threads.md](open-threads.md) | +| [`source-archive/streaming-server-upstream-plan.md`](source-archive/streaming-server-upstream-plan.md) | 539 | [streaming-server.md](streaming-server.md) + [decisions-log.md](decisions-log.md) | +| [`source-archive/dreamverse_integration.md`](source-archive/dreamverse_integration.md) | 285 | [cross-repo-surfaces.md](cross-repo-surfaces.md) | +| [`source-archive/video-generator-config-api-design.md`](source-archive/video-generator-config-api-design.md) | 93 | [design.md](design.md) (early-draft material) | +| `.agents/exploration/pr-link-review.md` | 29 | already promoted to `.agents/skills/review-pr-link/` (kept in exploration dir) | + +See [`source-archive/README.md`](source-archive/README.md) for the +archive policy. diff --git a/.agents/memory/dreamverse-integration/authors.md b/.agents/memory/dreamverse-integration/authors.md new file mode 100644 index 0000000000..4c15d24fa1 --- /dev/null +++ b/.agents/memory/dreamverse-integration/authors.md @@ -0,0 +1,150 @@ +# Authors — Dreamverse Integration + +**Status:** PERMANENT — keep around as the source of truth for who collaborated +on the dreamverse-integration work, even after every PR in the integration +scope has merged. +**Last updated:** 2026-05-05 (strategy reversal — single mega-PR #1288 on `will/ltx2_sr_port` replaces planned 6-PR split; #1287 closed; per [decisions-log.md D-17](decisions-log.md#d-17)) + +This file documents the human co-authors credited on every commit in the +dreamverse-integration scope (FastVideo public-API refactor, streaming server +upstream, GPU pool, prompt enhancer, NVFP4 wire-up, LTX-2 SR port). The +4 collaborators below worked on the FastVideo-internal precursor of this code +and are credited as co-authors on every public-side upstream commit via Git's +standard +[`Co-authored-by`](https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors) +trailer convention. + +Scope-wise this is the dreamverse-integration-flavored mirror of the +top-level [`CO-AUTHORS.md`](../../../CO-AUTHORS.md), which is scoped to the +broader `will/ltx2_sr_port` 10-PR stack. The roster is identical; this file +exists so the dreamverse-integration memory dir is self-contained and +discoverable without traversing to the repo root. + +## Co-author roster + +| GitHub user | Real name | GitHub ID | Trailer email | +|---|---|---|---| +| [`@Davids048`](https://github.com/Davids048) | Junda (David) Su | 90978028 | `90978028+Davids048@users.noreply.github.com` | +| [`@RandNMR73`](https://github.com/RandNMR73) | Matthew Noto | 99706358 | `99706358+RandNMR73@users.noreply.github.com` | +| [`@XOR-op`](https://github.com/XOR-op) | (unset) | 17672363 | `17672363+XOR-op@users.noreply.github.com` | +| [`@jzhang38`](https://github.com/jzhang38) | Zhang Peiyuan | 42993249 | `42993249+jzhang38@users.noreply.github.com` | + +## Verification — where these trailers appear + +Verified via `gh pr view --json commits --jq '.commits[].messageBody'` +across every PR in the integration scope: + +| PR | Branch | Status | Trailers present on every commit | +|---|---|---|---| +| #1257 | `will/api_7.6` (GPU pool upstream) | ✅ merged 2026-05-04 | yes (4/4) | +| #1258 | `will/api_7.7` (prompt enhancer + LLMProvider) | ✅ merged 2026-05-04 | yes (3/3) | +| #1284 | `will/api_7.8` (streaming auxiliaries) | ✅ merged 2026-05-04 | yes (2/2) | +| #1286 | `will/api_7.9` (streaming router) | ✅ merged 2026-05-05 at `2aaeee2a` (squash) | yes on commits 1-3; commit `a152cb77` (`[fix] streaming: router polish`) was missing trailers but got squashed into the merge commit, so the merge commit on main inherits the trailers from the other 3. The trailerless cherry-pick partner (`40e265b8` on `will/ltx2_sr_port`) was dropped by the post-#1286 rebase — gap permanently resolved. | +| #1287 | `will/api_7.10` (`generate_async` + `VideoEvent`) | ❌ CLOSED 2026-05-05 — superseded by #1288 per [D-17](decisions-log.md#d-17) | yes on all 3 commits (now part of #1288's chain) | +| **#1288** | **`will/ltx2_sr_port`** (mega-PR — full stack: SR runtime + NVFP4 + generate_async + Dynamo contract + agents memory + integration-review) | 🟢 OPEN, MERGEABLE at `b36bdbc9`, 36 commits / 70 files / ~+13.0k LOC (post STACK.md removal) | yes on all 36 commits | + +Aggregate count across `will/ltx2_sr_port` (top of stack) at the time of +writing: 32-33 commits per co-author, matching the 32 commits in the stack +on top of base `cfccd292`. Numbers stay consistent because the rebase +command (see "How the trailers were applied" below) walks every commit. + +## Trailer block (copy-paste ready) + +The trailers added to every commit on `will/ltx2_sr_port` and every +dreamverse-integration PR: + +``` +Co-authored-by: Junda (David) Su <90978028+Davids048@users.noreply.github.com> +Co-authored-by: Matthew Noto <99706358+RandNMR73@users.noreply.github.com> +Co-authored-by: XOR-op <17672363+XOR-op@users.noreply.github.com> +Co-authored-by: Zhang Peiyuan <42993249+jzhang38@users.noreply.github.com> +``` + +For one-off `git commit -m` invocations, use `--trailer` flags: + +```bash +git commit -m "..." \ + --trailer "Co-authored-by: Junda (David) Su <90978028+Davids048@users.noreply.github.com>" \ + --trailer "Co-authored-by: Matthew Noto <99706358+RandNMR73@users.noreply.github.com>" \ + --trailer "Co-authored-by: XOR-op <17672363+XOR-op@users.noreply.github.com>" \ + --trailer "Co-authored-by: Zhang Peiyuan <42993249+jzhang38@users.noreply.github.com>" +``` + +`--trailer` is idempotent (dedupes by full `key: value`) so re-running is safe. + +## Why no-reply emails + +GitHub's `+@users.noreply.github.com` form is the most reliable +way to link a `Co-authored-by` trailer to a GitHub account. It: + +- Always works regardless of whether the user has a public verified email +- Survives the user changing their primary email +- Doesn't expose anyone's personal email to git history +- Is the format GitHub itself produces when you click "Add co-author" in the + web UI + +(All 4 collaborators have this email already used in `FastVideo-internal` +git history, verified via `git log --all` on that repo.) + +## How the trailers were applied (bulk rebase) + +```bash +git rebase --exec ' + git commit --amend --no-edit \ + --trailer "Co-authored-by: Junda (David) Su <90978028+Davids048@users.noreply.github.com>" \ + --trailer "Co-authored-by: Matthew Noto <99706358+RandNMR73@users.noreply.github.com>" \ + --trailer "Co-authored-by: XOR-op <17672363+XOR-op@users.noreply.github.com>" \ + --trailer "Co-authored-by: Zhang Peiyuan <42993249+jzhang38@users.noreply.github.com>" +' origin/main will/ltx2_sr_port +``` + +After running, re-slice all 10 split branches per [`STACK.md`](../../../STACK.md) +and force-push the published branches (`will/api_7.9`, `will/ltx2_sr_port`). + +## How to add a new co-author later + +1. Add the user to the roster table above (and the top-level + [`CO-AUTHORS.md`](../../../CO-AUTHORS.md) — keep them in sync). +2. Append their `Co-authored-by` line to the trailer block above. +3. Re-run the bulk rebase command on `will/ltx2_sr_port` — git's trailer + dedupe handles the existing 4; the new one gets appended. +4. Re-slice all split branches per [`STACK.md`](../../../STACK.md). +5. Force-push the published branches. + +## What we do NOT add + +Per the repo's top-level [`AGENTS.md`](../../../AGENTS.md): + +> Never add any coding agent or models such as Claude (or Claude Code), GPT, +> Codex or others as a co-author in commits or PRs. Do not include +> `Co-Authored-By: Claude ...` trailers or "Generated with Claude Code" and +> other such lines. + +So no `Co-authored-by: Claude `, no +`Generated with Claude Code` footer, no `Cursor ` +trailer (one such commit exists on `will/ltx2_sr_port` from a pre-policy +external contribution and stays grandfathered; new commits MUST NOT introduce +the pattern). Only human collaborators. + +## Known gaps + +**Resolved 2026-05-05 by the post-#1286 rebase.** The two trailerless +commits (`a152cb77` on `will/api_7.9` and `40e265b8` on +`will/ltx2_sr_port`) are no longer reachable from any active branch: + +- `a152cb77` was absorbed into squash merge `2aaeee2a` on main, which + inherits the trailers from the other 3 commits in the squash. +- `40e265b8` was dropped by the post-#1286 rebase of + `will/ltx2_sr_port`. + +Both still exist on the local backup `will/ltx2_sr_port-pre-1286-rebase` +for archeological reference. No further action needed. + +## See also + +- [`../../../CO-AUTHORS.md`](../../../CO-AUTHORS.md) — top-level stack-scoped + co-authors file (same roster, broader scope) +- [`../../../STACK.md`](../../../STACK.md) — 10-PR split layout for + `will/ltx2_sr_port` (re-slice commands live here) +- [`pr-roadmap.md`](pr-roadmap.md) — per-PR status within the + dreamverse-integration scope diff --git a/.agents/memory/dreamverse-integration/cross-repo-surfaces.md b/.agents/memory/dreamverse-integration/cross-repo-surfaces.md new file mode 100644 index 0000000000..155b9a2654 --- /dev/null +++ b/.agents/memory/dreamverse-integration/cross-repo-surfaces.md @@ -0,0 +1,277 @@ +# Cross-Repo Surfaces — Dreamverse + Dynamo + +How Dreamverse consumes FastVideo today, what's already shared, what's +ad hoc, and what migrations land alongside each PR. Plus the Dynamo +backend contract. + +For the streaming-server side see [streaming-server.md](streaming-server.md). +For the API design see [design.md](design.md). For PR sequence see +[pr-roadmap.md](pr-roadmap.md). + +**Last updated:** 2026-05-03. + +## The three surfaces + +Dreamverse depends on FastVideo across three surfaces (in order of +stability): + +1. **Pipeline construction** (stable) +2. **Realtime runtime** (in flight: PRs 7.5/7.6) +3. **Continuation state** (PR 7 typed; PR 7.6 wires server-held) + +## Surface 1: Pipeline construction (stable) + +`Dreamverse/server/video_generation.py:VideoGenerationWorker` calls +`VideoGenerator.from_pretrained(...)`. + +After PR 6 the typed `GeneratorConfig` path exists; **as of `d80c2a8` +(May 2)** Dreamverse migrated to the typed path: + +| Dreamverse usage | FastVideo public surface (post-PR 6) | +|---|---| +| `VideoGenerator.from_pretrained(model_path, ltx2_refine_enabled=…, …)` | `VideoGenerator.from_pretrained(config=GeneratorConfig(...))` | +| Flat `torch_compile_kwargs={…}` dict | `engine.compile.{backend,fullgraph,mode,dynamic,extras}` | +| `ltx2_vae_tiling=True` | `pipeline.vae_tiling=True` | +| `ltx2_refine_*` family | `pipeline.preset_overrides.refine.*` + `pipeline.components.upsampler_weights` | +| `enable_torch_compile_text_encoder` | `engine.compile.text_encoder_enabled` | + +Refine knobs moved from `ltx2_refine_*` flat kwargs into +`preset_overrides["refine"]`. **The in-memory `pipeline_config` pin** +(`dit_config.quant_config = NVFP4Config()`) keeps using the legacy +`experimental["pipeline_config"]` carrier because typed +`transformer_quant: "NVFP4"` doesn't yet support setting +`layer_profile` (see [open-threads.md](open-threads.md) follow-up #4 + +[quantization.md](quantization.md)). + +Legacy flat-kwarg path stays supported via `compat.py`; migration is +opt-in. PR 13's deprecation warnings are the eventual nudge. + +## Surface 2: Realtime runtime (in flight: PRs 7.5–7.6) + +`Dreamverse/server/runtime/factory.py` selects a runtime backend at +process start: + +```python +def create_runtime_pool() -> RuntimePool: + if os.getenv("FASTVIDEO_REALTIME_BASE_URL"): + return FastVideoRealtimePool(base_url=..., ws_url=..., default_model_id=...) + return GPUPool(get_available_gpus()) # in-process, wraps + # fastvideo.entrypoints.realtime.local_runtime +``` + +Both backends speak the same `RuntimePool` / `RuntimeSlot` Protocol +(`server/runtime/interfaces.py`): + +- `acquire(client_id, websocket=None) -> (gpu_id, RuntimeSlot)` +- `release(client_id)` +- `RuntimeSlot.{join_user, user_step, leave_user, register_stream_queue, ...}` + +Today both impls reach into FastVideo-internal's +`fastvideo.entrypoints.realtime.local_runtime` (which exposes +`RealtimeRuntimeConfig`, `GPUPool`, `GPUSlot`). The remote backend talks +HTTP+WS to a separately-deployed runtime of the same shape. + +**Contract that PR 7.5/7.6 must preserve:** + +- `RealtimeRuntimeConfig` accepts `model_registry`, `default_model_id`, + `default_height/width/num_frames/fps/num_inference_steps/guidance_scale/seed/negative_prompt`, + `default_ltx2_image_crf`, `startup_warmup_{enabled,prompt,timeout_seconds}`. +- `GPUPool(gpu_ids: list[int], config: RealtimeRuntimeConfig)` constructor. +- `pool.initialize() / shutdown() / acquire() / release() / get_status()`. +- HTTP endpoints on the remote variant: `GET /healthz`, `GET /readyz`, + `GET /status`, `WS /ws`. (Already match what + `Dreamverse/server/routes/health.py` consumes.) + +**These three health routes still need to migrate into FastVideo's +`build_app` to make `BE_FLAVOR=fastvideo` FE-compatible** — see +[streaming-server.md](streaming-server.md) "build_app route contract" + +[open-threads.md](open-threads.md) follow-up #1. + +When PR 7.6 lands the upstream of `fastvideo/entrypoints/realtime/`, +Dreamverse should not need any code change unless the import path +renames. Decided: keep `streaming/` (post-PR-5.5 public name); ship +`realtime/__init__.py` as a re-export with `DeprecationWarning` for one +release cycle. + +### Note on `default_ltx2_image_crf` + +Dreamverse's `RealtimeRuntimeConfig` includes `default_ltx2_image_crf`. +The April 26 Dreamverse review (D-8) showed this getting passed to +`SamplingParam(...)` and **silently dropped** by the public schema. Post +`d80c2a8` (May 2 typed-config refactor), the migration target is +`request.stage_overrides.refine.image_crf` (per +[design.md](design.md) compatibility mapping table). + +**Whether `d80c2a8` actually wired this through, or it's still latent, +is unverified.** See [open-threads.md](open-threads.md) item D-8. + +## Surface 3: Continuation state (PR 7) + +`Dreamverse/server/video_generation.py:89 ContinuationState` is +Dreamverse's hand-rolled per-session state holder. PR 7 introduced the +typed equivalent at +[`fastvideo/pipelines/basic/ltx2/continuation.py`](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/continuation.py). + +### Field mapping + +| Dreamverse | PR 7 `LTX2ContinuationState` | Notes | +|---|---|---| +| `video_images: list[PIL.Image]` | `video_frames: list[np.ndarray]` (uint8 H×W×3) | numpy is leaner; Dreamverse already round-trips PIL→numpy→PIL just to add noise | +| `audio_latents: torch.Tensor` `[B, C, T, mel]` | `audio_latents: torch.Tensor` (safetensors-serialized; bf16-safe) | unchanged shape; safetensors preserves bf16 | +| `LTX2_VIDEO_CONDITIONING_FRAME_IDX` (env) | `video_conditioning_frame_idx: int` | env constant → per-state field | +| `LTX2_VIDEO_CONDITIONING_STRENGTH` (env) | `video_conditioning_strength: float` | env constant → per-state field | +| `AUDIO_CONDITIONING_NUM_FRAMES` (env) | `audio_conditioning_num_frames: int` | env constant → per-state field | +| `AUDIO_CONDITIONING_STRENGTH` (env) | `audio_conditioning_strength: float` | env constant → per-state field | +| `audio_lps` (passed into `apply_audio`) | `audio_sample_rate: int \| None` | analogous; rename worth confirming with audio team | +| Computed `prefix_sec` per segment | `video_position_offset_sec: float` | **see open question below** | +| `segment_idx` (param to `apply_*`) | `segment_index: int` | per-state field | +| `VIDEO_CONTEXT_NOISE`, `AUDIO_CONTEXT_NOISE`, `ENABLE_AUDIO_COND` | not on state | runtime policy / regularization knobs, not portable session data | +| `apply_video / apply_audio / save_video / save_audio_latents / clear` | not on PR-7 state class | state is a pure data carrier; runtime owns lifecycle policy | + +PR 7 is a strict superset of Dreamverse's data model **plus** lifts +several env globals into per-session typed fields. + +### Lifecycle mapping + +| Dreamverse pattern | `SessionStore` API | +|---|---| +| `self.continuation = ContinuationState()` per session | `state = session_store.snapshot(sid) or LTX2ContinuationState()` | +| `apply_video(req_kwargs, segment_idx)` + `apply_audio(req_kwargs, segment_idx, audio_lps)` | `state = session_store.snapshot(sid)`; runtime builds request from `state.video_frames` / `state.audio_latents` | +| `save_video(frames)` + `save_audio_latents(latents)` | runtime constructs new `LTX2ContinuationState`, `session_store.store(sid, ...)` | +| `clear()` at end of session | `session_store.drop(sid)` | + +`SessionStore` and `BlobStore` ABCs ship with thread-safe in-memory +defaults (`InMemorySessionStore`, `InMemoryBlobStore`). Dreamverse can +adopt them as-is for the local runtime; remote runtimes can plug in +redis-backed implementations later. + +### Wire format (HTTP/WS round-trip) + +Dreamverse's `FastVideoRealtimePool` already speaks the realtime +runtime's HTTP+WS protocol. When PR 7.5/7.6 land state emission on the +server side, the on-the-wire payload is the public envelope: + +```json +{ + "kind": "ltx2.v1", + "payload": { + "schema_version": 1, + "segment_index": 3, + "video_conditioning_frame_idx": 9, + "video_conditioning_strength": 0.75, + "audio_sample_rate": 24000, + "audio_conditioning_num_frames": 5, + "audio_conditioning_strength": 0.5, + "video_position_offset_sec": 0.2, + "video": {"frames_b64": ["..."]}, + "audio": {"safetensors_b64": "..."}, + "metadata": {} + } +} +``` + +JSON-serializable end-to-end; safetensors blob preserves audio dtype +(incl. bf16). For payloads above the inline threshold a `BlobStore` +indirection replaces the b64-encoded body with `{"blob_id": "..."}`; +the blob itself stays inside the runtime that produced it. + +## Migration plan per PR + +| PR | Dreamverse action | +|---|---| +| PR 6 (landed) | Typed `GeneratorConfig` available; flat-kwarg path still works via compat. Optional migration. | +| PR 7 (landed) | Typed `LTX2ContinuationState` available. ~50-line Dreamverse PR: replace `server/video_generation.py:89` import; move `apply_*`/`save_*`/`clear` off the state class onto `VideoGenerationWorker`; read knobs from typed state instead of env globals; swap `list[PIL.Image]` → `list[np.ndarray]`. | +| PR 7.5 (open) | Streaming server skeleton — Dreamverse's `runtime/factory.py` either keeps building `GPUPool` from `RealtimeRuntimeConfig` (current path), or migrates to `ServeConfig.streaming` shape and invokes `fastvideo serve --config realtime.yaml`. Dreamverse's `RuntimePool`/`RuntimeSlot` Protocol can stay in place. | +| PR 7.6 (branch ready) | GPU pool upstream — `local_runtime.py` import becomes a public import with same symbols (`RealtimeRuntimeConfig`, `GPUPool`, `get_available_gpus`). Per-GPU continuation state inside the worker becomes a `SessionStore` reference (Dreamverse doesn't see this). `request.state` / `result.state` round-trip starts working end-to-end on the local runtime. | +| PR 7.10 (planned) | `generate_async` is canonical. Dreamverse's per-segment `user_step` flow can migrate from sync `generate_video(..., **kwargs)` to consuming the typed event stream. Optional; sync wrapper stays. | + +## Dynamo backend contract + +**FastVideo does not host any Dynamo code.** The backend package +(`args.py`, `main.py`, `backend.py`, `register.py`, `health_check.py`, +adapter, Dockerfile) lives entirely in the Dynamo repo at +`components/src/dynamo/fastvideo/`, modeled on +`components/src/dynamo/sglang/`. + +FastVideo's only obligation is to expose a stable, typed Python API +that Dynamo's backend package imports. + +### Contract surface + +| Surface | Exposed as | +|---|---| +| Construction | `VideoGenerator.from_pretrained(model_path, **typed_kwargs)` (typed_kwargs = a stable subset from `GeneratorConfig`; no flat LTX2 legacy) | +| Sync execution | `generator.generate_video(request: GenerationRequest) -> VideoResult` | +| Async execution | `generator.generate_async(request: GenerationRequest) -> AsyncGenerator[VideoEvent, None]` (PR 7.10) | +| Typed request | `fastvideo.api.GenerationRequest`, `SamplingConfig`, `InputConfig` | +| Typed result | `VideoResult` with `video_bytes` or tensor frames + optional `ContinuationState` | +| Continuation | `ContinuationState(kind, payload)` — schema-versioned payloads | +| Health-check input | `VideoGenerator.default_health_check_request() -> GenerationRequest` (256x256 / 8 frames / 1 step) | +| Config dump | `GeneratorConfig.to_dict()` / `ServeConfig.to_dict()` | + +### Request/response mapping (Dynamo ↔ FastVideo) + +``` +NvCreateVideoRequest -> fastvideo.api.GenerationRequest + prompt -> sampling.prompt + size="WxH" -> sampling.width, sampling.height + seconds -> (seconds * nvext.fps) -> sampling.num_frames + input_reference -> input.image_path / input.video_path + nvext.fps -> sampling.fps + nvext.num_frames -> sampling.num_frames (overrides seconds*fps) + nvext.num_inference_steps -> sampling.num_inference_steps + nvext.guidance_scale -> sampling.guidance_scale + nvext.seed -> sampling.seed + nvext.negative_prompt -> sampling.negative_prompt + response_format -> (handled by adapter at output) + +VideoFinalEvent -> NvVideosResponse + video_bytes -> data[0].b64_json (if response_format=b64_json) + video_url (after upload) -> data[0].url (if response_format=url) + metadata.inference_time_s -> inference_time_s +``` + +All fields exist on FastVideo's typed schema after PR 6 expansion (typed +LTX2 kwargs) + PR 7.10 (`generate_async` + health check). + +### Reference: PR ai-dynamo/dynamo#7544 + +Closed draft establishing the Dynamo backend shape. Two frictions +identified: + +1. Flat legacy LTX2 kwargs — solved by PR 6. +2. Sync-only generation — solved by PR 7.10's `generate_async`. + +Next iteration of this PR (or its successor) will reopen against PR 8's +docs reference and land cleanly. + +## Open questions across surfaces + +| # | Question | Source | Status | +|---|---|---|---| +| Q-1 | Multi-model GPU pool | dreamverse_review D-1 | Deferred (production single-model) | +| Q-2 | LTX-2 prompt orchestration promotion to public | dreamverse_review D-2 | Open; consumer-side until 2nd consumer | +| Q-3 | Race-based provider fallback | dreamverse_review D-3 | Open; sequential is current public | +| Q-4 | Router upstream skip on Dreamverse | dreamverse_review D-4 | Resolved (PR 7.9 lands publicly, Dreamverse doesn't consume) | +| Q-5 / D-5 | `generate_async` cutover (audio re-encode) | dreamverse_review | **Blocked on PR 7.10** | +| D-6 | Don't upstream `realtime/local_runtime.py` | dreamverse_review | Resolved (Dreamverse switches to `streaming.gpu_pool.SubprocessGpuPool`) | +| D-7 / Q-6 | FP4Config public colocation | dreamverse_review | **Resolved May 2** — public NVFP4 landed with lazy flashinfer | +| D-8 | `ltx2_image_crf` silently dropped | dreamverse_review | **Unverified post-`d80c2a8`** — see [open-threads.md](open-threads.md) | +| D-9 | `aarch64-conda-linux-gnu-cc` triton compile failure | dreamverse_review | Operational; `ENABLE_TORCH_COMPILE=0` workaround | +| D-10 | Warmup OOM on shared GPU | dreamverse_review | Operational; idle-GPU pre-warm probe | +| D-11 | ffmpeg `Broken pipe` on disconnect | dreamverse_review | Cosmetic logging cleanup | +| — | `video_position_offset_sec` semantics (persistent vs per-segment) | dreamverse_integration | **Open — needs decision before PR 7.6 emits state** | +| — | `SessionStore` / `BlobStore` lifecycle (TTL/eviction/blob-drop) | dreamverse_integration | Open — defer to PR 7.5 design pass | + +See [decisions-log.md](decisions-log.md) for full rationale per +decision. + +## Don't / Cautions + +- **Don't pop the Dreamverse stash on this branch.** It's 3867 lines of + orphan modular refactor with broken absolute imports. +- **Don't change `RealtimeRuntimeConfig` shape without coordinating + with Dreamverse `runtime/factory.py`.** +- **Don't promise public compatibility for private Dreamverse-only + field aliases.** Those belong in the private adapter layer per design + spec. diff --git a/.agents/memory/dreamverse-integration/decisions-log.md b/.agents/memory/dreamverse-integration/decisions-log.md new file mode 100644 index 0000000000..62b627bed3 --- /dev/null +++ b/.agents/memory/dreamverse-integration/decisions-log.md @@ -0,0 +1,978 @@ +# Decisions Log — D + Q Resolutions + +Cross-doc consolidated decision log. Each entry: ID, source doc, +question/decision, rationale, current status. + +For implementation status see [pr-roadmap.md](pr-roadmap.md). For +follow-up actions see [open-threads.md](open-threads.md). + +**Last updated:** 2026-05-06 (added D-21 — chunk-stutter root cause is software libx264 encoding consuming ~22% of segment wall-time, NOT a migration regression; verified by 3 parallel explore agents that NVFP4 + torch.compile coverage matches FastVideo-internal exactly; landed opt-in NVENC build path in install_native_ffmpeg.sh + `--nvenc`/`--no-nvenc` flag in dreamverse-deploy.sh + `apps/dreamverse/server/benchmarks/benchmark_av_streaming.py` regression test + memory dir update; default codec stays `libx264` for backward compat, opt-in via `--nvenc`. Earlier: added D-12 — GpuPool layer separation, Oracle review post-#1257-merge; added D-13 — prompt enhancer / LLMProvider abstraction shape, Oracle review pre-#1258-merge; added D-14 — streaming auxiliaries cohesion, Oracle review during #1284 review cycle; added D-15 — streaming router placement + sticky/active-active deferral, Oracle review during #1286 review cycle; added D-16 — streaming router polish round 2, second-pass review on top of D-15 covering bridge cancellation hygiene, registry state machine, httpx hard-fail, replica YAML parsing, and `websockets` dep; added D-17 — strategy reversal: abandon 6-PR split in favor of single mega-PR #1288 on `will/ltx2_sr_port`; added D-18 — Option B+ chosen: Dreamverse FE+product-server move into FastVideo as `apps/dreamverse/` subfolder while generic backend stays at `fastvideo.entrypoints.streaming.*`; integration-review.md deprecated, integration-plan.md is the executable migration plan; added D-19 — D-18 executed: 5 commits land on `will/dreamverse-monorepo`, fix-up commits corrected the integration-plan's invalid "delete generic-merged, import public substitutes" assumption — generic-merged files carried product-local instead, e2e passes against migrated code with /proc-verified evidence; added D-20 — segment-2 BrokenPipe root cause was a TWO-direction silent drop of LTX-2 audio kwargs in public `VideoGenerator`). + +## Status legend + +- ✅ **Resolved** — decision made and implementation complete (or no implementation needed) +- 🟡 **Deferred** — decision made, implementation deferred to a known PR +- 🔴 **Open** — needs decision + +## Post-merge architecture decisions + +### D-26: Rebase `will/dreamverse-monorepo` directly onto `origin/main` (PR base flip) + +**Status:** ✅ Resolved 2026-05-06 (UTC; 2026-05-07 local). 66 commits cleanly replayed via `git rebase origin/main`; force-pushed via `--force-with-lease`. Local backup branch `will/dreamverse-monorepo-pre-main-rebase-backup-20260506` preserved at the pre-rebase tip `2ee839a3`. PR #1288 on `will/ltx2_sr_port` is untouched. +**Source:** User directive: "update this branch will/dreamverse-monorepo to be directly against origin/main for PR purposes instead of ltx_sr_port (don't open new PRs)". + +**Question:** `will/dreamverse-monorepo` was forked from `will/ltx2_sr_port` (PR #1288's head). Should it stay stacked on top of `will/ltx2_sr_port`, or be rebased so its PR base becomes `origin/main` directly? + +**Decision:** Rebase `will/dreamverse-monorepo` onto `origin/main` directly. This makes the branch openable as a single PR against main containing the entire 66-commit chain (40 from the legacy `will/ltx2_sr_port` work + 26 dreamverse-monorepo-specific commits including D-19/D-20/D-21/D-22). + +**Pre-rebase state:** + +``` +origin/main (c17d33bf) ← 1 new commit since 2aaeee2a (PR #1253 SSIM cosine) + │ + └─ 2aaeee2a (PR #1286 squash merge; old shared base) + ├─ 40 commits → will/ltx2_sr_port @ fbd823df (PR #1288) + └─ 40 + 26 = 66 commits → will/dreamverse-monorepo @ 2ee839a3 +``` + +**Post-rebase state:** + +``` +origin/main (c17d33bf) + │ + └─ 66 commits → will/dreamverse-monorepo @ 83829c5e (NEW SHAs, same content) + +origin/main (c17d33bf) -- still in main lineage + │ + └─ 2aaeee2a + └─ 40 commits → will/ltx2_sr_port @ fbd823df (PR #1288, UNCHANGED) +``` + +**Operation:** + +1. **Backup**: `git branch will/dreamverse-monorepo-pre-main-rebase-backup-20260506 will/dreamverse-monorepo` (local-only safety net pinning `2ee839a3`). +2. **Rebase**: `git rebase origin/main` while on `will/dreamverse-monorepo`. All 66 commits replayed conflict-free in ~30s. The single new origin/main commit `c17d33bf` (#1253 SSIM cosine regression) touches only `fastvideo/tests/ssim/*`, `fastvideo/tests/modal/ssim_test.py`, `.agents/skills/seed-ssim-references/SKILL.md`, `fastvideo/pipelines/basic/stable_audio/stages/decoding.py`, and a 56-line block in `fastvideo/entrypoints/video_generator.py`. None of our 66 commits touch the SSIM files; the `video_generator.py` overlap auto-merged because our D-20 changes (`_BATCH_EXTRA_PASSTHROUGH_KEYS`, result-dict surface) and #1253's changes are in different parts of the file. +3. **Verification (file-level, before push)**: + - Commit count: 66 (PASS) + - Co-author trailer count: 231 across 66 commits — within historical norm (some legacy `will/ltx2_sr_port` commits had partial trailers per [`authors.md`](authors.md) "Known gaps"). + - Tree-diff vs backup: only the 845-line forward delta from `c17d33bf` (expected). All D-20/D-21/D-22-introduced content (`_BATCH_EXTRA_PASSTHROUGH_KEYS` x2, "unknown field" x1, `av_chunk_interval_ms` x4, `av_chunk_publish_ms` x2, `enable-nvenc` x2, `NVENC_OVERRIDE` x4) survives intact. + - `pre-commit run --files` on the 7 most-edited files: PASS (yapf/ruff/codespell/mypy/spaces). + - Runtime pytest hung mid-import on this shared dev box (pre-existing CUDA/torch init issue affecting other commands too) — NOT a rebase regression. The same `fastvideo/tests/api/` suite passed 185/185 pre-rebase. +4. **Force-push**: `git push --force-with-lease=will/dreamverse-monorepo:2ee839a3... origin will/dreamverse-monorepo`. Updated `2ee839a3...83829c5e (forced update)`. + +**Implications:** + +- The branch can now be opened as a PR against `origin/main` containing all the LTX-2 SR port + NVFP4 + Dreamverse monorepo migration + audio kwarg fix + warmup + NVENC build + benchmarks + integration memory dir, in a single review unit. +- PR #1288 on `will/ltx2_sr_port` is untouched and continues to track its own subset of the work. If PR #1288 lands first, the duplicated commits on `will/dreamverse-monorepo` will be reconciled at the next rebase by `git rebase origin/main` dropping commits whose content is now in main (same mechanism as the post-#1286 rebase recorded in [state.md](state.md) "Post-#1286 rebase summary"). +- Local backup `will/dreamverse-monorepo-pre-main-rebase-backup-20260506 @ 2ee839a3` keeps the old chain available; recommend deleting after the new branch state is verified by running on a non-stuck dev box (or after the PR merges). + +**Watch-outs:** + +- Anyone with a checkout of the OLD `will/dreamverse-monorepo` (pre-rebase) needs to `git fetch origin will/dreamverse-monorepo --force` and discard local commits, OR rebase their local commits onto the new `83829c5e`. None observed in the runbook's worktree-sharing model. +- The trailer-count 231 (vs expected 264 for full coverage) is NOT introduced by this rebase — it's the historical gap from [`authors.md`](authors.md). Verifiable by counting trailers on the backup branch (same 231). + +### D-21: AV chunk stutter root cause — software libx264 encoding consumes ~22% of segment wall time; opt-in NVENC fix + +**Status:** 🟡 Deferred — fix landed (NVENC build + `--nvenc` flag), default unchanged so no behavior regression for operators who haven't rebuilt ffmpeg yet. Switch default to `h264_nvenc` once benchmark numbers are captured + a release notes entry is published. +**Source:** Live debug session 2026-05-06 prompted by user observation: "stuttering still between chunks" after D-20 + warmup r3 fix. 3 explore agents fanned out (NVFP4 config, torch.compile config, AV chunk pacing). + +**Question:** With D-20 (audio kwarg routing fix) + r3 warmup pass landed and warmup_success=true, why is the live deploy still stuttering between chunks? Is the migration missing some quantization or compile coverage that the FastVideo-internal reference has? + +**Investigation (3 parallel explore agents):** + +1. **NVFP4 config diff** (`bg_0629273d`): No divergence. apps/dreamverse, original Dreamverse, and FastVideo-internal ALL use `layer_profile="refine"` with the same 48-block `fp4_layers` superset, e2m1 mantissa, fp32 alpha, layout_128x4 scale, group size 16. Stage gating (`base` vs `refine`) and `transformer_refine_quant` carrier match. The only naming difference is the public surface rename `FP4Config` → `NVFP4Config`. +2. **torch.compile config diff** (`bg_97081cc5`): No divergence. ALL THREE repos use `inductor / fullgraph=True / max-autotune-no-cudagraphs / dynamic=False` and compile only the transformer + text_encoder. **VAE / audio_vae / vocoder are eager bf16 in all three** — so the migrated repo is not missing a compile pass that the original had. Only behavioral difference: FastVideo-internal calls `target.eval()` on its audio encoder; the migrated worker does not (separate D-22 follow-up). +3. **AV chunk pacing** (`bg_574e831e`): `stream_fmp4` has only one timer (`av_encode_stream_ms`) — no per-chunk instrumentation. Between `worker.generate_step()` returning and `stream_fmp4()` returning there is no significant work other than ffmpeg's own encode + chunk emission. The `main_user_step − worker_e2e ≈ 1300ms` gap is therefore mostly ffmpeg + controller relay loop, NOT IPC. Per-chunk emission cadence is driven by stdout read size (1 MiB), not fragment boundary, so non-uniform pacing is plausible. + +**Root cause synthesis:** + +| Phase | Wall-time | Compute | Compiled? | NVFP4? | +|---|---|---|---|---| +| transformer denoise (gen) | ~4500 ms | GPU | YES | YES | +| save_conditioning | ~100 ms | GPU/CPU | n/a | n/a | +| **stream_fmp4 (libx264 software encode)** | **~1300 ms** | **CPU** | **NO** | **NO** | +| TOTAL wall | ~6000 ms | producing 4.67 s playable | | | + +Realtime ratio = 4.67 s playable / 6.0 s wall = **0.78x**. FE buffer drains 1.3 s per segment until empty → inter-segment stutter. **The cause is not a migration regression** (FastVideo-internal exhibits the same architectural limit); it is the choice to use `libx264 ultrafast` software encoding on the segment-streaming hot path on machines that have idle hardware encoders. + +**Build-time finding:** `apps/dreamverse/scripts/install_native_ffmpeg.sh` was building ffmpeg with only `--enable-libx264 --enable-lto`. No `--enable-nvenc`, no nv-codec-headers prereq. So even setting `FASTVIDEO_VIDEO_CODEC=h264_nvenc` would have failed at runtime with "encoder not found". + +**Resolution (this round, default-preserving):** + +1. **`apps/dreamverse/scripts/install_native_ffmpeg.sh`** now: + - Clones `nv-codec-headers` (NVENC/NVDEC API headers; no CUDA libs) into `$INSTALL_PREFIX` so `ffnvcodec.pc` is on `pkg-config`'s search path. + - Configures ffmpeg with `--enable-cuda --enable-nvenc --enable-cuvid --enable-nvdec` plus `--extra-cflags=-I$CUDA_PREFIX/include` and `--extra-ldflags=-L$CUDA_PREFIX/lib64`. + - Drops `--enable-cuda-nvcc` and `--enable-libnpp` so the build does NOT require `--enable-nonfree` (we only need hardware encode/decode, not GPU-side filters). + - New env knobs: `ENABLE_NVENC=0|1` (default 1), `CUDA_PREFIX` (default `/usr/local/cuda`), `NV_CODEC_REF`. + - Sanity check verifies the resulting binary exposes `h264_nvenc` / `hevc_nvenc` encoders before exiting 0. + - **Emits `FASTVIDEO_VIDEO_CODEC=libx264` in the env file by default** so existing deploys are runtime-unchanged. + +2. **`.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh`** now: + - Accepts `--nvenc` / `--no-nvenc` flag (defaults to off, matches existing behavior). When `--nvenc`, exports `FASTVIDEO_VIDEO_CODEC=h264_nvenc` into the backend setsid block. + - Validates the binary actually has `h264_nvenc` encoder via `ffmpeg -encoders | grep h264_nvenc`. Fails fast if `--nvenc` is requested against a libx264-only ffmpeg with a clear hint to rerun the install script. + - `DREAMVERSE_NVENC` env var as the env-var counterpart (flag overrides). + - Banner now prints `nvenc=true|false` alongside `warmup` and `torch_compile`. + +3. **`apps/dreamverse/server/benchmarks/benchmark_av_streaming.py`** is the regression test: + - Drives `stream_fmp4` directly with synthetic 121-frame 1920x1088 video + 5-second 24kHz stereo audio (production shape). + - Sweeps `libx264` and `h264_nvenc` (auto-skips encoders not present in the active ffmpeg). + - Reports per-codec: wall_ms_min/median/p95/max, bytes_median, chunks_median, and **realtime_ratio_median** (playable / wall, must be ≥ 1.0 to avoid buffer drain). + - Exit code 1 if any codec produces realtime_ratio < 1.0; useful as a CI gate. + +**Empirical findings (this dev host, B200):** + +- `libx264 ultrafast` benchmark on production-shape input (121 frames, 1920x1088, 5s 24kHz stereo audio): wall_median=611ms, wall_p95=644ms, 8.25x realtime ratio in isolation. Captured via `apps/dreamverse/server/benchmarks/benchmark_av_streaming.py --runs 5 --codecs libx264`. +- **B200 has NO NVENC silicon.** Direct ffmpeg probe (`-c:v h264_nvenc` against a 64x64 0.2s color frame) fails with `OpenEncodeSessionEx failed: unsupported device (2): No capable devices found`. This is a hardware omission — datacenter Blackwell (B200) and some H100 SKUs prioritize compute density and ship without NVENC. Only consumer Blackwell (RTX 50-series) and select datacenter SKUs (T4, A10, A100 PCIe) have NVENC. +- The deploy script's `--nvenc` path now does TWO checks: (a) `h264_nvenc` is in the encoder list (build-time); (b) a 64x64 ffmpeg probe actually succeeds (runtime-time). On a B200, the runtime probe fails fast with a clear "no NVENC silicon on this host" error pointing at SKU-level alternatives. +- **Stutter on B200 is NOT primarily ffmpeg encoding.** The benchmark shows libx264 ultrafast at 611ms, but production logs show a 1300ms gap between `worker_e2e` and `main_user_step`. The other ~700ms is IPC + controller WebSocket relay (not measured per-chunk in current `stream_fmp4`). + +**Open / deferred:** + +- ~~D-22~~ ✅ **Resolved 2026-05-06** in `bade2c0a` — `stream_fmp4` is now fully instrumented with per-phase + per-chunk timings; gpu_pool prints a per-segment summary line. The controller-side WS-send slice is tracked separately as D-22-CTL. +- D-22-CTL: per-chunk timing in the controller's AV relay loop in `session/controller.py` (between media event arrival and `ws_send_bytes`). Worker side is captured by D-22; the controller side is the still-unmeasured remainder of the 700ms IPC+relay gap. +- D-23: B200 + RTX 5090 split — for B200-class deploys without NVENC, the stutter fix needs a different approach (pipeline gen N+1 with encode N, or larger initial FE buffer pre-fill). For RTX 5090 / T4 / A10 deploys, `--nvenc` is the answer once tested. Make the deploy default conditional: probe NVENC at boot, default `--nvenc` if available. +- D-24: re-evaluate flipping the deploy default from `libx264` to `h264_nvenc` after a real-NVENC host (RTX 5090 or H100 PCIe) benchmark is run. Tradeoff: NVENC has ~5-10% lower compression at same quality but is hardware-accelerated. For real-time streaming the latency win dominates IF the host has NVENC. +- D-25: pipeline benchmark via Python SDK (`apps/dreamverse/server/benchmarks/benchmark_pipeline.py`, landed in `f98811e0`) — captures per-stage timings via `FASTVIDEO_STAGE_LOGGING=1`. Cold-run baseline on B200 NVFP4 (no compile, no warmup): 6.99s for 5.04s playable = 0.72x realtime. Per-stage profile dominated by LTX2RefineLoRAStage (40% on cold, includes one-time LoRA conversion + adapter load), LTX2DenoisingStage (20% — base DiT 5-step denoise), LTX2TextEncodingStage (11%), DecodingStage (4%), audio_decoding/upsample/init each <1%. Future work: rerun under `compile_warm` scenario for steady-state numbers. +- The `target.eval()` call on the audio encoder that FastVideo-internal does and the migrated Dreamverse does not — surface as a separate decision once observed empirically (probably a no-op in inference path but worth the symmetry). + +**Cross-references:** + +- [D-20](decisions-log.md#d-20) (audio kwarg routing fix) made segment 2 generate cleanly. D-21 makes the segment-to-segment chain stutter-free in real-time. +- [`apps/dreamverse/server/av_streaming.py::stream_fmp4`](file:///home/william5lin/FastVideo/apps/dreamverse/server/av_streaming.py) is the hot path; the cmd builder there respects `FASTVIDEO_VIDEO_CODEC` and branches on `*_nvenc` codecs to use NVENC presets (`p1`/`p2`/...) and `-rc constqp -qp 28` instead of libx264 presets (`ultrafast`/...). +- The benchmark cross-references D-21 in its module docstring so a future contributor reading the script alone has the context. + +### D-20: Segment-2 BrokenPipe root cause — two-direction silent drop of LTX-2 audio kwargs in public `VideoGenerator` + +**Status:** ✅ Resolved 2026-05-05. 4 commits on `will/dreamverse-monorepo` (`1b686f4e`..`5eaf0a13`); pushed to origin. End-to-end verified on GPU4 (`/proc/$BE_PID/environ` + `Cached audio latents shape=(1, 8, 126, 16) for segment 2` log line + `Segment 2: relayed av chunks=22, bytes=3.8MB`). +**Source:** Live debugging session triggered by recurring `RuntimeError: ffmpeg frame writer failed: [Errno 32] Broken pipe` on segment 2 in `/tmp/opencode/dreamverse-deploy/backend-gpu4.log`. + +**Question:** Why does segment 2 of every Dreamverse session crash with a writer-side EPIPE, while segment 1 streams fine? + +**Symptom chain decoded:** + +1. ffmpeg writer thread in `apps/dreamverse/server/av_streaming.py:307-317` raises `BrokenPipeError` mid-frame. +2. ffmpeg's exit code is `0` — the `if rc != 0` branch of `stream_fmp4` never fires; only `if writer_error[0] is not None` does. +3. `rc=0 + BrokenPipeError` means ffmpeg exited cleanly *before* the writer finished pushing all frames → ffmpeg closed stdin early due to `-shortest` + audio shorter than video. +4. Manual repro confirmed: with audio 71240 samples (~2.97s) and video 112 frames (~4.67s), ffmpeg `-shortest` + 1MB pipe + 1920x1088x3 frames produces exactly this signature (`rc=0 out_bytes=751028 writer_error=BrokenPipeError(32)`). +5. The 1.7s audio undershoot is suspicious because Dreamverse's `apply_audio()` in `apps/dreamverse/server/video_generation.py:132-186` explicitly extends `audio_num_frames = NUM_FRAMES + audio_extra` (=`121 + 40 = 161`) for continuation segments. Audio should be 6.71s, not 5.01s. The kwarg was being silently dropped. + +**Root cause (TWO directions):** + +| Direction | Where | What was missing | What it broke | +|---|---|---|---| +| **Inbound** (kwargs → `batch.extra`) | `fastvideo/entrypoints/video_generator.py::_generate_video_impl` | The 5-key extraction block (`ltx2_audio_latents`, `ltx2_audio_clean_latent`, `ltx2_audio_denoise_mask`, `audio_num_frames`, `video_position_offset_sec`) that FastVideo-internal has at lines 168-183. Without it, `apply_audio`'s kwargs landed in `sampling_param.update(kwargs)` which `logger.error`'d "%s has no field %s" and dropped them. | `audio_num_frames` never reached `batch.extra` → `ltx2_denoising.py:325` fell back to `batch.num_frames=121` → audio generated for 5.01s instead of 6.71s. After `head_trim_audio_frames=49` removed the leading 2.04s, only 2.97s of audio remained for 4.67s of video. | +| **Outbound** (`batch.extra` → result dict) | `fastvideo/entrypoints/video_generator.py::_generate_single_video` | `"ltx2_audio_latents": output_batch.extra.get("ltx2_audio_latents")` in the result dict. Internal exposes it at line 556; public didn't expose it at all. | `Dreamverse._derive_next_audio_latents()` always saw `None` → `self.continuation.audio_latents` was never set → segment 2's `apply_audio` short-circuited (`if not (… and self.audio_latents is not None): return`) → no audio continuation, no `audio_num_frames` extension, no `ltx2_audio_clean_latent` carry-over. | + +The two directions hid each other: even after the inbound block was ported, segment 2 still broke until the outbound surface was added. Both must be present for audio continuation to round-trip. + +**Resolution — 4 commits on `will/dreamverse-monorepo`:** + +| SHA | Subject | +|---|---| +| `1b686f4e` | `[fix] dreamverse: pin ffmpeg native build toolchain by uname -m` | +| `265ce1a6` | `[fix] api: route LTX-2 audio kwargs through batch.extra; strict update` | +| `dab9499c` | `[feat] dreamverse-deploy: native ffmpeg + compile-off defaults` | +| `5eaf0a13` | `[feat] dreamverse-deploy: --warmup / --torch-compile CLI flags` | + +`265ce1a6` is the substantive public-API fix: ports `_BATCH_EXTRA_PASSTHROUGH_KEYS` extraction in `_generate_video_impl`, ports `_extra_overrides` consumption in `_generate_single_video` (writes into `batch.extra`), surfaces `ltx2_audio_latents` in the result dict, and converts `SamplingParam.update()` from `logger.error`-and-drop to `raise ValueError` on unknown keys so the next contributor who adds an unrecognized kwarg hits a loud failure pointing at `_BATCH_EXTRA_PASSTHROUGH_KEYS` instead of debugging a broken-pipe-shaped symptom hours later. Adds `fastvideo/tests/api/test_extra_overrides_routing.py` (7 tests pinning the contract). + +**Why the strict-update is non-negotiable:** the `logger.error`-and-continue pattern is the exact mechanism that hid this bug for the entire Dreamverse-monorepo migration window. It silently traded loud-failure-now for silent-corruption-later. Strict raise + a clear "route via `_BATCH_EXTRA_PASSTHROUGH_KEYS`" hint converts the next regression of this shape from "broken pipe in production" to "ValueError at first call". + +**Cross-references:** + +- [D-11](decisions-log.md#d-11) (Apr 26) noted "ffmpeg fragment write Broken pipe" but framed it as cosmetic (client-disconnect race). Today's was a different code path: server-side EPIPE caused by a server-internal A/V duration mismatch. Both are now resolved; D-11's fix domain (swallow on intentional disconnect) remains unchanged but lower priority. + +- The `[fix] api: route LTX-2 audio kwargs ...` commit (`265ce1a6`) is on `will/dreamverse-monorepo` only. Cherry-picking onto `will/ltx2_sr_port` so it lands as part of PR #1288's mega-PR is a deferred follow-up — see open-threads.md "Cherry-pick API audio routing fix to PR #1288". + +**Side effects of the fix:** + +- `[feat] dreamverse-deploy: native ffmpeg + compile-off defaults` (`dab9499c`) wires the native LTO+libx264+native-arch ffmpeg the team playbook mandates into every deploy via `FASTVIDEO_FFMPEG_BIN=$HOME/opt/ffmpeg-native/bin/ffmpeg` and disables `torch.compile` by default (`ENABLE_TORCH_COMPILE=0`) so segment-1 cold start drops from ~3-4min (max-autotune) to ~45s (pure inference) — required for any iterative debugging cycle to fit inside the 300s session timeout. +- `[fix] dreamverse: pin ffmpeg native build toolchain by uname -m` (`1b686f4e`) makes `apps/dreamverse/scripts/install_native_ffmpeg.sh` immune to conda envs that activate both `gcc_linux-64` and `gcc_linux-aarch64` (the aarch64 activation script sorts later and wins, so the inherited `CC=aarch64-conda-linux-gnu-cc` defeated the script's `: "${CC:=...}"` deferred default and tripped x264's compiler probe with "unknown value 'native' for '-march'"). +- `[feat] dreamverse-deploy: --warmup / --torch-compile CLI flags` (`5eaf0a13`) adds `--warmup`/`--no-warmup` and `--torch-compile`/`--no-torch-compile` flags that override the env-var defaults and accept any position relative to the positional GPU/port args (verified across 13 parser permutations). + +**Watch-outs for downstream contributors:** + +- Adding a new pipeline-specific kwarg now requires either making it a `SamplingParam` field OR adding it to `_BATCH_EXTRA_PASSTHROUGH_KEYS` in `fastvideo/entrypoints/video_generator.py`. Strict `update()` will raise `ValueError` on unknown kwargs that aren't routed through one of those paths. +- The `[fix] api:` commit (`265ce1a6`) is BACKWARD-INCOMPATIBLE for any caller that was relying on `SamplingParam.update()` to silently swallow unknown keys. If pre-existing CI breaks elsewhere on this surface, the fix is to add the legitimate kwarg to `SamplingParam` or `_BATCH_EXTRA_PASSTHROUGH_KEYS` (not to revert the strict mode). + +### D-19: D-18 executed — Dreamverse migration on `will/dreamverse-monorepo`, generic-merged files carried product-local + +**Status:** ✅ Resolved 2026-05-05. 5 commits on top of `will/ltx2_sr_port` HEAD `fbd823df`. Branch pushed to origin at `c1fe5d4c`. e2e definitively passes. +**Source:** Execution of [integration-plan.md](integration-plan.md) (D-18 plan), with one significant deviation surfaced by Oracle review. + +**Commits:** + +| SHA | Message | +|---|---| +| `08828d96` | `[feat] dreamverse-monorepo: Phase 1 — skeleton + tooling` | +| `f3a863ba` | `[feat] dreamverse-monorepo: Phase 2 — backend move + import rewires` | +| `876f7eb3` | `[feat] dreamverse-monorepo: Phase 3 — frontend + public assets` | +| `1d47ede6` | `[fix] dreamverse-monorepo: carry generic-merged files product-local` | +| `c1fe5d4c` | `[fix] dreamverse-monorepo: entrypoint + audio re-encode + verification` | + +Final stats: 164 files changed, +53294/-2 LOC, 31725 files under `apps/dreamverse/`. + +**Question:** [integration-plan.md](integration-plan.md) Phase 2 instructed "DELETE generic-merged files (`gpu_pool.py`, `av_streaming.py`, `worker_ipc.py`, `mock_server.py`, `session_init_image.py`, `session_logger.py`) from the Dreamverse copy and rewire imports to public `fastvideo.entrypoints.streaming.*` substitutes". The first execution attempt followed this instruction. Was that the right call? + +**Decision (forced by Oracle finding):** No. The "delete + import substitute" strategy assumed the public modules were API-compatible drop-ins for the Dreamverse-product modules. They are NOT. Public `fastvideo.entrypoints.streaming.GpuPool` is an abstract base class with `acquire/run/release/shutdown/health` semantics designed for a future Phase 4 streaming-runtime API. Dreamverse's product `GPUPool(gpu_ids).initialize()` has totally different shape (per-GPU subprocess workers with `slot.user_step / register_stream_queue / acquire(client_id, websocket) -> (gpu_id, slot)` semantics). Substituting one for the other made `apps/dreamverse/server/main.py:63` fail at boot with `TypeError: GpuPool() takes no arguments`. + +**Fix:** Carry all 7 generic-merged files (gpu_pool, av_streaming, worker_ipc, mock_server, session_init_image, session_logger, server_entry) into `apps/dreamverse/server/` as PRODUCT-LOCAL — same status as the rest of the Dreamverse server tree. Imports stay flat (`from gpu_pool import GPUPool`, etc.), matching Dreamverse's existing sys-path-injection convention. Public `fastvideo/entrypoints/streaming/*` reverts cleanly to its `fbd823df` state — `git diff fbd823df..c1fe5d4c -- fastvideo/entrypoints/streaming/` is empty. + +The "import public substitutes" promise becomes a future Phase 4 task: actually harmonize the APIs so Dreamverse can drop its product-local copies. Not in scope for this migration. + +**Why the e2e initially gave a false positive:** + +The first run of all 8 Playwright tests passed (5.1s) — Oracle caught that this was misleading. The `dreamverse-server` console script in `/home/william5lin/miniconda3/envs/fv-main/bin/dreamverse-server` was installed by a prior `pip install -e /home/william5lin/Dreamverse`, so `from server_entry import cli` resolved to `/home/william5lin/Dreamverse/server/...` (the canonical install), not `apps/dreamverse/server/...` (the migrated tree). The migrated code was never actually exercised. + +**Fix to entrypoint resolution** (in `c1fe5d4c`): wrapper scripts at `apps/dreamverse/scripts/dreamverse-server` (and `dreamverse-mock-server`) explicitly do: + +```bash +#!/usr/bin/env bash +REPO_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)" +cd "${REPO_ROOT}/apps/dreamverse/server" +exec "${REPO_ROOT}/.venv/bin/python" main.py "$@" +``` + +This guarantees the migrated tree is what runs. Verified end-to-end via `/proc/$PID/cwd = /home/william5lin/FastVideo/apps/dreamverse/server` during the second e2e run. All 8 Playwright tests pass against this confirmed-migrated backend. + +**Phase 0 environment prereqs (validated 2026-05-05):** + +- `flashinfer-python` in FastVideo `.venv` — required for NVFP4 path. Without it, model load fails with `ImportError: NVFP4 quantization requires flashinfer`. +- `cerebras-cloud-sdk` and `openai` in `.venv` — required by the migrated prompt enhancer. +- For B200 / sm_100a + gcc-15 conda toolchain: nvcc rejects host compiler. Workaround: + ```bash + CUDAHOSTCXX=/usr/bin/g++-13 + NVCC_PREPEND_FLAGS="-ccbin /usr/bin/gcc-13 -allow-unsupported-compiler" + ``` + Without these, flashinfer JIT compilation fails with `error: #error -- unsupported GNU version! gcc versions later than 14 are not supported!`. + +These are **operator-side prerequisites**, not migration code defects. Documented in `apps/dreamverse/README.md` and `docs/contributing/dreamverse-development.md`. + +**E2E evidence (live, post-fix-up):** + +``` +PID 179112 cwd: /home/william5lin/FastVideo/apps/dreamverse/server +/healthz → 200 {"status":"ok","service":"ltx2-streaming-backend",...} +/readyz → 200 {"status":"ready","ready_gpu_workers":1,"total_gpus":1,...} +GPU4 mem: 50.9 GiB (NVFP4 model loaded) + +Playwright (8/8 PASS in 5.1s): + ✓ backend-health/healthz returns ok via the next.js rewrite (32ms) + ✓ backend-health/readyz reports gpu pool state (11ms) + ✓ backend-health/status endpoint exposes gpu pool snapshot (12ms) + ✓ backend-health/prompt-system-config exposes operator-tunable prompts (15ms) + ✓ backend-health/curated presets endpoint serves a non-empty list (devtools only) (19ms) + ✓ frontend-shell/main page loads and exposes the FastVideo brand chip (1.4s) + ✓ frontend-shell/composer hydrates with curated preset cards (1.3s) + ✓ preset-prompt-generation/generates the first segment from a curated preset prompt (1.8s) +``` + +**Implications:** + +- The integration-plan.md is **partially superseded** by D-19 outcome: + - Phase 2's "DELETE generic-merged" prescription is invalid; replace with "carry product-local". + - Phase 0 prereqs need the gcc-13 / `NVCC_PREPEND_FLAGS` workaround documented for B200 hosts. + - Phase 4 (in a future PR) is now responsible for actually harmonizing public-vs-Dreamverse pool APIs so the carried product-local modules can be deleted. +- `dreamverse-mock-server` script under `apps/dreamverse/scripts/` is the only canonical launcher. The conda env's legacy `/home/william5lin/miniconda3/envs/fv-main/bin/dreamverse-server` should NOT be used (it points at canonical Dreamverse repo). +- The audio re-encode handling in `apps/dreamverse/server/video_generation.py` was carried per `c1fe5d4c`; verify the exact shape (restored from source vs deferred) when reading the commit. +- Once this branch lands as a PR + merges, the Dreamverse repo can be archived per [integration-plan.md](integration-plan.md) Phase 7. + +**Open follow-ups:** + +- Open a PR for `will/dreamverse-monorepo` (target main, base on `will/ltx2_sr_port` until #1288 merges). +- Re-Oracle the post-fix-up state to confirm the prior FAIL is now PASS. +- Eventually move audio re-encode into a public module (Phase 4) so the carried product file can be slimmed. +- Eventually do real Phase 4 API harmonization between Dreamverse pool and public `fastvideo.entrypoints.streaming.GpuPool` so the 7 carried product files can be deleted. + +### D-18: Option B+ — Dreamverse becomes `apps/dreamverse/` subfolder under FastVideo + +**Status:** ✅ Resolved 2026-05-05. [integration-plan.md](integration-plan.md) is the executable migration plan; [integration-review.md](integration-review.md) is deprecated but kept for drift audit + OSS precedents. +**Source:** User decision after reviewing [integration-review.md](integration-review.md)'s Option D recommendation. + +**Question:** [integration-review.md](integration-review.md) recommended **Option D** — Dreamverse stays a separate repo, generic backend (streaming runtime, GPU pool, prompt enhancer, router) merges into `fastvideo.entrypoints.streaming.*`. The user reviewed this and chose a different shape: keep the generic-backend principle from Option D but ALSO move the Dreamverse FE + product server into FastVideo as a subfolder (`apps/dreamverse/`). Combination is "Option B+" (Option B layout with Option D's backend principle). + +**Decision:** Option B+. Concrete shape: + +- **One repo**: `hao-ai-lab/FastVideo`. Dreamverse repo gets archived after migration completes. +- **Python ML library** stays at root: `fastvideo/`, `fastvideo-kernel/`. +- **Generic backend** stays at `fastvideo.entrypoints.streaming.*` (already there per #1257/#1258/#1284/#1286/#1288). +- **Dreamverse product** moves into `apps/dreamverse/{server,web,prompts,serve_configs,scripts}/`. +- **Tooling**: uv workspace for Python (`[tool.uv.workspace] members = ["apps/dreamverse/server"]`), standalone pnpm for the FE (no root `package.json`), split CI workflows with path-filter triggers. + +**Rationale:** + +- Drops the cross-repo coordination overhead identified in the post-#1286 rebase cycle (D-17 handled by consolidating into mega-PR; D-18 prevents the next round of cross-repo coordination from happening). +- Keeps the architectural separation Option D recommended (FastVideo owns reusable runtime; product owns product). The boundary is now `apps/dreamverse/` directory rather than two repos. +- Single repo means atomic cross-cutting refactors (e.g. GpuPool API change + Dreamverse adoption) ship as one PR. +- OSS precedents support the shape (chainlit uv-workspace + pnpm; open-webui Python + Svelte with paths-ignore CI). The librarian explicitly noted no precedent for "Python ML library + Next.js product merged into library namespace" — but this isn't that pattern. Dreamverse goes into a sibling directory, NOT into `fastvideo.entrypoints.dreamverse.*`. Library namespace stays clean. + +**Why not Option D (separate repos):** + +- Each upstream merge into FastVideo invalidates Dreamverse's lockfile/imports; the post-#1286 rebase showed this requires coordination overhead that scales with feature velocity. +- Cross-repo contract tests catch shape drift but not behavior drift. +- Two repos means two `AGENTS.md`, two CI configs, two release stories, two Dependabot dashboards. + +**Why not Option C (full merge into `fastvideo.entrypoints.dreamverse.*`):** + +- Forces FastVideo to ship Tailwind config + curated preset JSON + Next.js build artifacts. +- Locks Dreamverse product cadence to FastVideo PyPI releases. +- Librarian: "no 1:1 precedent for Python ML library + Next.js product merged into library namespace" — argues against this. + +**Why not Option B (subfolder, but generic backend folded into `apps/dreamverse/server/`):** + +- Other consumers (Dynamo, future streaming clients) need the backend without the Dreamverse product. Folding the backend under `apps/dreamverse/server/` would force Dynamo to either depend on `apps/` paths (ugly) or carry a fork. + +**Implications:** + +- [integration-review.md](integration-review.md) is **deprecated** (banner header + reading-guide demotion). Kept in tree for drift audit + OSS precedent reference. +- [integration-plan.md](integration-plan.md) is the **canonical executable plan** with 7 phases (Phase 0: land #1288; Phase 1: skeleton + tooling; Phase 2: backend move; Phase 3: FE move; Phase 4: promote generic-pending; Phase 5: prompt enhancer fork retirement; Phase 6: CI/release cutover; Phase 7: archive Dreamverse repo). +- Dreamverse repo will be **archived** at end of Phase 7 — not before. +- Dreamverse history does NOT migrate cross-repo via `git mv` (technical limitation); original history stays in archived Dreamverse repo, and Phase 2 PR body records the source SHA(s). +- New top-level `apps/` directory created — must be excluded from FastVideo PyPI wheel via `[tool.setuptools.packages.find] exclude = ["apps*", ...]`. +- Drift items from [integration-review.md](integration-review.md) get folded into specific phases of [integration-plan.md](integration-plan.md) (e.g. health routes → Phase 4, DR-1 → Phase 5). + +**Open questions deferred to phase planning:** + +- DR-2 (`cerebras_ifm`): public Literal vs Dreamverse-side custom provider — decide before Phase 5. +- VPO (`video_position_offset_sec` semantics): persistent vs per-segment — decide in Phase 4. +- Cross-repo history: fresh import vs `git subtree` import — decide before Phase 2. +- CORS / write-endpoint security policy: dev-only vs auth vs firewall — decide before Phase 6. + +### D-17: Abandon 6-PR split — land everything as single mega-PR #1288 + +**Status:** ✅ Resolved 2026-05-05. PR #1287 closed; PR #1288 opened on `will/ltx2_sr_port` covering the full chain. +**Source:** User decision after observing the post-#1286 rebase + re-slice cycle. + +**Question:** The original plan ([STACK.md](../../../STACK.md), [pr-roadmap.md](pr-roadmap.md)) called for the remaining `will/ltx2_sr_port` content (after PRs 7.5/7.6/7.7/7.8/7.9 landed) to ship as 6 stacked PRs: 7.10 (#1287, generate_async), 8 (server contract docs), LTX-2 SR runtime, NVFP4, post-fixes, agents-cleanup. PR #1287 was opened on 2026-05-05 as the first slice. Should the remaining 5 slices be opened sequentially as planned, or should everything be consolidated into one PR? + +**Decision:** Consolidate. Close #1287; open one mega-PR (#1288) on `will/ltx2_sr_port` covering all 34 commits / 71 files / +13,074 LOC at once. + +**Rationale:** + +- The post-#1286 rebase + re-slice cycle exposed real overhead: backup branch, interactive rebase with manual `drop` directives, force-push, re-slice 6 bookmarks, push next slice as new remote, open new PR, update memory dir. Repeating that 6 more times for the remaining slices accumulates substantial review-coordination overhead with diminishing structural benefit. +- The 6 layers are not independent in the way that landed PRs 7.5-7.9 were. PR 7.10 (`generate_async`) is the only API-shape change; PR 8 is docs+tests on top; LTX-2 SR / NVFP4 / post-fixes / agents-cleanup are feature/fix/docs work that doesn't shape the public API. Reviewing them as one ordered diff is at least as easy as reviewing 6 stacked PRs whose dependencies must be tracked manually. +- Single PR keeps CI / merge queue simpler and avoids the 6-PR cascade where every upstream merge invalidates the chain below it. + +**Implications:** + +- [STACK.md](../../../STACK.md) (top-level, 10-PR split tracker) is **deprecated**. Kept in tree as a historical artifact with the merged half (PRs 1-4 of the 10) accurate. Safe to delete in a follow-up. +- [authors.md](authors.md), [`CO-AUTHORS.md`](../../../CO-AUTHORS.md) — co-author roster is unchanged; trailers still apply per-commit on every commit in the consolidated PR. +- [runbook.md](runbook.md) — "After a PR merges (re-slice protocol)" section replaced by a simpler "After PR #1288 merges" section. +- Local split bookmarks (`will/api_7.10`, `will/api_8`, `will/ltx2_sr_runtime`, `will/ltx2_nvfp4`, `will/ltx2_post_fixes`, `will/agents_cleanup`) are no longer maintained; safe to delete locally. +- `origin/will/api_7.10` — pushed during the #1287 cycle; can be deleted on origin once #1287 close-cleanup completes. + +**Watch outs:** + +- The PR is large (71 files, +13,074 LOC). Reviewers will need commit-by-commit review; the PR body structures the layers in commit order to make this tractable. +- If #1288 becomes too large to merge cleanly later (e.g. main moves significantly underneath it), the fallback is to re-split — but the current expectation is to land it as-is. + +### D-12: `GpuPool` layer separation — keep distinct from `VideoGenerator` + +**Status:** ✅ Resolved (interim) + 🟡 Deferred long-term shape to PR 7.10. +**Source:** Oracle review on 2026-05-04, post-PR-#1257 merge. + +**Question:** Should `fastvideo.entrypoints.streaming.GpuPool` (PR #1257) be +folded into `fastvideo.entrypoints.video_generator.VideoGenerator`, or kept +separate? Three alternatives were evaluated: + +| Alt | Approach | Verdict | +|---|---|---| +| A | Status quo — `VideoGenerator` (single inference call) and `GpuPool` (multi-session orchestration) stay separate | ✅ Correct as **interim** | +| B | `VideoGenerator` absorbs the pool's role (`from_pretrained_pool`, `acquire/release/run`) | ❌ **Wrong layer.** Conflates execution with serving scheduler. | +| C | `GpuPool` becomes a thin **session-aware async executor** over PR 7.10's `generate_async` | ✅ Correct **long-term destination** | + +**Decision:** Alt A as interim; evolve toward Alt C once PR 7.10 lands +`generate_async`. Do NOT pursue Alt B. + +**Rationale:** + +- `VideoGenerator` is a library handle — "execute one request, possibly + across ranks via `MultiprocExecutor`/`RayDistributedExecutor`." +- `GpuPool` is serving infrastructure — "schedule N concurrent sessions + across N independent replicas, with sticky session-to-GPU affinity for + cache locality." +- These are different layers driven by different consumers (a Python + script doing `gen.generate(req)` vs. a WebSocket server with sticky + sessions). Folding them muddies both surfaces. + +**Key finding — `MultiprocExecutor` and `SubprocessGpuPool` are orthogonal, +not redundant:** + +| Layer | Job | Granularity | +|---|---|---| +| `MultiprocExecutor` (`fastvideo/worker/`) | TP/SP shard ONE inference call across N GPU ranks | per-call | +| `streaming_generator.py` (existing real-time path) | Per-frame streaming via `MultiprocExecutor.submit_step`/`get_result` | per-step within one generator | +| `SubprocessGpuPool` (`entrypoints/streaming/`, PR #1257) | Serve N concurrent sessions on N replicas, sticky-bound | per-session | + +Both spawn subprocesses because **CUDA contexts demand process boundaries**, +not because they solve the same problem. Sharing low-level lifecycle +utilities (process spawn, queue plumbing, shutdown) is a future refactor; +unifying the abstractions is wrong. + +**Sticky binding stays in the pool, NOT in `VideoGenerator`:** sticky +session-to-GPU affinity is a serving policy driven by LTX-2's per-GPU +continuation cache (last-9-decoded-frames + audio-latents). Different +consumers want different policies — stateless OpenAI HTTP wants +per-request leasing; LTX-2 streaming wants sticky affinity; per-frame +real-time streaming wants a continuous queue. Keeping policy in the pool +keeps `VideoGenerator` policy-free. + +**Specific risks flagged in PR #1257 (already merged):** + +| Risk | Mitigation (when relevant) | +|---|---| +| `GpuPool.run() -> Any` is sync — fine for whole-segment dispatch, blocks on cancellation | Replace with `run_async() -> AsyncIterator[VideoEvent]` in PR 7.10 cycle (`generate_async` makes this trivial) | +| `PoolAssignment.gpu_id: int` assumes one-GPU-per-worker | Don't lock as public API. Future may need `device_ids: list[int]` for topology-aware pooling (one worker = group of GPUs running internal `MultiprocExecutor`) | +| `GpuPool` could be documented as the canonical FastVideo serving API | Mark as **experimental / server-internal** in docstring until PR 7.10 lands. Don't include in user-facing API docs yet | +| Memory: N processes = N model replicas (~10-50 GB each) | Expected for concurrent serving with crash isolation. CUDA IPC weight sharing loses isolation; CPU-shared-memory loading helps host RAM not device. Real scalable path is topology-aware pooling later. | + +**Action items (carried into post-7.10 cycle):** + +- [ ] Update `GpuPool` ABC docstring to note "API may change post-PR-7.10" +- [ ] Plan to replace `run()` with `run_async() -> AsyncIterator[VideoEvent]` in PR 7.10 cycle +- [ ] Don't promote `gpu_id: int` to public API; revisit shape post-7.10 +- [ ] Consider clarifying field naming (e.g. `worker_id` is the stable identifier; `gpu_id` is current-impl detail) +- [ ] When opening 7.10's PR, have it consume `generate_async` from `GpuPool.run_async` end-to-end + +**Open thread it touches:** PR 7.10 (`open-threads.md` item D — generate_async) +unblocks Alt C and is the natural place to land the API shape change. + +### D-15: Streaming router (PR #1286) — keep in-repo, defer sticky / active-active + +**Status:** ✅ Resolved (interim). Pre-merge polishes applied. Three follow-up +items tracked. +**Source:** Oracle review on 2026-05-05, during PR #1286 review cycle. + +**Question:** Where should the multi-replica WebSocket router live? Should it +ship at all (vs. delegating to nginx/envoy)? Should sticky session routing +or weighted/round-robin balancing be in the initial PR? + +| Alt | Approach | Verdict | +|---|---|---| +| A | Status quo — `fastvideo/entrypoints/streaming/router/`, FastAPI-based, single-primary failover, lazy `httpx`/`websockets` imports | ✅ **Keep** | +| B | Move to separate package `fastvideo-router/` | ❌ **Premature** — adds packaging/release/compat overhead before evidence of independent adoption | +| C | Fold router into the streaming server itself (one app, mode flag) | ❌ Conflates router/generator lifecycles, mode-dependent config, drags inference deps into routing deployments | +| D | Replace with reverse proxy (nginx/envoy/HAProxy) recipes | ❌ Not as the SOLE answer — mature proxies don't naturally emit FastVideo typed `gpu_unavailable` frames or evolve with FastVideo session semantics. Recommend external proxies as a complement at high scale. | +| E | Add sticky session routing now | ❌ **Defer** — implementing correctly depends on where `session_id` is available (URL/header is easy, first JSON frame is invasive). Reconnects are rare today. | +| F | Add weighted / round-robin now | ❌ **Defer** — active-active without sticky routing is worse for LTX-2 continuation locality than active-passive failover | + +**Decision:** Alt A — keep current shape. Apply pre-merge polishes; preserve +forward-compat for sticky routing. + +**Rationale:** + +- Python router is justified as a FastVideo-aware control-plane component, + not a replacement for Envoy/HAProxy. It can emit typed + `gpu_unavailable` frames, evolve with FastVideo session semantics, + and ship local/dev deployment without ceremony. +- The current abstraction is small + testable: `RouterConfig`, + `ReplicaRegistry`, `ReplicaStatus`, `HttpProbe` (Protocol/structural alias). + Adding strategy registries / telemetry interfaces / active-active policies + now would be over-engineering. +- Active-passive (single primary) is the right MVP for LTX-2 streaming — + preserves continuation cache locality (D-12 sticky binding rationale) + better than naive active-active. +- The biggest architectural risk isn't placement; it's accidentally baking + in unstated semantics. Define single-primary behavior + config validation + now so future active-active or sticky routing becomes additive. + +**Pre-merge polishes applied (per gemini + Oracle review):** + +| # | What | Why | +|---|---|---| +| 1 | `ReplicaRegistry.select()` docstring rewrite | gemini flagged "round-robin via insertion order" claim was misleading — implementation always returns `[0]`. Replaced with explicit "first healthy primary, else first healthy non-primary; this MVP picks first match within tier; round-robin/weighted deferred". | +| 2 | Refactored `run_health_check_loop` to share single `httpx.AsyncClient` across the loop's lifetime via `_build_default_probe()` async context manager | gemini flagged per-probe client instantiation as inefficient. With ~1 probe/second default polling, TCP/TLS handshake overhead is non-trivial; now reuses connection. Tests inject probes directly so the path stays bypassable. | +| 3 | Probe all replicas concurrently per cycle via `asyncio.gather(..., return_exceptions=True)` | gemini flagged sequential probes risk falling behind `health_check_interval_seconds` if replicas time out. Now per-cycle wall time = max(probe latencies), not sum. | +| 4 | `RouterConfig.__post_init__` validation | Oracle recommended: empty replicas, non-positive intervals/timeouts, thresholds < 1, non-`http(s)://` URLs, and >1 primary all `raise ValueError`. Surfaces misconfiguration at config-load instead of confusing runtime failures. | +| 5 | Migrated `@app.on_event("startup"/"shutdown")` to `@contextlib.asynccontextmanager`-based `_lifespan()` | Pre-merge — FastAPI deprecated the old API. Was tracked as the 7.9 caveat in pr-roadmap.md. | + +**One review comment intentionally not implemented:** + +| Comment | Decision | +|---|---| +| gemini medium: `_load_router_config` duplicates `fastvideo.api.parser.parse_config` logic | Kept manual flat-from-nested mapping. The YAML schema has nested `health_check:` block but `RouterConfig` is flat; using `parse_config` directly would require either restructuring `RouterConfig` to have a nested `HealthCheckConfig` (schema change beyond this PR's scope) or accepting incomplete parsing. Manual mapping is intentional and well-typed. | + +All 4 review threads marked resolved on the GitHub PR. + +**Action items (deferred):** + +- [ ] Track sticky session routing extensibility — when needed, add + `ReplicaRegistry.select(routing_key: str | None = None)` so registry + evolution is additive; document upfront where `session_id` should + appear (URL/header preferred over first JSON frame to avoid + buffering/peeking) +- [ ] Track `_bridge_session()` backpressure note — fine for MVP because + `websockets` library provides basic transport backpressure, but at + high scale add max_size/timeouts or recommend Envoy/HAProxy in front +- [ ] If active-active multi-primary becomes a requirement, define + behavior (round-robin within healthy primaries, weighted, sticky-by-key) + rather than letting `select()` silently pick `[0]` + +**Watch outs:** + +- `session_id` in WebSocket URL/headers is the cleanest sticky-routing + hook. If it ends up only in the first JSON message, sticky routing + later will require buffering/peeking before backend selection. +- Multi-primary configs are now explicitly rejected by validation; + documented + enforced. +- `_bridge_session()` is fine for MVP (the libraries provide basic + backpressure), but not production-grade for edge load. Document the + limit. + +**Open thread it touches:** open-threads.md items #13 (sticky routing), +#14 (bridge backpressure), #15 (multi-primary semantics). + +### D-16: Streaming router polish round 2 — second-pass fixes on top of D-15 + +**Status:** ✅ Resolved. Applied as `[fix] streaming: router polish — bridge +cancel + state machine + deps` (`a152cb77` on `will/api_7.9`, `40e265b8` on +`will/ltx2_sr_port`). +**Source:** Second-pass review on PR #1286, 2026-05-05, after D-15's pre-merge +polishes landed. + +**Question:** D-15 closed the structural review (placement, sticky/active-active +deferral, basic `__post_init__` validation). On a second pass through the same +files, five latent issues surfaced that weren't covered by gemini's first pass +or Oracle's structural review. Apply them on top of the merged D-15 polishes, +or queue for a follow-up PR? + +**Decision:** Apply on top of `will/api_7.9` directly. All five are bug-class +or DX-class — none are scope-expanding architecture changes — so folding them +into PR #1286 keeps the router landing in one reviewable unit instead of +shipping a router PR plus an immediate follow-up fix PR. + +**Fixes applied:** + +| # | File | What | Why | +|---|---|---|---| +| 1 | `router/main.py::_bridge_session` | Replaced `asyncio.gather()` with `wait(FIRST_COMPLETED)` + explicit `cancel()`/drain + `_is_normal_disconnect()` classifier | `gather` waited for both directions; on client disconnect, the backend-reader task leaked and stayed pending. Backend `ConnectionClosed` also surfaced as an unhandled exception in server logs. New shape: first task to finish triggers explicit cancel of the other, both are drained, and only non-routine exceptions re-raise. | +| 2 | `router/registry.py::record_success` | Split state transitions: `UNKNOWN -> HEALTHY` is now immediate on first successful probe; only `UNHEALTHY -> HEALTHY` remains gated by `recovery_threshold` | Previously a fresh registry needed `recovery_threshold` consecutive successes before any replica was selectable. With default `recovery_threshold=2` and `health_check_interval=1s`, that meant 2-3s of `gpu_unavailable` rejections at startup. Now the first probe promotes immediately; recovery gating still protects against flapping replicas. | +| 3 | `router/registry.py::_build_default_probe` | Missing `httpx` now raises `RuntimeError` with install hint instead of yielding a "disabled" probe stub | Previous behavior: silently returned `(0.0, "httpx not installed; ...")` for every probe, which `record_failure` then folded into `UNHEALTHY` after `failure_threshold` cycles. Operators saw replicas drop UNHEALTHY with a confusing reason and no clear remediation. Hard-fail at startup is the right surface. | +| 4 | `router/config.py::__post_init__` | Extended D-15 polish #4 with: rejects `urlparse(url).path not in ("", "/")`, rejects `query`/`fragment`, rejects duplicate URLs across replicas | D-15's validation rejected non-`http(s)://` URLs and >1 primary; it didn't catch `http://host/api` (the router appends `/health` and `/v1/stream` itself, so a base-URL with path yields malformed routes) or `[{url: x}, {url: x}]` (replica registry keys by URL — duplicates would silently collapse to one entry, masking the misconfiguration). | +| 5 | `cli/router_serve.py::_load_router_config` | Replaced silent list-comprehension filter (`for r in replicas_raw if isinstance(r, dict) and r.get("url")`) with per-index `raise ValueError` | Original parser silently dropped malformed YAML entries. A single typo in `replicas[2].url` would yield 2 replicas instead of 3 with no log line. New shape: explicit per-index error message ("missing required key 'url'", "must be a mapping"). | +| 6 | `pyproject.toml::[streaming]` extra | Added `websockets` as explicit dep | `router/main.py::_bridge_session` does `import websockets` lazily and raises `RuntimeError` if missing. The `[streaming]` extra was an implicit transitive — anyone installing only `[streaming]` (and not the broader requirements) hit the runtime error. Now explicit. | + +**Tests added (7 cases in `fastvideo/tests/entrypoints/streaming/test_router.py`):** + +- `TestUnknownToHealthyImmediate.test_first_success_promotes_unknown` — first probe success transitions `UNKNOWN -> HEALTHY` regardless of `recovery_threshold` +- `TestUnknownToHealthyImmediate.test_unhealthy_recovery_still_gated_by_threshold` — `UNHEALTHY -> HEALTHY` still requires `recovery_threshold` successes +- `TestConfigValidation.test_rejects_path_in_url` / `test_rejects_query_in_url` / `test_rejects_fragment_in_url` / `test_rejects_duplicate_urls` / `test_accepts_trailing_slash` — `__post_init__` URL validation matrix + +**Verification:** 17/17 router tests pass on both branches. `pre-commit run` +clean (yapf / ruff / codespell / mypy). `lsp_diagnostics` clean on changed +regions; the one pre-existing `Task` generic-type warning at `main.py:37` is +unrelated and predates this commit. + +**In-flight pre-commit corrections (not part of the 6 fixes themselves):** + +- yapf auto-reformatted 4 files (kept verbatim). +- ruff `UP038`: rewrote `isinstance(exc, (CancelledError, WebSocketDisconnect))` + to `isinstance(exc, CancelledError | WebSocketDisconnect)`. +- mypy `[misc]`: renamed loop var `exc` (inside `for task in done`) to + `task_exc` to avoid name collision with the outer + `except ImportError as exc` binding. + +**Open thread it touches:** None new. Item #14 (bridge backpressure) and +item #13 (sticky routing) from D-15 remain deferred — this round addressed +**cancellation/disconnect** semantics on the bridge, which is distinct from +**throughput backpressure**. Item #14 still applies: at higher load, add +`_bridge_session()` max-size + timeout limits or recommend Envoy/HAProxy +in front. + +### D-14: Streaming auxiliaries (PR #1284) — cohesion + concrete-vs-Protocol scoping + +**Status:** ✅ Resolved (interim). Two polish items applied during review; one +operational caveat tracked. +**Source:** Oracle review on 2026-05-04, during PR #1284 review cycle. + +**Question:** Is PR #1284's bundle of 4 streaming-server auxiliary modules +(`prompt/safety.py`, `prompt/rewrite.py`, `session_logger.py`, +`mock_server.py`) correctly scoped? Should `mock_server` live in production +module path? Should `PromptSafetyFilter` be a Protocol? Should the bundle +have been split into 4 PRs? + +| Alt | Approach | Verdict | +|---|---|---| +| A | Status quo — single PR, 4 modules under `streaming/`, mock_server in production path, concrete safety filter | ✅ **Keep** | +| B | Split into 4 separate PRs | ❌ Process overhead, not architectural improvement | +| C | Move `mock_server.py` into `tests/` | ❌ Would reduce discoverability + install-time usability of `python -m fastvideo.entrypoints.streaming.mock_server` | +| D | Move `session_logger.py` to `streaming/observability/` (or top-level `fastvideo/observability/`) | ❌ Premature — currently session-shaped + streaming-specific; promote when a non-streaming consumer appears | +| E | Convert `PromptSafetyFilter` to Protocol (like `LLMProvider`) | ❌ Premature abstraction — only one classifier exists; small duck-typed surface preserves future Protocol introduction without breaking the concrete | +| F | Convert `MockGenerator` to Protocol | ❌ Same — small duck-typed surface; no second mock generator exists | + +**Decision:** Alt A — keep current shape. Apply two polish items from +Oracle's review before merge. + +**Rationale:** + +- "Streaming-server auxiliaries" is cohesive enough at 730 LOC with + isolated modules + tests. Each module has independent code path but + shared deployment context (the streaming server boots them all). +- `mock_server.py` in production path is a strength: reuses + `build_app()` for protocol parity. Hiding it under `tests/` would lose + `python -m fastvideo.entrypoints.streaming.mock_server` CLI access for + FE devs. +- Concrete `PromptSafetyFilter` matches "ship what we have, abstract + later" pattern. Internal had multi-classifier composition; public + ships single + leaves chaining as a Dreamverse-side concern (per D-2). +- Same pattern for `MockGenerator`: small duck-typed `_GeneratorLike` + surface lets a second mock implementation drop in without inheritance. +- `threading.Lock` (not `asyncio.Lock`) in `session_logger.py` is + correct — writes come from real encoder/control threads via + `run_in_executor`, not from coroutines directly. `asyncio.Lock` would + be the wrong primitive for cross-thread concurrency. + +**Pre-merge polishes applied (per Oracle):** + +| Polish | What | Why | +|---|---|---| +| 1 | Removed `RewriteOptions.user_system_prompt_override` | Inert public field — was declared but never threaded through to `enhancer.rewrite()`. Shipping unused public options is more likely to bite than any structural choice. Re-add when actually wired through. | +| 2 | Sanitized `session_id` filename in `session_logger.SessionLogger._get_file()` | Defense-in-depth: today session_id is server-generated UUID, but a future code path that accepts client-supplied ids would otherwise allow path traversal via `../`. Added `_FILENAME_SANITIZE_RE = re.compile(r"[^A-Za-z0-9._-]")` + sub before `os.path.join`. | + +**Operational caveat tracked (not a code change):** + +- `SafetyDecision.UNAVAILABLE` is treated as `ALLOW` by callers — a + policy choice that's correct for an opt-in safety filter, but + callers should log loudly so operators know the filter is degraded. + Tracked as open-threads.md item #12. + +**Pre-merge review feedback (4 of 4 resolved on the GitHub PR):** + +| # | File:Line | Severity | Issue | Fix applied | +|---|---|---|---|---| +| 1 | `session_logger.py:57` | High | `log()` race vs `close()` — `KeyError` on `_locks[session_id]` | Atomic capture in `_get_file()`; master `_registry_lock`; `with lock, contextlib.suppress(ValueError):` | +| 2 | `rewrite.py:71` | Medium | `re.compile()` in hot path | Module-level `_LEADING_MARKER_RE`, top-level `import re` | +| 3 | `safety.py:105` | Medium | `_ensure_loaded()` race on concurrent fastText load | `_load_lock = threading.Lock()` + double-check pattern | +| 4 | `pyproject.toml:145` | Medium | `streaming` extra missing `prompt-safety` | Added to aggregator | + +All 4 review threads marked resolved via GraphQL `resolveReviewThread`. + +**Action items (deferred):** + +- [ ] Track `SafetyDecision.UNAVAILABLE` log loudness in + open-threads.md item #12 — when streaming server starts using the + safety filter, ensure operator-visible logging on `UNAVAILABLE` + results +- [ ] If a second safety classifier appears (Perspective API, Detoxify, + custom rules), promote `PromptSafetyFilter` to a Protocol — same + pattern as `LLMProvider` per D-13 +- [ ] If a second mock generator appears (different frame patterns, + different latency models), promote `MockGenerator` to a Protocol + +**Open thread it touches:** PR #1284 itself; future safety-classifier +Protocol promotion; future observability module extraction. + +### D-13: Prompt enhancer / `LLMProvider` abstraction shape — keep streaming-scoped + +**Status:** ✅ Resolved (interim) + 🟡 Three deferred polishes after metrics or 2nd consumer. +**Source:** Oracle review on 2026-05-04, pre-PR-#1258-merge. + +**Question:** Is PR #1258's `fastvideo.entrypoints.streaming.prompt.*` module +correctly designed? Should it be (a) Protocol-based vs ABC, (b) under +`streaming/` vs top-level `fastvideo.prompt.*`, (c) closed 3-op enum vs +open `complete()` API? + +| Alt | Approach | Verdict | +|---|---|---| +| A | Status quo — `streaming/prompt/*`, Protocol provider, fixed 3 ops, lazy `httpx`, per-call `AsyncClient` | ✅ **Keep** | +| B | Move to top-level `fastvideo.prompt.*` (decouple from streaming) | ❌ **Premature.** No second consumer exists yet. | +| C | Convert `LLMProvider` Protocol → ABC with default impls + retry classification | ❌ **Wrong direction.** Biases extension toward OpenAI shape; `_openai_compat.py` already factors that as helper not inheritance. | + +**Decision:** Alt A as interim. Promote to Alt B only when a second +non-streaming consumer (OpenAI server, batch generation, tooling) actually +needs the prompt enhancer. Don't pursue Alt C. + +**Rationale:** + +- Public contract is tiny — `name: str` + `async complete(LLMRequest) -> LLMResponse`. ABC adds zero value. +- `_openai_compat.py` is the right place for shared logic — helper, not base class. Anthropic / local / custom providers stay first-class. +- The 3 ops (enhance / auto_extend / rewrite) are LTX-2 streaming concepts. `auto_extend` (continue prompt sequence) and `rewrite` (multi-line alternatives) come directly from session UX. Calling this "the FastVideo prompt API" misrepresents that. + +**Specific risks flagged in PR #1258 (already merged-pending review):** + +| Risk | Mitigation (when relevant) | +|---|---| +| API publicity — calling this "the FastVideo prompt API" before a second consumer exists | Document module as "streaming-server prompt enhancement" in user-facing docs; keep it nested under `entrypoints/streaming/` | +| `httpx.AsyncClient` per-call (no connection pooling) | Acceptable for ~6-10 calls per LTX-2 session; LLM latency dominates. Add optional `client_factory` parameter LATER if metrics show connect overhead is meaningful. | +| 3 fixed operations could constrain future generic use | Closed enum is right for application-level orchestration. Future generic consumers should either call `provider.complete()` directly, or get a thin separate enhancer that shares the provider/fallback machinery. | +| `register_provider(priority=-1)` semantics rely on Python's negative-index `list.insert` | Cosmetic concern; docstring is clear. Could be tightened to explicit branch later. | +| `runtime_checkable` Protocol with `name: str` instance attribute — static type checkers may miss missing `name` | Acceptable; runtime check via `isinstance(p, LLMProvider)` works for plugin discovery. | + +**Action items (deferred):** + +- [ ] Document `fastvideo.entrypoints.streaming.prompt.*` as streaming-scoped in user-facing docs (PR 12 docs migration); avoid promoting as framework-level +- [ ] Add optional `client_factory` parameter to providers when metrics justify pooling +- [ ] Plan future move to `fastvideo.prompt.*` (with import shim) when second non-streaming consumer materializes +- [ ] Track Q-2 reactivation: promote LTX-2 prompt orchestration (locked segments, segment-prompts JSON parsing) to public `fastvideo.entrypoints.streaming.prompt.ltx2_orchestration` when a second LTX-2-style consumer appears + +**Open thread it touches:** Dreamverse migration (open-threads.md DR-1) +will be the first real test of the public surface. Lessons learned there +inform whether Alt B becomes feasible. + +## D-decisions (from `dreamverse_review.md`, Apr 26) + +### D-1: Realtime runtime → streaming GpuPool migration shape + +**Status:** ✅ Resolved. + +Internal `RealtimeRuntimeConfig` had a multi-model registry + +flattened sampling defaults. Public `SubprocessGpuPool` is single-model ++ uses per-request `SamplingConfig`. + +**Decision:** Drop multi-model registry on integration branch (not used +in production). Construct `GeneratorConfig` for chosen model and pass to +`SubprocessGpuPool`. Move sampling defaults to a server-side +`default_request: GenerationRequest` template. + +**Risk:** Migration branch surfaces missing-model errors if a flow +silently relied on registry to swap models per-session. Integration +tests exercise at least one segment per supported model id before +merging. + +### D-2: PR 7.7 prompt enhancer API surface narrower than internal + +**Status:** ✅ Resolved. + +Public `PromptEnhancer.enhance/auto_extend/rewrite` returns +`LLMResponse(content, provider, model, latency_ms, fallback_used)`. +Internal returns `EnhanceResult(prompt, fallback_used, error, ...)` / +`RewriteResult(prompts, ..., rollout_id, rollout_label, ...)`. + +**Decision:** Adapt at the call site via +`Dreamverse/server/prompting/_internal_compat.py` shim. Locked-segment / +next-segment-index plumbing stays Dreamverse-side. Public stays minimal +and provider-agnostic. + +**Open question (Q-2):** Promote LTX-2-specific orchestration into +`fastvideo.entrypoints.streaming.prompt.ltx2_orchestration` once a +second consumer appears. Logged for future review. + +### D-3: Multi-stage provider race vs. sequential fallback + +**Status:** ✅ Resolved (public stays sequential). + +Internal enhancer runs all providers in a stage in parallel +(`_run_provider_race`). Public enhancer runs sequentially with +retryable-error fallback. + +**Decision:** Public stays sequential for PR 7.7. Race is a +Dreamverse-specific tail-latency optimization that depends on parallel +API budgets. + +**Risk / Q-3:** First-segment latency on Dreamverse may regress +slightly when Cerebras has a bad minute (sequential waits 20s before +trying Groq). If real production concern, add public +`concurrency: int = 1` knob behind a race path — but only after measuring. + +### D-4: Skip PR 7.9 router for the integration branch + +**Status:** ✅ Resolved. + +Internal stack ships `router/main.py` for multi-replica load balancing. +Dreamverse deployment uses single replica per region. + +**Decision:** Land PR 7.9 publicly (upstream the surface). Skip wiring +into Dreamverse integration branch. Dreamverse's `server/main.py` does +not import from `router/`. + +### D-5: Audio re-encode (PR 7.10) needed for streaming, deferred + +**Status:** 🟡 Deferred to PR 7.10. + +Internal streaming server's per-step path runs `_re_encode_audio` inside +`_stream_av_fmp4_events` so each fMP4 segment ships with +continuation-conditioning audio. Whole-segment `pool.run()` path doesn't +need this. + +**Decision:** Land PR 7.10's `generate_async` publicly. Dreamverse +integration branch initially keeps using `pool.run()` (whole segment, no +re-encode). Follow-up branch swaps to `generate_async` + audio re-encode. + +**Open question (Q-5):** Acceptable for first switch, or does +Dreamverse audio quality regress vs. internal until 7.10 wires in? + +### D-6: `realtime/local_runtime.py` is NOT upstreamed + +**Status:** ✅ Resolved. + +It was the FastVideo-internal precursor to `streaming.gpu_pool`. +Upstreaming both would create two GPU pool implementations in public. + +**Decision:** Don't upstream `realtime/local_runtime.py`. Dreamverse +switches to `streaming.gpu_pool.SubprocessGpuPool` on integration +branch. Internal module can be deleted at follow-up. + +### D-7 / Q-6: `FP4Config` is private-only + +**Status:** ✅ **Resolved May 2.** + +April 26: `Dreamverse/server/video_generation.py:271` imported +`fastvideo.layers.quantization.fp4_config.FP4Config` from +FastVideo-internal only. The 411-line module hard-imported `flashinfer`. + +**Two options at the time:** + +1. Colocate publicly with `flashinfer` as optional extra + `pip install fastvideo[fp4]`; refactor `FP4QuantizeMethod` to take + layer-prefix list from a pipeline-config field instead of hardcoding + ltx2 paths. +2. Keep private — Dreamverse imports from internal via thin shim. + +**Recommendation at the time:** option 1 once API refactor settles. + +**Resolution:** May 2 work chose option 1. +- `365a66c7` upstreamed FP4Config with lazy `flashinfer` import in + loader helper (no public hard-dep) +- `94c983a2` renamed FP4 → NVFP4 to disambiguate from MX-FP4 / OCP-FP4 +- `42b30bf9` wired through `fastvideo.layers.quantization` + +See [quantization.md](quantization.md) for full details. + +### D-8: `ltx2_image_crf` silently dropped by public schema + +**Status:** 🔴 **Unverified post-`d80c2a8`.** + +April 26: Dreamverse's `server/video_generation.py:406` passed +`ltx2_image_crf=0.0` to `SamplingParam(...)`. Public +`fastvideo.api.sampling_param.SamplingParam` did NOT have this field; +the BE logged ERROR and silently dropped the kwarg. + +**Migration target** (per [design.md](design.md) compatibility map): +`request.stage_overrides.refine.image_crf`. + +**Resolution status:** `d80c2a8` (May 2) refactored +`server/video_generation.py` to use typed `GeneratorConfig` + +`preset_overrides["refine"]`. Whether this PR routed `image_crf` +through the typed `stage_overrides` path or left it silently dropped is +unverified. See [open-threads.md](open-threads.md). + +### D-9: `aarch64-conda-linux-gnu-cc` triton compile failure + +**Status:** ✅ Resolved (operational). + +Conda env injected an ARM cross-compiler ahead of `gcc` on `$PATH`, so +`torch._inductor`'s triton launcher failed compilation. Setting +`ENABLE_TORCH_COMPILE=0` bypasses it. + +**Long-term fix:** clean conda env's compiler shadowing or add +`CC=gcc` override in Dreamverse's worker bootstrap. + +### D-10: Warmup OOM on shared GPU + +**Status:** ✅ Resolved (operational). + +When `CUDA_VISIBLE_DEVICES` lands on a GPU another tenant uses, LTX-2 +warmup fails with OOM. Picking an idle GPU (4-7 in test setup) is a +manual step. + +**Improvement:** pre-warm probe that checks free memory before booting +the pool would prevent this. + +### D-11: ffmpeg fragment write `Broken pipe` + +**Status:** ✅ Resolved (cosmetic). + +When WS client closes before backend finishes streaming first segment, +ffmpeg hits `[Errno 32] Broken pipe`. Currently propagates to +"User step failed". Cosmetic — swallowing pipe-broken on intentional +disconnect would clean up logs. + +## Q-questions (from `streaming-server-upstream-plan.md`, Apr 17) + +### Q-1: Router placement (in-repo or separate package) + +**Status:** ✅ Resolved (in-tree). + +**Recommendation at the time:** separate package `fastvideo-router/` or +`fastvideo/contrib/router/`; defer final call to PR 7.9. + +**Resolution:** PR 7.9 implementation places router in-tree at +`fastvideo/entrypoints/streaming/router/`. + +### Q-2: Session ID authority + +**Status:** ✅ Resolved (server-generated). + +**Recommendation:** server-generated UUID; accept externally provided +session ID only for resume flows. + +### Q-3: Torch compile kwargs typing (opaque vs full vs hybrid) + +**Status:** ✅ Resolved (hybrid). + +**Recommendation:** hybrid — type the common four (`backend`, +`fullgraph`, `mode`, `dynamic`) + allow `extras: dict[str, Any]`. + +**Resolution:** PR 6 + NVFP4 `221cb20a` shipped exactly this hybrid. + +### Q-4: Prompt safety / fasttext dependency + +**Status:** ✅ Resolved (optional extra). + +**Recommendation:** ship as optional extra `pip install fastvideo[prompt-safety]`. + +**Resolution:** PR 7.8 implements as optional extra. + +### Q-5: Audio-specific tensor payloads in continuation + +**Status:** ✅ Resolved (typed `LTX2ContinuationState`). + +`ltx2_audio_clean_latent`, `ltx2_audio_denoise_mask`, +`ltx2_audio_latents` not in pre-refactor public schema. + +**Recommendation:** classify as opaque fields inside +`LTX2ContinuationState.payload`, not top-level sampling fields. + +**Resolution:** PR 7's typed `LTX2ContinuationState` lifts these into +typed fields (see [cross-repo-surfaces.md](cross-repo-surfaces.md) +field mapping table). + +### Q-6: Dynamo subpackage home + +**Status:** ✅ Resolved (lives in Dynamo repo). + +**Resolution:** No Dynamo code in FastVideo. Full backend package +(handler, adapter, registration, health check) owned by Dynamo repo at +`components/src/dynamo/fastvideo/`, same pattern as vllm/sglang. +FastVideo only guarantees the public API contract. + +### Q-7 (was Q-6 in dreamverse_review): How to land FP4Config publicly + +**Status:** ✅ Resolved May 2 — option 1 (colocate publicly). + +See D-7 above. + +### Q-8: Disaggregation readiness contract test + +**Status:** 🟡 Recommended; not yet shipped. + +PR ai-dynamo/dynamo#7544 is aggregated-only. `ContinuationState` hybrid +already supports future prefill/decode split. + +**Recommendation:** PR 7.10 explicitly validate `ContinuationState` +survives round-trip through Dynamo-style RPC (pickle or JSON), even +though Dynamo isn't using it today. Cheap regression guard. + +### Q-9: Dynamo progress/status passthrough + +**Status:** 🟡 Deferred until Dynamo clarifies. + +`NvVideosResponse` has `status` and `progress` fields. + +**Recommendation:** PR 7.10 stays aggregated-final-only to match PR +#7544 shape; revisit after Dynamo clarifies their streaming/progress +semantics. + +## Cross-doc questions still 🔴 OPEN + +These need decisions; tracked also in [open-threads.md](open-threads.md): + +| ID | Question | Source | Why it matters | +|---|---|---|---| +| **D-8** | Did `d80c2a8` route `ltx2_image_crf` correctly, or is it still silently dropped? | dreamverse_review | Latent silent-drop bug; FP4-disabled paths may degrade | +| **VPO** | `video_position_offset_sec` — persistent accumulation (a) vs per-segment hint (b) | dreamverse_integration | Needs decision before PR 7.6 emits state | +| **SBS** | `SessionStore` / `BlobStore` lifecycle (TTL/eviction/blob-drop on state replacement) | dreamverse_integration | Needs decision in PR 7.5 design pass | +| **#1** | Migrate `/healthz`+`/readyz`+`/status` into FastVideo `build_app` | streaming-upstream-plan + handoff | Closes BE_FLAVOR=fastvideo FE-compatibility | +| **#3** | Add `cerebras_ifm` to public `PromptEnhancerConfig.provider` Literal | handoff | Internal supports it; public schema doesn't | +| **#4** | Expose `layer_profile` on typed `engine.quantization` | handoff | Removes Dreamverse's `experimental["pipeline_config"]` dodge | +| **#5** | Typed `dit_config.quant_config` carrier (design TBD) | handoff | Eliminates the `experimental["pipeline_config"]` escape hatch entirely | diff --git a/.agents/memory/dreamverse-integration/design.md b/.agents/memory/dreamverse-integration/design.md new file mode 100644 index 0000000000..a0d0e00c8b --- /dev/null +++ b/.agents/memory/dreamverse-integration/design.md @@ -0,0 +1,332 @@ +# Design — Typed Public Inference API + +Synthesis of the FastVideo public inference API refactor design philosophy. +For PR-by-PR execution see [pr-roadmap.md](pr-roadmap.md). For the streaming +extension see [streaming-server.md](streaming-server.md). + +**Last updated:** 2026-05-03. + +## Why the refactor + +The pre-refactor public boundary mixed three concerns through `**kwargs`: + +- `VideoGenerator.from_pretrained(..., **kwargs)` mixed engine/runtime, + pipeline init, and component overrides. +- `VideoGenerator.generate_video(..., **kwargs)` mixed prompt+inputs, + sampling, output, and model-specific workflow knobs. +- Unknown keys silently filtered or merely logged → API drift hard to detect. +- Multi-stage models (LTX-2 two-stage, Hunyuan15 SR, LongCat distill+refine) + exposed via ad hoc top-level flags. + +This was already painful for LTX2/Dreamverse and would worsen as more +multi-stage pipelines came in. + +## Core decision + +FastVideo has: + +1. **Typed nested public schema** — `RunConfig`, `ServeConfig`, + `GeneratorConfig`, `GenerationRequest`, `ContinuationState`. +2. **Model-owned named pipeline presets** — `ltx2_two_stage`, + `longcat_distill_refine`, `hunyuan15_sr_1080p`, etc. All 13 model families + landed presets in PR 4. +3. **Semantic stage overrides by stage name** — + `request.stage_overrides["refine"] = LTX2RefineStageOverride(...)`. +4. **Optional advanced explicit plans** for power users — `GenerationPlan` + (escape hatch only; not the canonical surface). +5. **YAML-first CLI** with dotted overrides — + `fastvideo generate --config run.yaml --request.sampling.seed 42`. + +The canonical user experience: choose a model → choose a preset → override +a few typed fields → generate. Dicts/YAML/JSON are supported as +serialization, but parse immediately into typed objects with strict +unknown-key validation. + +## Schema surface + +Implemented in [`fastvideo/api/`](file:///home/william5lin/FastVideo/fastvideo/api/): + +| Type | Role | +|---|---| +| `RunConfig` | Offline envelope: `generator` + `request` | +| `ServeConfig` | Serving envelope: `generator` + `server` + `default_request` + optional `streaming` | +| `GeneratorConfig` | `model_path`, `revision`, `trust_remote_code`, `engine`, `pipeline` | +| `EngineConfig` | parallelism / offload / compile / quantization / flags | +| `PipelineSelection` | `workload_type`, `preset`, `preset_version`, `components`, `preset_overrides`, `experimental` | +| `GenerationRequest` | `prompt`, `negative_prompt`, `inputs`, `sampling`, `runtime`, `output`, `stage_overrides`, `state`, `plan`, `extensions` | +| `ContinuationState` | Opaque envelope `{kind: str, payload: dict[str, Any]}` | +| `GenerationPlan` | Advanced/escape-hatch only; `{stages: list[PlannedStage], final_stage: str|None}` | + +Files: + +| File | Role | +|---|---| +| [`schema.py`](file:///home/william5lin/FastVideo/fastvideo/api/schema.py) | All public dataclasses | +| [`parser.py`](file:///home/william5lin/FastVideo/fastvideo/api/parser.py) | `from_dict`, `to_dict`, `load_yaml`, `load_json`, validation | +| [`overrides.py`](file:///home/william5lin/FastVideo/fastvideo/api/overrides.py) | Dotted override application | +| [`compat.py`](file:///home/william5lin/FastVideo/fastvideo/api/compat.py) | Legacy kwargs translation (~370 lines, scheduled for death PRs 14-17) | +| [`presets.py`](file:///home/william5lin/FastVideo/fastvideo/api/presets.py) | Preset registry | +| [`sampling_param.py`](file:///home/william5lin/FastVideo/fastvideo/api/sampling_param.py) | Internal `SamplingParam` adapter (canonical home since PR 4) | +| [`results.py`](file:///home/william5lin/FastVideo/fastvideo/api/results.py) | `GenerationResult` / `VideoResult` | +| [`errors.py`](file:///home/william5lin/FastVideo/fastvideo/api/errors.py) | Path-aware validation errors | + +## Boundary normalization rule + +Every public inference entrypoint normalizes into typed config objects +before touching legacy internals (`FastVideoArgs`, `SamplingParam`). +Includes Python constructors, `generate*` calls, CLI `generate`, CLI +`serve`, OpenAI server request translation, streaming server request +translation. + +Legacy internals (`FastVideoArgs`, `SamplingParam`) may remain temporarily, +but only behind a typed normalization boundary. + +## Strict-by-default validation + +All structured inputs are strict: + +- Unknown keys → error +- Wrong types → error +- Invalid stage names → error +- Incompatible state/preset combinations → error + +The only intentional escape hatches: + +- `generator.pipeline.experimental` — for in-flight features without typed home +- `request.extensions` — same, request-side + +These bypass validation by design. Intent: shrink as presets absorb +model-specific fields. New fields should not land in `experimental` / +`extensions` without a plan to either promote them to typed fields or +remove them within two PR cycles. + +Error format includes nested path: + +``` +Invalid field: request.stage_overrides.refine.num_inference_steps +Expected int, got "two" +Preset: ltx2_two_stage +Stage: refine +``` + +## Request mutation tracking + +When a `GenerationRequest` is parsed from raw dict (YAML/JSON/Python), +FastVideo tracks which fields the user explicitly provided vs. which got +schema defaults. Matters for `request_to_sampling_param()` — explicit +values override model defaults; schema defaults do NOT. + +Mechanics: + +- At parse time, original raw dict + baseline snapshot stored on the request. +- Dataclass field mutations (e.g. `request.sampling.seed = 7`) captured via + lightweight `__setattr__` dirty-path recording. +- Dict-typed field mutations (e.g. `del request.stage_overrides["refine"]`) + detected at access time by diffing current dict vs. baseline. +- Setting a field to its schema default value IS captured as explicit, so + it overrides model defaults. +- Raw dict reconciled lazily when `normalize_generation_request()` is called. + +## Schema purity (model-specific fields still in shared schema) + +Remain for back-compat during initial migration; targeted for migration +into preset-owned typed override classes: + +| Field | Owner | Migration target | +|---|---|---| +| `SamplingConfig.height_sr` / `width_sr` / `num_inference_steps_sr` | Hunyuan15 SR | `HunyuanSRStageOverride` (PR 10) | +| `SamplingConfig.guidance_scale_2`, `boundary_ratio` | Wan2.2, LingBotWorld | preset-owned (per-family PR) | +| `InputConfig.mouse_cond`, `keyboard_cond`, `grid_sizes` | MatrixGame | `request.extensions` or typed input config | +| `InputConfig.c2ws_plucker_emb` | LingBotWorld | `request.extensions` or typed input config | +| `InputConfig.refine_from`, `stage1_video` | LongCat | `LongCatRefineStageOverride` inputs (PR 9) | + +LTX-2 multi-modal CFG knobs (`ltx2_modality_scale_video/_audio`, +`ltx2_rescale_scale`, `ltx2_stg_scale_video/_audio`, +`ltx2_stg_blocks_video/_audio`) still leak into shared `SamplingParam` but +only LTX-2 reads them today. Migration to typed `LTX2SamplingOverride` is +deferred to per-model migration sweep. + +**LTX-2 CFG-force fix landed in PR 6**: defaults moved from `3.0/7.0` to +`1.0/1.0` to stop force-enabling CFG for non-LTX-2 families. +`ltx2_base` preset still sets `3.0/7.0` explicitly. Regression guard: +`test_presets.py::TestPresetDefaultTypes::test_ltx2_cfg_defaults_are_off`. + +## Continuation state + +Public surface: + +```python +@dataclass +class ContinuationState: + kind: str # e.g. "ltx2.v1" + payload: dict[str, Any] +``` + +Internally, model-specific typed subclasses (e.g. `LTX2ContinuationState` +at [`fastvideo/pipelines/basic/ltx2/continuation.py`](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/continuation.py)). + +Payload must be JSON-serializable or use opaque blob-ID indirection for +large tensors — supports both stateless OpenAI client round-trip AND +future Dynamo prefill/decode disaggregation. + +Hybrid model: server-held for streaming WS, client-round-trip for +stateless HTTP. See [streaming-server.md](streaming-server.md) D-1. + +## Pipeline package structure (target) + +Per-family colocation under `pipelines/basic//`: + +``` +fastvideo/pipelines/basic// +├── _pipeline.py # pipeline implementation(s) +├── presets.py # user-facing presets (DONE in PR 4) +├── pipeline_configs.py # engine/arch config (from configs/pipelines/) +└── stages/ # model-specific stages (optional, if >2 files) +``` + +What stays shared: + +- `configs/pipelines/base.py` — `PipelineConfig` base class +- `configs/models/` — architecture defs (dits/, vaes/, encoders/) +- `pipelines/stages/` — shared stages only (denoising, encoding, decoding, + text_encoding, timestep_preparation, ...) + +What's gone (PR 4): + +- `fastvideo/configs/sample/` — directory removed entirely; defaults + absorbed into per-family `presets.py`. +- All 12 `*_SamplingParam` subclass files — `SamplingParam` lives at + `fastvideo/api/sampling_param.py`; defaults flow through + `SamplingParam.from_pretrained()` → `_from_preset()`. + +What's pending: `configs/pipelines/.py` colocation, optional +`pipelines/stages/_*.py` colocation. Per-model migration PRs +(6/9/10) include the colocation step for that family. + +## YAML examples + +### Run config + +```yaml +generator: + model_path: /models/ltx2 + engine: + num_gpus: 1 + parallelism: {tp_size: -1, sp_size: -1} + offload: {dit: false, text_encoder: false, vae: false, pin_cpu_memory: true} + pipeline: + workload_type: t2v + preset: ltx2_two_stage + components: + config_root: /models/ltx2-config + upsampler_weights: /models/ltx2-refine + lora_path: /models/ltx2-refine-lora + preset_overrides: + refine: {enabled: true, add_noise: true} + +request: + prompt: "a fox running through snow" + sampling: {num_frames: 121, height: 1024, width: 1536, num_inference_steps: 8, seed: 42} + output: {save_video: true, return_state: true} + stage_overrides: + refine: {num_inference_steps: 2, guidance_scale: 1.0} +``` + +### Serve config + +See [`Dreamverse/serve_configs/streaming_demo.yaml`](file:///home/william5lin/Dreamverse/serve_configs/streaming_demo.yaml) +for a canonical example matching internal/ui defaults (LTX-2 distilled, +NVFP4, 121 frames @ 1088×1920 24fps, 5 inference steps, 2-step refine). + +## Compatibility mapping (legacy → typed) + +| Legacy field | New path | +|---|---| +| `model_path` | `generator.model_path` | +| `num_gpus` | `generator.engine.num_gpus` | +| `tp_size` / `sp_size` | `generator.engine.parallelism.{tp_size,sp_size}` | +| `dit_cpu_offload` | `generator.engine.offload.dit` | +| `enable_torch_compile` | `generator.engine.compile.enabled` | +| `torch_compile_kwargs` | split: `generator.engine.compile.{backend,fullgraph,mode,dynamic}` + `.extras` | +| `enable_torch_compile_text_encoder` | `generator.engine.compile.text_encoder_enabled` | +| `prompt_txt` | `request.inputs.prompt_path` | +| `image_path` / `video_path` | `request.inputs.{image_path,video_path}` | +| `output_path` / `save_video` / `return_frames` | `request.output.*` | +| `seed` / `num_frames` / `height` / `width` / `fps` / `num_inference_steps` / `guidance_scale` | `request.sampling.*` | +| `enable_teacache` / `return_trajectory_*` | `request.runtime.*` | + +LTX-2 specific (private adapter, NOT public compat promise): + +| Legacy LTX-2 field | New path | +|---|---| +| `config_model_path` | `generator.pipeline.components.config_root` | +| `ltx2_refine_enabled` | `generator.pipeline.preset_overrides.refine.enabled` | +| `ltx2_refine_upsampler_path` | `generator.pipeline.components.upsampler_weights` | +| `ltx2_refine_lora_path` | `generator.pipeline.components.lora_path` | +| `ltx2_refine_num_inference_steps` | `request.stage_overrides.refine.num_inference_steps` | +| `ltx2_refine_guidance_scale` | `request.stage_overrides.refine.guidance_scale` | +| `ltx2_refine_add_noise` | `generator.pipeline.preset_overrides.refine.add_noise` | +| `ltx2_image_crf` | `request.stage_overrides.refine.image_crf` | +| `return_continuation_state` | `request.output.return_state` | + +LongCat: + +| Legacy | New | +|---|---| +| `refine_from` / `stage1_video` | `request.inputs.{refine_from,stage1_video}` | +| `t_thresh` / `spatial_refine_only` / `num_cond_frames` | `request.stage_overrides.refine.*` | + +## External inspirations (and limits) + +| Source | Useful idea | Don't copy | +|---|---|---| +| Ray | YAML-first config interchange | Ray's package layout | +| SGL `multimodal_gen` | Split instance/request config; dict input parsed into typed objects; merge user overrides on model defaults | `SamplingParams._adjust(ServerArgs)` (request depending on engine config); broad weakly-typed request bags | +| vLLM-Omni | Model-owned pipeline presets; explicit stage topology; per-stage default sampling | Positional `sampling_params_list`; serving-engine stage-index semantics in primary Python API | + +## Naming guidance + +- Public schema names namespaced under `fastvideo.api` +- Don't export from top-level `fastvideo/__init__.py` until migration further along +- `RunConfig` / `ServeConfig` get sufficient disambiguation from training + config via the namespace +- Future rename to `EngineQuantizationConfig` reserved if a collision + arises (deferred) + +## Public Python API (canonical form) + +```python +from fastvideo import VideoGenerator +from fastvideo.api import ( + GeneratorConfig, GenerationRequest, + EngineConfig, OutputConfig, + PipelineSelection, SamplingConfig, +) + +generator = VideoGenerator.from_pretrained( + config=GeneratorConfig( + model_path="/models/ltx2", + engine=EngineConfig(num_gpus=1), + pipeline=PipelineSelection(workload_type="t2v", preset="ltx2_two_stage"), + ) +) + +result = generator.generate( + GenerationRequest( + prompt="a fox running through snow", + sampling=SamplingConfig(num_frames=121, height=1024, width=1536, + num_inference_steps=8, seed=42), + output=OutputConfig(save_video=True, return_state=True), + ) +) +``` + +Accepted constructor forms: + +```python +VideoGenerator.from_pretrained(config=GeneratorConfig(...)) +VideoGenerator.from_config(GeneratorConfig(...)) +VideoGenerator.from_file("run.yaml") +VideoGenerator.from_pretrained("model-id", num_gpus=2, ...) # stable convenience +VideoGenerator.from_pretrained(model_path, **legacy_kwargs) # compat (deprecated PR 13) +``` diff --git a/.agents/memory/dreamverse-integration/integration-plan.md b/.agents/memory/dreamverse-integration/integration-plan.md new file mode 100644 index 0000000000..e79ad021c7 --- /dev/null +++ b/.agents/memory/dreamverse-integration/integration-plan.md @@ -0,0 +1,1380 @@ +# Integration Plan — Option B+ (Monorepo subfolder + generic backend) + +**Status:** Approved plan for execution; do not treat as historical audit. + +**Last updated:** 2026-05-05. + +**Decision owner:** User decision in the 2026-05-05 planning thread. + +**Target branch:** `will/ltx2_sr_port` in +[`/home/william5lin/FastVideo`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/runbook.md#L11-L16). + +**Supersedes:** +[`integration-review.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/integration-review.md#L543-L563) +for the recommendation only. The drift audit, citations, and open-thread +inventory in that document remain reference material. + +**Companion docs:** + +- Current integration snapshot: + [`state.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/state.md#L10-L20). +- PR status and #1288 scope: + [`pr-roadmap.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/pr-roadmap.md#L38-L42). +- Typed public API design: + [`design.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L24-L43). +- Cross-repo Dreamverse surfaces: + [`cross-repo-surfaces.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L13-L20). +- Active follow-ups and drift items: + [`open-threads.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L15-L45). +- Streaming server route contract: + [`streaming-server.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L232-L259). +- Memory index and repo paths: + [`README.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/README.md#L73-L80). +- Execution runbook: + [`runbook.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/runbook.md#L79-L124). + +--- + +## Decision recap + +Option B+ is the selected end state. + +Option B+ combines two earlier options: + +1. **Option B layout principle:** Dreamverse becomes a product subfolder in + the FastVideo repository. +2. **Option D backend principle:** reusable backend code remains generic under + `fastvideo.entrypoints.streaming.*`, not under a Dreamverse namespace. + +This differs from the prior Option D recommendation in +[`integration-review.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/integration-review.md#L543-L563): + +- Prior recommendation: keep Dreamverse product in a separate repo and merge + only reusable backend pieces into FastVideo. +- New decision: move Dreamverse product code into the FastVideo repo under + `apps/dreamverse/`, while keeping reusable backend code generic. + +The repo decision is now: + +- One canonical repo: `hao-ai-lab/FastVideo`. +- Dreamverse repo is archived or redirected after migration. +- FastVideo Python library remains at the repository root. +- FastVideo kernel package remains in `fastvideo-kernel/`. +- Generic streaming backend remains at `fastvideo.entrypoints.streaming.*`. +- Dreamverse product server and web app move to `apps/dreamverse/`. + +The backend boundary stays aligned with the typed-public-boundary rule: public +inputs normalize into typed objects before legacy internals are touched +([design](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L73-L83)). + +The generic backend work already in flight through PRs #1257, #1258, #1284, +#1286, and #1288 stays on that path. #1288 is the current consolidated vehicle +for the remaining `will/ltx2_sr_port` chain +([roadmap](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/pr-roadmap.md#L38-L42)). + +--- + +## Target architecture + +### Repo layout (after migration) + +```text +FastVideo/ +├── fastvideo/ # Python ML library, public API, entrypoints +│ └── entrypoints/{openai,streaming}/ # existing OpenAI + generic streaming backend +├── fastvideo-kernel/ # separate CUDA/custom-kernel package +├── examples/serving/streaming_demo.yaml +├── docs/contributing/dreamverse-development.md +├── apps/ +│ └── dreamverse/ +│ ├── README.md, AGENTS.md, arch.md, design.md, gpu-pool.{svg,drawio} +│ ├── server/ +│ │ ├── pyproject.toml, main.py, config.py, video_generation.py +│ │ ├── session/{controller.py,messages.py} +│ │ ├── routes/presets.py +│ │ ├── prompts/ +│ │ └── tests/ +│ ├── web/ # standalone Next.js frontend +│ ├── prompts/ # curated product content if separated +│ ├── serve_configs/ # product deployment YAMLs +│ └── scripts/ # setup and launch scripts +├── .github/workflows/ +│ ├── ci-dreamverse-backend.yml +│ └── ci-dreamverse-frontend.yml +├── pyproject.toml, uv.lock +└── .pre-commit-config.yaml +``` + +FastVideo already has a Python-package layout with `fastvideo/`, +`fastvideo-kernel/`, `examples/`, `docs/`, and `tests/` +([codebase map](file:///home/william5lin/FastVideo/.agents/memory/codebase-map/README.md#L5-L75)). +Option B+ adds `apps/dreamverse/` without moving the library or kernel paths. + +### Module boundary + +| Area | Owns | Does not own | Evidence / reference | +|---|---|---|---| +| `fastvideo.api` | `GeneratorConfig`, `GenerationRequest`, `ServeConfig`, `VideoResult`, `VideoEvent`, `ContinuationState` | Product route policy or curated content | Typed schema surface is documented in [design](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L45-L72). | +| `fastvideo.entrypoints.streaming.*` | Generic WebSocket server, GPU pool, streaming protocol, fMP4 stream, mock server, prompt enhancer, safety/rewrite helpers, router | Dreamverse-only curated presets, prompt UX routes, frontend devtools | Streaming target package is documented in [streaming-server](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L164-L195). | +| `apps/dreamverse/server.*` | Product FastAPI composition, env defaults, curated content, Dreamverse WebSocket/session flow, product worker wrapper | Generic reusable FastVideo backend code | Product-only routes stay Dreamverse-side per route contract [streaming-server](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L239-L255). | +| `apps/dreamverse/web` | Next.js product UI and browser tests | Python package release or FastVideo core CI | New standalone frontend CI is introduced in this plan. | +| `apps/dreamverse/prompts` | Curated product prompt content and presets | Generic prompt provider protocol | DR-1 keeps product prompt orchestration Dreamverse-side unless a second consumer appears [open-threads](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L440-L455). | +| `examples/serving/` | Public-safe serving examples | Product deployment secrets or private paths | Missing streaming demo config is tracked as drift item #7 [integration-review](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/integration-review.md#L259-L276). | + +### Import contract + +`apps/dreamverse/server/*` may import the following FastVideo surfaces: + +```python +# Public root re-exports +from fastvideo import VideoGenerator, PipelineConfig, SamplingParam + +# Typed public schema, results, presets +from fastvideo.api import GeneratorConfig, GenerationRequest, ServeConfig, ... + +# Reusable streaming runtime +from fastvideo.entrypoints.streaming import build_app, ... +from fastvideo.entrypoints.streaming. import ... + +# Pipeline + arch configs (typed dataclasses, public surface for advanced wiring) +from fastvideo.configs.pipelines import ... +from fastvideo.configs.models import ... + +# High-level entrypoints +from fastvideo.entrypoints.video_generator import VideoGenerator +``` + +It must NOT import from internal library implementation paths: + +```python +from fastvideo.pipelines... import ... # internal pipeline impl +from fastvideo.models... import ... # internal model impl +from fastvideo.layers... import ... # internal layer impl +from fastvideo.worker... import ... # internal worker IPC +from fastvideo.fastvideo_args import ... # legacy args; use GeneratorConfig +``` + +**Why the relaxation from `{api, entrypoints.streaming}` only**: Dreamverse's +[`video_generation.py`](file:///home/william5lin/Dreamverse/server/video_generation.py#L260-L420) +currently imports from `fastvideo.configs`, `fastvideo.entrypoints.video_generator`, +and uses `VideoGenerator.from_pretrained()` — these are public surfaces by design +([design.md](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L295-L332)) +even though they live outside `fastvideo.api/`. Restricting to only `api` + +`entrypoints.streaming` would force a 578-LOC rewrite of `video_generation.py` +which is out of scope for the migration. The contract enforces the +**meaningful** boundary: no internal `pipelines/models/layers/worker` paths. + +Rationale: + +- Dreamverse's three integration surfaces are pipeline construction, realtime + runtime, and continuation state + ([cross-repo-surfaces](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L13-L20)). +- The target public surface for reusable streaming runtime is + `fastvideo.entrypoints.streaming/` + ([streaming-server](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L55-L60)). +- Dynamo and Dreamverse should consume stable typed APIs, not private modules + ([cross-repo contract](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L188-L210)). + +Add a contract test in Phase 2: + +```python +# apps/dreamverse/server/tests/test_import_contract.py +import ast +from pathlib import Path + +ALLOWED_PREFIXES = ( + "fastvideo.api", + "fastvideo.entrypoints.streaming", + "fastvideo.entrypoints.video_generator", + "fastvideo.configs", +) +ALLOWED_EXACT = ("fastvideo",) +FORBIDDEN_PREFIXES = ( + "fastvideo.pipelines", + "fastvideo.models", + "fastvideo.layers", + "fastvideo.worker", + "fastvideo.fastvideo_args", +) + + +def test_dreamverse_server_imports_only_public_fastvideo_surfaces() -> None: + root = Path(__file__).resolve().parents[1] + bad: list[tuple[str, int, str]] = [] + for path in root.rglob("*.py"): + if "/tests/" in path.as_posix(): + continue + for node in ast.walk(ast.parse(path.read_text(), filename=str(path))): + names = ( + [a.name for a in node.names] if isinstance(node, ast.Import) + else [node.module] if isinstance(node, ast.ImportFrom) and node.module + else [] + ) + for name in names: + if not name: + continue + if name.startswith(FORBIDDEN_PREFIXES): + bad.append((str(path.relative_to(root)), node.lineno, name)) + + assert bad == [], f"Forbidden internal imports: {bad}" +``` + +Treat this as the import-boundary gate for all future product-server changes. + +--- + +## Tooling stack + +### Python build: uv workspace + +Use uv workspaces for the Python side. + +Precedent and rationale: + +- Official uv workspace docs: https://docs.astral.sh/uv/concepts/workspaces/ +- The docs describe workspaces as suitable for a FastAPI web application + alongside libraries. +- Similar workspace patterns are used by chainlit, rerun-io/rerun, + microsoft/autogen, and langgenius/dify. +- Hatch workspace remains an alternative, but uv is already present in + FastVideo's root `pyproject.toml` + ([pyproject](file:///home/william5lin/FastVideo/pyproject.toml#L89-L115)). + +Root `pyproject.toml` currently uses setuptools and discovers packages by +excluding assets, docker, docs, and scripts +([pyproject](file:///home/william5lin/FastVideo/pyproject.toml#L1-L3), +[package find](file:///home/william5lin/FastVideo/pyproject.toml#L158-L162)). + +Apply this root diff in Phase 1: + +```diff +diff --git a/pyproject.toml b/pyproject.toml +@@ + [tool.uv] + prerelease = "allow" + ++[tool.uv.workspace] ++members = ["apps/dreamverse/server"] ++ + [tool.uv.sources] + torch = [ +@@ + [tool.setuptools.packages.find] +-exclude = ["assets*", "docker*", "docs", "scripts*"] ++exclude = ["assets*", "docker*", "docs", "scripts*", "apps*"] + + [tool.wheel] +-exclude = ["assets*", "docker*", "docs", "scripts*"] ++exclude = ["assets*", "docker*", "docs", "scripts*", "apps*"] +``` + +Create `apps/dreamverse/server/pyproject.toml` in Phase 1: + +```toml +[project] +name = "dreamverse-server" +version = "0.1.0" +description = "Dreamverse product server" +requires-python = ">=3.10" +dependencies = [ + "fastvideo[streaming]", + "fastapi==0.129.0", + "uvicorn==0.41.0", + "aiofiles", + "websockets", +] + +[project.optional-dependencies] +test = [ + "httpx", + "pytest", + "pytest-asyncio", +] + +[tool.uv] +package = false + +[tool.uv.sources] +fastvideo = { workspace = true } + +[tool.pytest.ini_options] +testpaths = ["tests"] +pythonpath = ["."] +asyncio_mode = "auto" +``` + +Notes: + +- `package = false` keeps this as an application workspace member, not a + package to publish. +- `fastvideo = { workspace = true }` forces local workspace resolution during + development and CI. +- Product server release is Docker/deploy workflow, not PyPI. + +### Frontend build: standalone pnpm + +Do not add a root `package.json`. + +Keep all frontend tooling under: + +```text +apps/dreamverse/web/package.json +apps/dreamverse/web/pnpm-lock.yaml +apps/dreamverse/web/playwright.config.* +``` + +Rationale: + +- FastVideo remains primarily a Python ML library. +- Python contributors should not need Node or pnpm for normal work. +- This intentionally diverges from chainlit's root JS workspace pattern and + follows the simpler open-webui-style split. + +The frontend CI works from `apps/dreamverse/web/` directly. + +### Pre-commit + +Root `.pre-commit-config.yaml` currently excludes generated or heavyweight +paths, including `.agents`, `examples`, and `fastvideo/models` +([pre-commit](file:///home/william5lin/FastVideo/.pre-commit-config.yaml#L4-L17)). + +Extend the global exclude for the Node frontend only. + +Do not exclude `apps/dreamverse/server/`; Python hooks must cover product +server code. + +Apply this Phase 1 diff: + +```diff +diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml +@@ + fastvideo/models/.*| ++ apps/dreamverse/web/.*| + examples/.*| +``` + +Verification: + +```bash +pre-commit run --files \ + pyproject.toml \ + .pre-commit-config.yaml \ + apps/dreamverse/server/pyproject.toml +``` + +Memory-dir edits are excluded from yapf/ruff/mypy; only the filename-space +check applies +([runbook](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/runbook.md#L81-L93)). + +### `.gitignore` + +Root `.gitignore` currently contains Python, docs, asset, output, and local +tooling ignores, and notes that Node artifacts are only ignored under `ui/` +([gitignore](file:///home/william5lin/FastVideo/.gitignore#L38-L94)). + +Add Dreamverse-scoped Node ignores only, **AND unignore product public assets** (the root currently ignores `*.png`, `*.jpg`, `*.mp4`, `*.gif` per [`.gitignore:6-9`](file:///home/william5lin/FastVideo/.gitignore#L6-L9)): + +```diff +diff --git a/.gitignore b/.gitignore +@@ + # Next.js / Node artifacts under ui/: see ui/.gitignore ++ ++# Next.js / Node artifacts under apps/dreamverse/web/ ++apps/dreamverse/web/node_modules/ ++apps/dreamverse/web/.next/ ++apps/dreamverse/web/out/ ++apps/dreamverse/web/coverage/ ++apps/dreamverse/web/test-results/ ++apps/dreamverse/web/playwright-report/ ++apps/dreamverse/web/.env.local ++apps/dreamverse/web/.env.development.local ++apps/dreamverse/web/.env.test.local ++apps/dreamverse/web/.env.production.local ++ ++# Unignore migrated Dreamverse product assets — root .gitignore globally ++# ignores *.png/*.jpg/*.mp4/*.gif, but apps/dreamverse/web/public/ MUST ++# be tracked (logo, icons, k2.png, etc.). ++!apps/dreamverse/web/public/** ++!apps/dreamverse/web/prompts/** ++!apps/dreamverse/server/prompts/** ++!apps/dreamverse/gpu-pool.svg ++!apps/dreamverse/gpu-pool.drawio +``` + +Do not add global `node_modules/` or `.next/` ignores. Keep the pattern scoped +so unrelated JS projects do not inherit accidental behavior. **Verify before +committing Phase 3** with `git check-ignore -v apps/dreamverse/web/public/k2.png` +(should report nothing once the unignore lands). + +### CI workflows + +Existing FastVideo CI remains in place: + +- Buildkite GPU and test matrix lives at + [`.buildkite/pipeline.yml`](file:///home/william5lin/FastVideo/.buildkite/pipeline.yml#L199-L280) + and uses path-based monorepo diff watch lists. +- Full suite is triggered by GitHub Actions and Buildkite + ([trigger workflow](file:///home/william5lin/FastVideo/.github/workflows/ci-trigger-full-suite.yml#L52-L83), + [Buildkite full suite](file:///home/william5lin/FastVideo/.buildkite/pipeline.yml#L282-L438)). +- Pre-commit workflow currently runs on pull requests + ([ci-precommit](file:///home/william5lin/FastVideo/.github/workflows/ci-precommit.yml#L1-L32)). +- Docs workflow already uses explicit docs paths + ([infra-docs](file:///home/william5lin/FastVideo/.github/workflows/infra-docs.yml#L3-L18)). +- FastVideo PyPI publish remains version-driven on root `pyproject.toml` + ([publish-fastvideo](file:///home/william5lin/FastVideo/.github/workflows/publish-fastvideo.yml#L1-L72)). + +Add two new workflows. + +#### `.github/workflows/ci-dreamverse-frontend.yml` + +```yaml +name: Dreamverse Frontend + +on: + pull_request: + branches: [main] + paths: + - 'apps/dreamverse/web/**' + - '.github/workflows/ci-dreamverse-frontend.yml' + push: + branches: [main] + paths: + - 'apps/dreamverse/web/**' + - '.github/workflows/ci-dreamverse-frontend.yml' + +permissions: + contents: read + +defaults: + run: + working-directory: apps/dreamverse/web + +jobs: + frontend: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + # IMPORTANT: pnpm/action-setup MUST run BEFORE setup-node when using + # cache: pnpm — setup-node otherwise can't find pnpm to populate cache. + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: pnpm + cache-dependency-path: apps/dreamverse/web/pnpm-lock.yaml + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Typecheck + run: pnpm run typecheck --if-present + + - name: Unit tests + run: pnpm run test --if-present + + - name: Build + run: pnpm run build + + # NOTE: Playwright tests require a running backend. Until Phase 4 lands + # `/healthz`/`/readyz`/`/status`/`/prompt-system-config`/`/curated-presets` + # in `apps/dreamverse/server/main.py`, scope frontend CI to build + unit + # tests only. Re-enable Playwright in Phase 4 once health/preset routes + # are mounted by `apps/dreamverse/server/main.py` (which can wrap public + # `fastvideo.entrypoints.streaming.build_app` and add product routes). + # + # - name: Install Playwright browsers + # run: pnpm exec playwright install --with-deps chromium + # + # - name: Playwright (re-enable in Phase 4) + # run: pnpm exec playwright test +``` + +**Playwright config update needed** when moving FE: `Dreamverse/apps/web/playwright.config.ts` line 39 currently uses `npm run dev`; change to `pnpm run dev` post-move ([source](file:///home/william5lin/Dreamverse/apps/web/playwright.config.ts#L39)). + +#### `.github/workflows/ci-dreamverse-backend.yml` + +```yaml +name: Dreamverse Backend + +on: + pull_request: + branches: [main] + paths: + - 'apps/dreamverse/server/**' + - 'pyproject.toml' + - 'uv.lock' + # apps/dreamverse/server depends on these public surfaces — changes + # there must trigger Dreamverse backend tests: + - 'fastvideo/api/**' + - 'fastvideo/entrypoints/streaming/**' + - 'fastvideo/entrypoints/video_generator.py' + - 'fastvideo/configs/**' + - '.github/workflows/ci-dreamverse-backend.yml' + push: + branches: [main] + paths: + - 'apps/dreamverse/server/**' + - 'pyproject.toml' + - 'uv.lock' + - 'fastvideo/api/**' + - 'fastvideo/entrypoints/streaming/**' + - 'fastvideo/entrypoints/video_generator.py' + - 'fastvideo/configs/**' + - '.github/workflows/ci-dreamverse-backend.yml' + +permissions: + contents: read + +jobs: + backend: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install uv + uses: astral-sh/setup-uv@v3 + + - name: Sync Dreamverse backend workspace (locked) + run: uv sync --locked --package dreamverse-server --extra test + + - name: Backend tests + run: uv run --locked --package dreamverse-server --extra test pytest apps/dreamverse/server/tests/ -q +``` + +Extend existing workflows where appropriate. + +Recommended diffs: + +```diff +diff --git a/.github/workflows/ci-precommit.yml b/.github/workflows/ci-precommit.yml +@@ + pull_request: + branches: [main] ++ paths-ignore: ++ - 'apps/dreamverse/web/**' +``` + +```diff +diff --git a/.github/workflows/ci-trigger-full-suite.yml b/.github/workflows/ci-trigger-full-suite.yml +@@ + pull_request_target: + types: [labeled, synchronize] ++ paths-ignore: ++ - 'apps/dreamverse/**' +``` + +Do not add `paths-ignore` to workflows already constrained by non-Dreamverse +`paths`, such as docs deploy or PyPI publish, unless a later CI audit finds +actual false triggers. + +### Release + +FastVideo PyPI release remains unchanged: + +- Root package is still `fastvideo`. +- Version-driven publish remains tied to root `pyproject.toml` version changes + ([publish workflow](file:///home/william5lin/FastVideo/.github/workflows/publish-fastvideo.yml#L23-L72)). +- `apps*` is excluded from setuptools and wheel discovery. + +Dreamverse product release is separate: + +- Backend: Docker or deployment workflow rooted at `apps/dreamverse/server/`. +- Frontend: Vercel or frontend deploy workflow rooted at `apps/dreamverse/web/`. +- No PyPI publish for `apps/dreamverse/server`. +- No root `package.json`. + +Add deployment workflows only after Phase 6, once the product runs from the +monorepo CI path. + +### OSS precedents used for this plan + +| Project | URL | Pattern applied here | +|---|---|---| +| uv workspaces | https://docs.astral.sh/uv/concepts/workspaces/ | Authoritative Python workspace model. | +| Hatch monorepo | https://hatch.pypa.io/latest/how-to/environment/workspace/ | Alternative workspace model; not selected. | +| chainlit | https://github.com/Chainlit/chainlit | uv workspace precedent plus **per-language CI split** (separate `check-frontend.yaml` / `check-backend.yaml` workflows path-filtered by directory). Not a PR-level split — independent of D-17 single-mega-PR decision. | +| open-webui | https://github.com/open-webui/open-webui | Frontend path filtering (`paths-ignore` on backend-only changes) and separate release tracks. **Note:** open-webui has a root `package.json`; we are choosing standalone-pnpm despite the precedent, to avoid forcing Python-only contributors to install Node. | +| streamlit | https://github.com/streamlit/streamlit | Split Python and JS testing in one repo. | +| gradio | https://github.com/gradio-app/gradio | Python package plus JS workspace precedent. | +| full-stack-fastapi-template-nextjs | https://github.com/nemanjam/full-stack-fastapi-template-nextjs | Separate frontend/backend build and deploy workflows. | +| rerun-io/rerun, microsoft/autogen, langgenius/dify | various | uv workspace examples with workspace members and sources. | + +### Test strategy + +The migration spans CPU-only logic, GPU-required inference, and end-to-end +WebSocket flows. Each phase's verification gate must specify which test +class runs where, because not all tests can run on `ubuntu-latest` CI. + +#### Test taxonomy + +| Class | Marker | Runs in | What it covers | Examples | +|---|---|---|---|---| +| **Unit** | (none / `unit`) | `ci-dreamverse-backend.yml` (ubuntu-latest CI) + locally | Pure logic, no GPU, no live service. Mocked FastVideo backends, schema validation, helper functions. | `test_config.py`, `test_rewrite_prompt_payload.py`, `test_session_init_image.py`, the new `test_import_contract.py` | +| **Integration (fakes)** | `integration` | `ci-dreamverse-backend.yml` + locally | FastAPI test client + in-process fakes/mocks for GPU pool. Validates routes, request/response shapes, session state machine. | `test_health_endpoints.py`, `test_mock_server.py`, `test_entrypoints.py`, `test_prompt_safety.py`, `test_batching.py` (deleted) | +| **Live-service GPU** | `gpu` (skip-by-default in CI) | **Local GPU4 manual QA** + Buildkite-Modal (when added) | Real `fastvideo serve` process + real model weights + real WebSocket round-trips. Validates LTX-2 streaming, NVFP4 wiring, continuation state, frame emission. | `test_realtime_stress.py` (947 LOC), `test_session_logging.py` (1278 LOC) — these spin up real workers per their current shape | +| **Frontend unit / build** | (n/a — pnpm) | `ci-dreamverse-frontend.yml` (ubuntu-latest, no GPU) | Vitest + tsc + Next.js build. No backend needed. | `apps/dreamverse/web/src/**/*.test.ts(x)` | +| **Frontend Playwright E2E** | (n/a — pnpm) | **Local GPU4 manual QA** until Phase 4 lands public health routes; then `ci-dreamverse-frontend.yml` against a mock backend OR a deployed staging | Real browser → real backend WebSocket flow. Requires `/healthz`, `/readyz`, `/status`, `/prompt-system-config`, `/curated-presets`, `/v1/stream`. | `apps/dreamverse/web/e2e/{backend-health,frontend-shell,preset-prompt-generation}.spec.ts` | +| **FastVideo public contract** | (none) | Existing FastVideo CI (`ci-precommit` + Buildkite for GPU) | Schema/shape guards that this migration must not break. | `fastvideo/tests/contract/test_dreamverse_shape.py`, `test_dynamo_shape.py`, `test_generate_async.py` | +| **FastVideo SSIM regression** | (Buildkite path-filter) | Buildkite-Modal | Inference-quality gates for ported models. | `fastvideo/tests/ssim/test_*.py` | + +#### Adding the `gpu` marker + +In Phase 1, add to root `pyproject.toml`: + +```diff + [tool.pytest.ini_options] ++markers = [ ++ "gpu: requires a real GPU + model weights; skip in ubuntu-latest CI", ++] +``` + +In `apps/dreamverse/server/pyproject.toml` `[tool.pytest.ini_options]`, set +the default for the backend test command to skip GPU tests: + +```toml +[tool.pytest.ini_options] +addopts = "-m 'not gpu'" +markers = ["gpu: requires real GPU"] +``` + +GPU-dependent tests must add `@pytest.mark.gpu` at module or function level +during the Phase 2 move. Specifically: `test_realtime_stress.py` and +`test_session_logging.py` per their current LOC and live-service shape. + +#### Local GPU4 verification hook + +This dev node has 8× B200 GPUs. **GPU4** is the operator's chosen target for +migration smoke tests. The original `dreamverse-server` was launched with +`CUDA_VISIBLE_DEVICES=4`, which makes physical GPU 4 appear as logical GPU 0 +inside the process — so the Dreamverse-side log shows `Selected GPU ids: [0]` +even though it physically holds GPU 4. **Always launch with `CUDA_VISIBLE_DEVICES=4`** +to keep the same physical pin during smoke runs. + +##### Phase 0 prerequisites for the GPU4 hook (validated 2026-05-05) + +A live smoke test of `fastvideo serve` from `will/ltx2_sr_port` HEAD +`d23e71c2` ran on GPU4 and revealed two missing optional deps in the +FastVideo `.venv`: + +- **`flashinfer-python`** — required for the NVFP4 path. Without it, the + server fails at boot with `ImportError: NVFP4 quantization requires + flashinfer. Install with 'pip install flashinfer-python'.` +- **`flash_attn`** — optional. Without it, attention falls back to Torch + SDPA (`Cannot use FlashAttention-2 backend ... Using Torch SDPA backend.`). + Functional but slower per inference step. + +For a fast smoke that doesn't need NVFP4, comment out or omit +`engine.quantization` in the serve config — the loader auto-falls-back +to bf16. The serve config in +[`Dreamverse/serve_configs/streaming_demo.yaml`](file:///home/william5lin/Dreamverse/serve_configs/streaming_demo.yaml#L26-L29) +explicitly says: "Hosts without flashinfer / NVFP4: comment out the +`engine.quantization` block below — the loader falls back to bf16 +automatically when no quant_config is set." + +For production-equivalent NVFP4 smoke, install both deps in the FastVideo +`.venv`: + +```bash +.venv/bin/pip install flashinfer-python flash-attn --no-build-isolation +``` + +This is a **Phase 0 prerequisite** to document in +`docs/contributing/dreamverse-development.md` (Phase 1). + +##### Reclaim and redeploy commands + +```bash +# Stop the running Dreamverse-side server holding GPU4 +sudo kill 2453227 # or use the supervisor that owns it + +# Confirm GPU4 is free +nvidia-smi --query-gpu=index,memory.used --format=csv | grep -E '^4,' + +# Deploy the new public FastVideo streaming server pinned to GPU4 +CUDA_VISIBLE_DEVICES=4 uv run --locked --package dreamverse-server \ + fastvideo serve --config apps/dreamverse/serve_configs/streaming_demo.yaml \ + --host 0.0.0.0 --port 8009 + +# Smoke-test from another terminal +curl -s http://localhost:8009/health | jq . +curl -s http://localhost:8009/readyz | jq . # Phase 4+ only +# Drive the FE against it: cd apps/dreamverse/web && pnpm run dev +``` + +This is the **manual QA gate** for any phase that touches the live-service +path (Phase 2 backend move, Phase 3 frontend move, Phase 4 health-route +promotion, Phase 5 prompt enhancer retirement). The verification gate for +each phase calls out whether the GPU4 smoke is required or optional. + +**Cleanup after each test session:** + +```bash +# Kill the test deployment +pkill -f 'fastvideo serve --config' + +# Restart the canonical Dreamverse-side server with the same GPU pin +cd /home/william5lin/Dreamverse +setsid bash -c 'CUDA_VISIBLE_DEVICES=4 exec .venv/bin/dreamverse-server > /tmp/dv.log 2>&1 < /dev/null' & disown + +# Confirm restart +sleep 3 && pgrep -af dreamverse-server | head -3 +``` + +**Verified 2026-05-05**: this kill/redeploy/teardown cycle was executed +end-to-end on `will/ltx2_sr_port` HEAD `d23e71c2`. Public `fastvideo serve` +booted in ~24 s on GPU4 with bf16 fallback (no flashinfer in `.venv`), +served `/health` → 200 `{"status":"ok","sessions":0,"stream_mode":"av_fmp4"}`, +and confirmed empirically that `/healthz`, `/readyz`, `/status`, +`/prompt-system-config`, and `/curated-presets` all 404 (matching drift +table item #4 → Phase 4 promotion target). Smoke artifacts at +`/tmp/opencode/fv_smoke/` (serve.log, smoke.yaml). + +#### Per-phase test responsibilities (summary) + +| Phase | Unit | Integration (fakes) | GPU live (GPU4) | Frontend build | Frontend E2E (Playwright) | +|---|:---:|:---:|:---:|:---:|:---:| +| 0 (#1288 land) | Existing FastVideo suite | Existing | Optional sanity | n/a | n/a | +| 1 (skeleton) | New empty pkg `pytest --collect-only` | n/a | n/a | n/a | n/a | +| 2 (backend move) | **Required** in CI | **Required** in CI | **Required manual** on GPU4 (smoke) | n/a | n/a | +| 3 (FE move) | Backend still green | Backend still green | Optional | **Required** in CI | **Manual on GPU4 only** (FE CI Playwright deferred to Phase 4) | +| 4 (promote pending) | Streaming tests must add coverage | Required | **Required manual** on GPU4 | Required | **Required manual** on GPU4 → re-enable FE-CI Playwright at end | +| 5 (DR-1 / DR-2) | Required | Prompt-shim tests required | **Required manual** prompt-flow on GPU4 | Required | **Required manual** preset-prompt-generation spec on GPU4 | +| 6a-6f | All CI green | All CI green | Optional during 6b/6c deploy dry runs | All CI green | Required against staging in 6c | +| 7 (archive) | n/a | n/a | n/a | n/a | n/a | + +--- + +## File-by-file migration map + +### PRODUCT files (move into `apps/dreamverse/`) + +| Source path | LOC | Target path | Notes | +|---|---:|---|---| +| `Dreamverse/server/main.py` | 148 | `apps/dreamverse/server/main.py` | FastAPI app composition; imports change to `from fastvideo.entrypoints.streaming import build_app` etc. | +| `Dreamverse/server/config.py` | 303 | `apps/dreamverse/server/config.py` | Dreamverse-specific env/model registry/prompt paths. | +| `Dreamverse/server/video_generation.py` | 578 | `apps/dreamverse/server/video_generation.py` | LTX-2 product-specific worker wrapper + continuation conditioning. | +| `Dreamverse/server/session/controller.py` | 1948 | `apps/dreamverse/server/session/controller.py` | Per-WebSocket session controller — Dreamverse protocol/UI flow. | +| `Dreamverse/server/session/messages.py` | 21 | `apps/dreamverse/server/session/messages.py` | Queue DTOs; promote only if generic. | +| `Dreamverse/server/routes/presets.py` | 234 | `apps/dreamverse/server/routes/presets.py` | Curated preset HTTP routes, product content. | +| `Dreamverse/server/tests/test_config.py` | 154 | `apps/dreamverse/server/tests/test_config.py` | Product config tests. | +| `Dreamverse/server/tests/test_entrypoints.py` | 99 | `apps/dreamverse/server/tests/test_entrypoints.py` | Product CLI tests. | +| `Dreamverse/server/tests/test_realtime_stress.py` | 947 | `apps/dreamverse/server/tests/test_realtime_stress.py` | E2E websocket stress, product-specific. | +| `Dreamverse/server/tests/test_session_logging.py` | 1278 | `apps/dreamverse/server/tests/test_session_logging.py` | Product session flow tests. | +| `Dreamverse/server/tests/conftest.py` | 14 | `apps/dreamverse/server/tests/conftest.py` | Test path bootstrap. | +| `Dreamverse/server/prompts/*.md` | — | `apps/dreamverse/server/prompts/*.md` | System prompt content: 4 files plus README. | +| `Dreamverse/apps/web/**` | — | `apps/dreamverse/web/**` | Entire Next.js frontend. | +| `Dreamverse/AGENTS.md`, `arch.md`, `design.md`, `gpu-pool.{svg,drawio}` | — | `apps/dreamverse/` | Product-level docs and diagrams. | +| `Dreamverse/scripts/install_native_ffmpeg.sh`, `smoke_local.sh` | — | `apps/dreamverse/scripts/` | Product launch/setup scripts. | +| `Dreamverse/serve_configs/streaming_demo.yaml` | — | `apps/dreamverse/serve_configs/streaming_demo.yaml` | Product deployment config; also copy to `examples/serving/streaming_demo.yaml`. | +| `Dreamverse/.agents/skills/launch-demo/scripts/*.sh` | — | `apps/dreamverse/scripts/launch/*.sh` | Demo launch helpers. | + +### GENERIC-MERGED files (delete from Dreamverse copy; import public FastVideo) + +| Source path | Already on FastVideo public at | Action | +|---|---|---| +| `Dreamverse/server/gpu_pool.py` (1053 LOC) | `fastvideo.entrypoints.streaming.gpu_pool` | Delete; `apps/dreamverse/server/main.py` imports public API. | +| `Dreamverse/server/prompt_enhancer.py` (1933 LOC) | `fastvideo.entrypoints.streaming.prompt.*` (partial) | **DEFER deletion to Phase 5.** Public `PromptEnhancer` does not yet expose Dreamverse-side methods (`resolve_rewrite_model` per [`controller.py:203`](file:///home/william5lin/Dreamverse/server/session/controller.py#L203), `get_prompt_config` / `save_prompt_config` per [`routes/presets.py:95`](file:///home/william5lin/Dreamverse/server/routes/presets.py#L95)). Carry the file into `apps/dreamverse/server/prompt_enhancer.py` during Phase 2 unmodified. Phase 5 implements DR-1 compat shim + retires the fork. | +| `Dreamverse/server/av_streaming.py` (434 LOC) | `fastvideo.entrypoints.streaming.stream` | Delete. | +| `Dreamverse/server/worker_ipc.py` (161 LOC) | `fastvideo.entrypoints.streaming.protocol` | Delete. | +| `Dreamverse/server/mock_server.py` (1207 LOC) | `fastvideo.entrypoints.streaming.mock_server` | Delete. | +| `Dreamverse/server/session_init_image.py` (103 LOC) | `fastvideo.entrypoints.streaming.session_init_image` | Delete. | +| `Dreamverse/server/session_logger.py` (44 LOC) | `fastvideo.entrypoints.streaming.session_logger` | Delete. | +| `Dreamverse/server/tests/test_gpu_pool.py` (126 LOC) | covered by FastVideo tests | Delete. | +| `Dreamverse/server/tests/test_mock_server.py` (360 LOC) | covered by FastVideo tests | Delete. | +| `Dreamverse/server/tests/test_prompt_enhancer.py` (1176 LOC) | covered by FastVideo tests | Delete, or keep product-specific subset only. | +| `Dreamverse/server/tests/test_session_init_image.py` (74 LOC) | covered by FastVideo tests | Delete. | + +Generic-merged ownership is consistent with the existing upstreaming map in +[`streaming-server.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L14-L31). + +### GENERIC-PENDING files (schedule for promotion) + +| Source path | LOC | Target path on FastVideo public | +|---|---:|---| +| `Dreamverse/server/runtime.py` | 21 | `fastvideo.entrypoints.streaming.runtime` or absorb into server state. | +| `Dreamverse/server/prompt_safety.py` | 222 | `fastvideo.entrypoints.streaming.prompt.safety` by extending existing safety module. | +| `Dreamverse/server/rewrite_prompt_payload.py` | 98 | `fastvideo.entrypoints.streaming.prompt.rewrite` by extending existing rewrite module. | +| `Dreamverse/server/utils.py` | 21 | absorb into appropriate streaming/API utility. | +| `Dreamverse/server/routes/health.py` | 101 | extend `fastvideo.entrypoints.streaming.server.build_app` to expose `/healthz`, `/readyz`, `/status`. | +| `Dreamverse/server/benchmarks/benchmark_*.py` | ~900 total | `fastvideo/tests/benchmarks/` or `benchmarks/` at FastVideo root. | +| `Dreamverse/server/tests/test_health_endpoints.py` | 163 | follow health route merge. | +| `Dreamverse/server/tests/test_prompt_safety.py` | 51 | follow prompt safety merge. | +| `Dreamverse/server/tests/test_rewrite_prompt_payload.py` | 89 | follow rewrite merge. | +| `Dreamverse/server/tests/test_benchmark_*.py` | ~470 total | follow benchmark merge. | + +The health route gap is tracked as open item #1 +([open-threads](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L69-L99)). + +### DELETE files (no longer needed) + +| Source path | LOC | Why | +|---|---:|---| +| `Dreamverse/server/server_entry.py` | 15 | CLI shim no longer needed in monorepo. | +| `Dreamverse/server/routes/__init__.py` | 1 | Empty package marker. | +| `Dreamverse/server/session/__init__.py` | 5 | Empty package marker. | +| `Dreamverse/server/tests/test_batching.py` | 149 | Obsolete ORCA batching protocol. | + +--- + +## Phased migration plan + +### Phase 0 — Land #1288 (in flight) + +**Purpose:** Ensure the generic FastVideo backend substrate is available before +moving Dreamverse product code into the monorepo. + +**Files / scope:** + +- `fastvideo/api/` typed results and event classes. +- `fastvideo/entrypoints/video_generator.py` async generation path. +- `fastvideo/entrypoints/streaming/` generic streaming server, GPU pool, + prompt, safety, rewrite, mock server, router, and tests. +- LTX-2 SR runtime and NVFP4 wiring included in #1288. +- Contract tests for Dreamverse and Dynamo shapes. + +**Source:** #1288 is open and mergeable on `will/ltx2_sr_port` +([roadmap](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/pr-roadmap.md#L38-L42)). + +**Steps:** + +1. Wait for #1288 to merge to `origin/main`. +2. Fetch main and verify the content is present. +3. Update memory-dir state after merge per runbook + ([runbook](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/runbook.md#L51-L70)). +4. Start Phase 1 from updated `main` or a new branch based on it. + +**Verification gate:** + +- #1288 merge commit exists on `origin/main`. +- `fastvideo.api.VideoEvent` and `VideoGenerator.generate_async` are importable. +- Existing API/contract/NVFP4/LTX-2 smoke baseline remains green; May 2 baseline + is documented in + [`state.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/state.md#L142-L149). + +**Rollback:** + +- If #1288 does not merge, stop. Do not move Dreamverse product code. +- If #1288 merges and regresses, revert or fix #1288 before Phase 1. +- Do not create `apps/dreamverse/` until generic backend import targets are + stable on the branch used for migration. + +### Phase 1 — Add `apps/` skeleton + +**Purpose:** Establish monorepo tooling and empty product directories before a +mass move. This should be a small PR. + +**Files to add:** + +- `apps/dreamverse/README.md` +- `apps/dreamverse/server/pyproject.toml` +- `apps/dreamverse/server/tests/.gitkeep` +- `apps/dreamverse/web/.gitkeep` +- `apps/dreamverse/prompts/.gitkeep` +- `apps/dreamverse/serve_configs/.gitkeep` +- `apps/dreamverse/scripts/.gitkeep` +- `docs/contributing/dreamverse-development.md` + +**Files to modify:** + +- `pyproject.toml` +- `uv.lock` — **regenerated** when adding the workspace member; commit alongside. +- `.pre-commit-config.yaml` +- `.gitignore` +- `mkdocs.yml`, if `docs/contributing/dreamverse-development.md` is added to + the Developer Guide nav. Current nav lives at + [`mkdocs.yml`](file:///home/william5lin/FastVideo/mkdocs.yml#L169-L180). +- `fastvideo/entrypoints/streaming/gpu_pool.py` for D-12-A docstring caveat. + +**Steps:** + +1. Create the directory skeleton. +2. Add the server `pyproject.toml` shown in the tooling section. +3. Add `[tool.uv.workspace] members = ["apps/dreamverse/server"]` to root + `pyproject.toml`. +4. Add `apps*` to root setuptools and wheel excludes. +5. Add scoped Dreamverse web ignores + product-asset unignores to `.gitignore`. +6. Add `apps/dreamverse/web/.*` to pre-commit global exclude. +7. Add `docs/contributing/dreamverse-development.md` with local dev commands: + backend `uv run --locked --package dreamverse-server --extra test pytest ...`; + frontend `cd apps/dreamverse/web && pnpm install && pnpm run build`. +8. Run `uv lock` to regenerate `uv.lock` with the new workspace member; commit + the lock change in the same PR. +9. Land D-12-A docstring caveat: mark `GpuPool` experimental/server-internal + until `run_async()` lands. This is tracked in + [`open-threads.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L294-L308). + +**Verification gate:** + +- `uv sync --locked --package dreamverse-server --extra test` succeeds (proves + `uv.lock` is in sync with the workspace declaration). +- `pre-commit run --files pyproject.toml uv.lock .pre-commit-config.yaml .gitignore apps/dreamverse/server/pyproject.toml docs/contributing/dreamverse-development.md` succeeds. +- `uv run --with build python -m build --sdist --wheel .` still excludes + `apps*` from the FastVideo wheel/sdist (verify with `unzip -l dist/*.whl | grep apps` returns nothing). +- `lsp_diagnostics` is clean for changed Python files. +- No root `package.json` exists. +- `git check-ignore -v apps/dreamverse/web/public/k2.png` reports nothing + (asset unignore works) — only verifiable in Phase 3 once the file exists, + but the rule lands in Phase 1. + +**Rollback:** + +- Revert the Phase 1 PR. +- No product files have moved yet, so rollback does not affect Dreamverse repo. +- If only uv workspace sync fails, revert the workspace stanza and keep the + empty directory PR blocked until the pyproject shape is fixed. + +### Phase 2 — Move PRODUCT files (server) + +**Purpose:** Move the Dreamverse product backend into the monorepo while +rewiring imports to public FastVideo surfaces. + +**Files to move:** + +- `Dreamverse/server/main.py` → `apps/dreamverse/server/main.py` +- `Dreamverse/server/config.py` → `apps/dreamverse/server/config.py` +- `Dreamverse/server/video_generation.py` → `apps/dreamverse/server/video_generation.py` +- `Dreamverse/server/session/controller.py` → `apps/dreamverse/server/session/controller.py` +- `Dreamverse/server/session/messages.py` → `apps/dreamverse/server/session/messages.py` +- `Dreamverse/server/routes/presets.py` → `apps/dreamverse/server/routes/presets.py` +- `Dreamverse/server/tests/test_config.py` → `apps/dreamverse/server/tests/test_config.py` +- `Dreamverse/server/tests/test_entrypoints.py` → `apps/dreamverse/server/tests/test_entrypoints.py` +- `Dreamverse/server/tests/test_realtime_stress.py` → `apps/dreamverse/server/tests/test_realtime_stress.py` +- `Dreamverse/server/tests/test_session_logging.py` → `apps/dreamverse/server/tests/test_session_logging.py` +- `Dreamverse/server/tests/conftest.py` → `apps/dreamverse/server/tests/conftest.py` + +**Files NOT moved as PRODUCT (deleted in Phase 2 because public substitute exists):** + +- `Dreamverse/server/gpu_pool.py` — replaced by `fastvideo.entrypoints.streaming.gpu_pool` +- `Dreamverse/server/av_streaming.py` — replaced by `fastvideo.entrypoints.streaming.stream` +- `Dreamverse/server/worker_ipc.py` — replaced by `fastvideo.entrypoints.streaming.protocol` +- `Dreamverse/server/mock_server.py` — replaced by `fastvideo.entrypoints.streaming.mock_server` +- `Dreamverse/server/session_init_image.py` — replaced by `fastvideo.entrypoints.streaming.session_init_image` +- `Dreamverse/server/session_logger.py` — replaced by `fastvideo.entrypoints.streaming.session_logger` + +**Files MOVED AS-IS into `apps/dreamverse/server/` despite being technically generic — these are GENERIC-PENDING that haven't landed publicly yet, and Dreamverse won't boot without them:** + +| Source path | Target | Reason carried into Phase 2 | +|---|---|---| +| `Dreamverse/server/runtime.py` (21) | `apps/dreamverse/server/runtime.py` | [`main.py:19`](file:///home/william5lin/Dreamverse/server/main.py#L19) and `controller.py` import `runtime` for the runtime singletons; promote to public in Phase 4. | +| `Dreamverse/server/utils.py` (21) | `apps/dreamverse/server/utils.py` | Used by `controller.py` for timestamps + segment-cap helpers; absorb into public utility in Phase 4. | +| `Dreamverse/server/prompt_safety.py` (222) | `apps/dreamverse/server/prompt_safety.py` | Imported by `main.py` startup; promote to `fastvideo.entrypoints.streaming.prompt.safety` in Phase 4. | +| `Dreamverse/server/rewrite_prompt_payload.py` (98) | `apps/dreamverse/server/rewrite_prompt_payload.py` | Imported by `routes/presets.py` and `controller.py`; promote to `fastvideo.entrypoints.streaming.prompt.rewrite` in Phase 4. | +| `Dreamverse/server/routes/health.py` (101) | `apps/dreamverse/server/routes/health.py` | Mounted at startup by `main.py`; needed for FE Playwright tests. Promote to `fastvideo.entrypoints.streaming.server.build_app` in Phase 4. | +| `Dreamverse/server/prompt_enhancer.py` (1933) | `apps/dreamverse/server/prompt_enhancer.py` | DR-1 fork; replaced in Phase 5 with public + thin compat shim. | + +These are **explicit shims** — Phase 4 is responsible for their promotion to public surfaces and corresponding deletion from `apps/dreamverse/server/`. + +**Required import rewrites in moved PRODUCT files:** + +- `from .gpu_pool import GpuPool` → `from fastvideo.entrypoints.streaming.gpu_pool import GpuPool` +- `from .av_streaming import ...` → `from fastvideo.entrypoints.streaming.stream import ...` +- `from .worker_ipc import ...` → `from fastvideo.entrypoints.streaming.protocol import ...` +- `from .mock_server import ...` → `from fastvideo.entrypoints.streaming.mock_server import ...` +- `from .session_init_image import ...` → `from fastvideo.entrypoints.streaming.session_init_image import ...` +- `from .session_logger import ...` → `from fastvideo.entrypoints.streaming.session_logger import ...` +- Typed request/result/state imports → `fastvideo.api` +- `runtime`, `utils`, `prompt_safety`, `rewrite_prompt_payload`, `routes.health`, `prompt_enhancer` — kept relative (`from .runtime import ...`) inside `apps/dreamverse/server/` until Phase 4/5 promotes them. + +**Required path rewrites in moved files:** + +- [`config.py:13`](file:///home/william5lin/Dreamverse/server/config.py#L13): `_APP_ROOT / "apps" / "web"` → `_APP_ROOT / "web"` (since `_APP_ROOT` will resolve to `apps/dreamverse/` in the new layout). +- [`apps/web/next.config.ts:11`](file:///home/william5lin/Dreamverse/apps/web/next.config.ts#L11): `outputFileTracingRoot: path.resolve(__dirname, "../..")` → `path.resolve(__dirname, "../../..")` (one extra `..` since the FE is one level deeper in the monorepo). +- [`playwright.config.ts:39`](file:///home/william5lin/Dreamverse/apps/web/playwright.config.ts#L39): `command: "npm run dev"` → `command: "pnpm run dev"` (matches Phase 1 tooling decision). +- Any hardcoded `../FastVideo` paths in scripts/configs → make repo-root-relative since they now share a repo. + +**Steps:** + +1. **Cross-repo move with explicit history disposition.** `git mv` does NOT preserve history across repositories. Choose one: + - **(Recommended) Fresh import**: `git mv` from `Dreamverse/server/...` → `apps/dreamverse/server/...` within the new monorepo as a single commit; original Dreamverse repo retains full history; mention the move source SHA in the commit body. + - **(Alternative) Subtree merge**: use `git subtree add --prefix=apps/dreamverse ` to import history. Heavier; usually unnecessary if Dreamverse repo is being archived (history stays accessible there). + - The decision **must be documented in the Phase 2 PR body**, including the SHA of the originating Dreamverse commit being imported. +2. Rewire imports to public streaming and API modules per the rewrite list above. +3. Apply path rewrites listed above. +4. Add the import contract test from the Target architecture section. +5. Keep `routes/presets.py` product-local. +6. Keep `session/controller.py` product-local. +7. Verify D-8 `ltx2_image_crf` flow after migration: + - Source item is tracked in + [`open-threads.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L51-L68). + - The known concern is that `ltx2_image_crf` may still be silently dropped + unless it reaches `request.stage_overrides.refine.image_crf`. + - Add a Dreamverse-shape contract test pinning the field once the trace is verified. + +**Verification gate:** + +- **CI / unit / integration**: + `uv run --locked --package dreamverse-server --extra test pytest apps/dreamverse/server/tests/ -m 'not gpu' -q` + succeeds (skips GPU-marked tests; runs in `ci-dreamverse-backend.yml`). +- Import contract test (`test_import_contract.py`) passes. +- `lsp_diagnostics` is clean for changed Python files. +- `pre-commit run --files apps/dreamverse/server/*.py apps/dreamverse/server/session/controller.py apps/dreamverse/server/session/messages.py apps/dreamverse/server/routes/presets.py apps/dreamverse/server/tests/*.py` succeeds. +- D-8 trace is documented in the PR body and either passes or opens a blocking + fix item. +- No imports from internal `fastvideo.pipelines`, `fastvideo.models`, + `fastvideo.layers`, or `fastvideo.worker` remain under + `apps/dreamverse/server/`. +- **Manual QA on GPU4** (required, not optional): + - Reclaim GPU4 (kill running dreamverse-server PID 2453227). + - `CUDA_VISIBLE_DEVICES=4 uv run --locked --package dreamverse-server fastvideo serve --config apps/dreamverse/serve_configs/streaming_demo.yaml --host 0.0.0.0 --port 8009` boots cleanly. + - `curl -s http://localhost:8009/health` returns 200. + - `pytest apps/dreamverse/server/tests/ -m gpu -q` against the live deploy passes + (this exercises `test_realtime_stress.py` and `test_session_logging.py` + with a real GPU + real model weights). + - Capture output in PR description. + - Cleanup: `pkill -f 'fastvideo serve --config'` and restart the canonical + Dreamverse-side server. + +**Rollback:** + +- Revert the Phase 2 PR. +- Dreamverse source repo remains canonical until Phase 7, so no production + rollback is needed. +- If only one public import is missing, add a temporary product-local shim only + if it is explicitly deleted in Phase 4 or Phase 5. +- If the GPU4 manual QA reveals a real-service bug, the Phase 2 PR is + blocked; fix the bug and re-run the GPU4 smoke before merging. + +### Phase 3 — Move FE + content + +**Purpose:** Move the Dreamverse frontend, prompts, serve configs, launch +scripts, and product docs after backend tests are green. + +**Files to move:** + +- `Dreamverse/apps/web/**` → `apps/dreamverse/web/**` +- `Dreamverse/server/prompts/*.md` → `apps/dreamverse/server/prompts/*.md` +- `Dreamverse/AGENTS.md` → `apps/dreamverse/AGENTS.md` +- `Dreamverse/arch.md` → `apps/dreamverse/arch.md` +- `Dreamverse/design.md` → `apps/dreamverse/design.md` +- `Dreamverse/gpu-pool.svg` → `apps/dreamverse/gpu-pool.svg` +- `Dreamverse/gpu-pool.drawio` → `apps/dreamverse/gpu-pool.drawio` +- `Dreamverse/scripts/install_native_ffmpeg.sh` → `apps/dreamverse/scripts/install_native_ffmpeg.sh` +- `Dreamverse/scripts/smoke_local.sh` → `apps/dreamverse/scripts/smoke_local.sh` +- `Dreamverse/serve_configs/streaming_demo.yaml` → `apps/dreamverse/serve_configs/streaming_demo.yaml` +- `Dreamverse/serve_configs/streaming_demo.yaml` → `examples/serving/streaming_demo.yaml` as a public-safe copy. +- `Dreamverse/.agents/skills/launch-demo/scripts/*.sh` → `apps/dreamverse/scripts/launch/*.sh` + +**CI additions:** + +- Add `.github/workflows/ci-dreamverse-frontend.yml`. +- Ensure `.gitignore` covers scoped Next.js and Playwright artifacts. + +**Steps:** + +1. Move frontend tree without restructuring package internals. +2. Update relative paths in frontend scripts/configs from old repo root to + `apps/dreamverse/` or FastVideo root as appropriate. +3. Move product prompts and docs. +4. Copy `streaming_demo.yaml` to `examples/serving/streaming_demo.yaml` with + public-safe comments. The missing example config is tracked in + [`integration-review.md`](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/integration-review.md#L259-L276). +5. Add frontend workflow. +6. Add docs/contributing link if not already added in Phase 1. + +**Verification gate:** + +- `cd apps/dreamverse/web && pnpm install --frozen-lockfile` succeeds. +- `cd apps/dreamverse/web && pnpm run build` succeeds. +- `cd apps/dreamverse/web && pnpm run test --if-present` succeeds (Vitest + tsc). +- **Frontend CI Playwright is intentionally DEFERRED to Phase 4** — at Phase 3 + the public `build_app` does not yet expose `/healthz`+`/readyz`+`/status`+ + `/prompt-system-config`+`/curated-presets`. The `ci-dreamverse-frontend.yml` + scaffold from Phase 1 keeps Playwright steps commented out until Phase 4 + reactivates them. No PR note required. +- **Manual GPU4 Playwright smoke** (recommended): on this dev node, run + `apps/dreamverse/web/e2e/frontend-shell.spec.ts` against the GPU4-deployed + backend from Phase 2 manual QA + a `pnpm run dev` frontend at port 5274 + to confirm shell hydration. `backend-health.spec.ts` and + `preset-prompt-generation.spec.ts` will fail until Phase 4 — that is + expected; document as deferred. +- `uv run --locked --package dreamverse-server --extra test pytest apps/dreamverse/server/tests/ -m 'not gpu' -q` + still succeeds. +- `examples/serving/streaming_demo.yaml` parses with FastVideo serve config. + +**Rollback:** + +- Revert the Phase 3 PR. +- If frontend CI is the only failing component, revert only the frontend move + and keep Phase 2 backend in monorepo. +- If the public example config is wrong, revert the example copy separately; + product deployment config can remain under `apps/dreamverse/serve_configs/`. + +### Phase 4 — Promote GENERIC-PENDING + close drift items + +**Purpose:** Finish generic backend promotions that should not live in +Dreamverse product code. + +**Files likely to touch:** + +`fastvideo/entrypoints/streaming/{server.py,health.py,gpu_pool.py,session_store.py,blob_store.py,prompt/safety.py,prompt/rewrite.py}`, +`fastvideo/tests/entrypoints/streaming/`, `apps/dreamverse/server/{main.py,config.py}`. + +**Work items:** + +1. Add `/healthz`, `/readyz`, `/status` to generic `build_app` ([contract](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L232-L259), [open item](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L69-L99)). +2. Add `GpuPool.run_async() -> AsyncIterator[VideoEvent]`; keep sync `run()` as collector ([D-12](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L47-L116), [D-12-B](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L310-L325)). +3. Decide and document `video_position_offset_sec` semantics ([VPO](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L119-L144)). +4. Define SessionStore/BlobStore lifecycle policy ([SBS](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L277-L292)). +5. Promote or absorb `runtime.py`, `utils.py`, prompt safety, rewrite payload, + and health tests according to the generic-pending table. +6. Update Dreamverse server imports to consume the new generic public modules. + +**Verification gate:** + +- FastVideo streaming tests pass (existing CI suite). +- Dreamverse backend tests pass (`-m 'not gpu'` in CI; `-m gpu` on GPU4 manual). +- Contract tests for `/healthz`, `/readyz`, `/status` cover both healthy and + not-ready states (added in this phase to `fastvideo/tests/entrypoints/streaming/`). +- `run_async()` cancellation test proves client disconnect can stop mid-work. +- VPO decision is documented in code comments/tests. +- SessionStore/BlobStore lifecycle policy has tests for replacement cleanup and + disconnect expiry if implemented. +- **Frontend CI Playwright RE-ENABLED** at end of this phase: uncomment the + Playwright steps in `ci-dreamverse-frontend.yml` (deferred since Phase 1) + AND change CI to either (a) run against the mock backend + `fastvideo.entrypoints.streaming.mock_server`, or (b) require a deployed + staging URL via env var. +- **Manual GPU4 full E2E**: deploy `fastvideo serve` on GPU4 with the new + health routes, run all 3 Playwright specs (`backend-health`, `frontend-shell`, + `preset-prompt-generation`) against it. All 3 must pass — this is the + re-baseline after Phase 3's deferral. Capture output in PR. + +**Rollback:** + +- Each generic-pending promotion should be a focused PR. +- If a generic promotion regresses FastVideo, revert that PR and keep the + product-local code temporarily under `apps/dreamverse/server/`. +- If health route compatibility is wrong, revert route additions but keep + tests skipped only with an explicit tracking issue. + +### Phase 5 — Replace prompt enhancer fork (DR-1) + `cerebras_ifm` decision (DR-2) + +**Purpose:** Remove the 1933-LOC Dreamverse prompt enhancer fork and keep only +product-specific prompt orchestration. + +**Files likely to touch:** `apps/dreamverse/server/prompting/_internal_compat.py` (new), `main.py`, `config.py`, `session/controller.py`, product prompt tests, and only if DR-2 picks public provider: `fastvideo/entrypoints/streaming/prompt/providers/` plus `fastvideo/api/schema.py`. + +**DR-1 migration shape:** create `_internal_compat.py` over public `PromptEnhancer`, preserve product response shapes, keep locked segment metadata / rollout IDs / lenient JSON fallback product-local, then delete the full fork ([DR-1](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L174-L206)). + +**DR-2 decision:** pick public `cerebras_ifm` provider + Literal, or Dreamverse-side custom provider registered with public enhancer. Default: Dreamverse-side unless another user needs IFM ([DR-2](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L211-L229)). + +**Verification gate:** + +- Product prompt tests pass through `_internal_compat.py`. +- Public prompt enhancer tests remain green. +- `cerebras`, `groq`, and selected `cerebras_ifm` path have unit tests or + mocked-provider tests. +- Playwright preset prompt generation test passes against live BE+FE, matching + the existing Dreamverse-side verification gate + ([open-threads](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L495-L498)). + +**Rollback:** + +- Keep the deleted fork recoverable in git history. +- If product prompt behavior regresses, revert Phase 5 only and restore the + product-local fork temporarily. +- Do not roll back Phase 2 or Phase 3 for a prompt-specific regression. + +### Phase 6 — Switch CI/release + +**Purpose:** Make monorepo CI/deploy authoritative after code migration. **Splits into 6 substeps to avoid coupling unrelated changes.** + +**Files:** `ci-dreamverse-{backend,frontend}.yml` (already added in Phase 1/3), new `deploy-dreamverse-{backend,frontend}.yml`, `apps/dreamverse/README.md`, `docs/contributing/dreamverse-development.md`, README links. + +#### Phase 6a — CI path-filter proof +- Land a no-op test PR that touches only `apps/dreamverse/web/README.md` and verify ONLY `ci-dreamverse-frontend.yml` runs (not Buildkite full suite, not `ci-precommit` if `paths-ignore` applied). +- Land a no-op test PR that touches only `apps/dreamverse/server/README.md` and verify ONLY `ci-dreamverse-backend.yml` + `ci-precommit` run. +- Land a no-op test PR that touches `fastvideo/api/__init__.py` (a no-op comment) and verify BOTH FastVideo CI AND `ci-dreamverse-backend.yml` run (because the path filter includes `fastvideo/api/**`). +- Document the verification PR URLs in the Phase 6a merge commit. + +#### Phase 6b — Backend deploy dry run +- Add `deploy-dreamverse-backend.yml` with a manual dispatch trigger only (no `push` trigger yet). +- Run a manual deploy to a **staging** environment (not production). +- Verify the deployed backend serves `/healthz`, `/readyz`, `/status`, `/v1/stream` correctly using public Dreamverse FE pointing at the staging URL. + +#### Phase 6c — Frontend deploy dry run +- Add `deploy-dreamverse-frontend.yml` (Vercel or Docker depending on team choice) with manual dispatch only. +- Deploy to a Vercel preview / staging Docker. +- Verify product Playwright e2e against the staging FE+BE pair. + +#### Phase 6d — Staging cutover +- Switch the staging environment to use ONLY the monorepo deploys. +- Disable the Dreamverse repo's deploy workflows for staging. +- Run for at least 24-48 hours to observe stability. + +#### Phase 6e — Old-repo CI freeze +- Disable Dreamverse repo CI workflows (set them to manual-only or remove). +- Update Dreamverse repo's README to point to the FastVideo monorepo for new contributions. +- DO NOT archive the repo yet — that's Phase 7. + +#### Phase 6f — Production cutover +- Switch production deploy to use monorepo workflows. +- Add `push: branches: [main]` triggers to deploy workflows now that they're proven. +- Update DNS / load-balancer / external link integrations. +- Monitor for 1 week before Phase 7. + +**Verification gate:** Each substep has its own gate; do not proceed to next substep without the prior one passing. Final gate after 6f: monorepo production deploys are stable for 1 week with no Dreamverse-repo dependency in the production path. + +**Rollback:** Each substep is independently revertible. Rolling back Phase 6f means switching deploy back to Dreamverse repo (which Phase 6e left functional but disabled). Rolling back Phase 6e means re-enabling Dreamverse CI. The 6a-6c substeps create no production dependency and can be reverted by deleting workflow files. + +### Phase 7 — Archive Dreamverse repo + +**Purpose:** Finish consolidation only after monorepo product CI/deploy are proven. + +**Steps:** commit Dreamverse README redirect to `hao-ai-lab/FastVideo/apps/dreamverse/`, tag/branch final Dreamverse state for rollback, disable old CI, archive repo, update external links, and update this memory dir. + +**Verification gate:** backend and frontend monorepo deploys are live; product docs and Dreamverse README redirect point to FastVideo; no production job depends on the old repo. + +**Rollback:** unarchive Dreamverse, restore backup branch/tag, disable monorepo deploy, and point external links back until fixed. + +--- + +## Risk register + +| Risk | Severity | Likelihood | Mitigation | Owner | +|---|---|---:|---|---| +| Build-system complexity from adding a product app to a Python ML repo | High | Medium | Use uv workspace for Python only; keep frontend standalone; exclude `apps*` from wheel. | FastVideo build owner | +| Python contributors needing Node | Medium | Medium | No root `package.json`; frontend CI and commands live under `apps/dreamverse/web/`. | Frontend owner | +| CI cost increase | Medium | Medium | Add Dreamverse path-specific workflows; add `paths-ignore` to broad workflows; rely on Buildkite monorepo diff watch lists. | CI owner | +| FastVideo PyPI release accidentally includes Dreamverse app | High | Low | Add `apps*` to `[tool.setuptools.packages.find]` and `[tool.wheel]` excludes; verify built wheel contents. | Release owner | +| Release cadence coupling | Medium | Medium | Keep FastVideo PyPI version release unchanged; Dreamverse uses Docker/Vercel deploy from app paths. | Release owner | +| Frontend tooling drift | Medium | Medium | Pin pnpm lockfile in `apps/dreamverse/web/`; no root JS workspace. | Frontend owner | +| Security surface enlargement | Medium | Medium | Product routes stay in `apps/dreamverse/server`; only generic health/streaming routes go into FastVideo. | Backend owner | +| Product-specific API leakage into `fastvideo.*` | High | Medium | Enforce import/module boundary; keep curated presets and prompt UX product-local. | Architecture owner | +| Migration regression | High | Medium | Phase gates; backend before frontend; can stop after any phase with Dreamverse repo still usable until Phase 7. | Migration owner | +| Lost git history on moved files | High | High | **`git mv` does not preserve history across repositories.** Choose between (a) fresh import (no history; record source SHA in PR body; original history stays in archived Dreamverse repo) or (b) `git subtree add` / `git filter-repo` import (preserves history but heavier). Document the choice in Phase 2 PR. | Migration owner | +| Migrated public assets ignored by root `.gitignore` | High | High | Root ignores `*.png`/`*.jpg`/`*.mp4`/`*.gif`; Phase 1 must add `!apps/dreamverse/web/public/**` etc. unignore rules. Verify with `git check-ignore -v` before Phase 3 commits. | Migration owner | +| CORS open to `*` in product server | Medium | Medium | [`Dreamverse/server/main.py:99`](file:///home/william5lin/Dreamverse/server/main.py#L99) sets `allow_origins=["*"]`. After move, decide: (a) keep dev-only and document; (b) tighten to known FE origins; (c) deployment-firewall. Document in `apps/dreamverse/server/README.md`. | Backend owner | +| Write endpoints (`/prompt-system-config`, `/curated-presets/append`) | Medium | Medium | [`routes/presets.py:106`](file:///home/william5lin/Dreamverse/server/routes/presets.py#L106) exposes write routes. Decide auth/rate-limit policy; either gate behind devtools origin OR add auth before production cutover. | Backend owner | +| Prompt enhancer behavior regression | High | Medium | Build DR-1 shim with product tests before deleting fork; keep rollback path to restore fork. | Prompt owner | +| `cerebras_ifm` production gap | Medium | Medium | Decide DR-2 before Phase 5 merge; default Dreamverse-side provider unless public user exists. | Product owner | +| Health route compatibility gap | High | Medium | Land `/healthz`, `/readyz`, `/status` in generic build_app with tests before FE switches to FastVideo flavor. | Streaming owner | +| `video_position_offset_sec` ambiguity | Medium | Medium | Decide VPO semantics in Phase 4; encode in tests. | Audio/runtime owner | +| Session/blob memory leak | Medium | Medium | Define lifecycle policy before high-traffic deploy; add TTL/replacement cleanup tests. | Runtime owner | +| Existing FastVideo CI false positives on frontend-only changes | Medium | Medium | Apply path filters; verify with a frontend-only test PR. | CI owner | +| Dreamverse repo archive too early | High | Low | Archive only after monorepo staging deploy and production deploy are proven. | Release owner | + +--- + +## Verification gates + +| Phase | Required checks | Stop condition | +|---|---|---| +| 0 | #1288 merged; public typed events and `generate_async` import; baseline API/contract tests green. | #1288 missing or regressed. | +| 1 | uv workspace sync; pre-commit on changed root/app files; wheel excludes `apps*`; no root `package.json`. | FastVideo package build includes app code or uv workspace cannot sync. | +| 2 | Dreamverse backend tests green; import contract green; D-8 trace complete; lsp/pre-commit clean. | Product server imports private FastVideo modules or D-8 is silently dropped. | +| 3 | Frontend install/build/test/Playwright green; backend tests still green; public example config parses. | Frontend cannot build from `apps/dreamverse/web/`. | +| 4 | Streaming tests green; health routes covered; `run_async()` cancellation covered; VPO/SBS decisions encoded. | Generic backend regression or unresolved route contract. | +| 5 | Prompt shim tests green; selected IFM path works; product Playwright preset prompt flow green. | Prompt behavior differs from product expectations. | +| 6 | Backend-only and frontend-only CI PRs trigger correct workflows; staging deploy succeeds. | Existing FastVideo CI is noisy for frontend-only changes or deploy fails. | +| 7 | Monorepo production deploy proven; old repo redirect committed; no jobs depend on old repo. | Any production dependency still points to Dreamverse repo. | + +Global verification requirements: + +- `lsp_diagnostics` clean on changed Python files. +- `pre-commit run --files ` for non-excluded files. +- Relevant tests pass before each phase merges. +- Do not run GPU-heavy full suite for frontend-only changes. +- Capture command output in PR descriptions. + +--- + +## Rollback strategy + +| Phase | Rollback path | Data loss risk | Notes | +|---|---|---:|---| +| 0 | Do not proceed until #1288 is fixed or reverted. | Low | No Dreamverse files moved. | +| 1 | Revert skeleton/tooling PR. | Low | Empty dirs and root tooling only. | +| 2 | Revert backend move PR; Dreamverse repo remains source of truth. | Low | Move commits do NOT preserve cross-repo history (`git mv` only preserves within a single repo). Original Dreamverse history stays in the archived Dreamverse repo. The Phase 2 PR body must record the originating Dreamverse SHA(s) for traceability. | +| 3 | Revert frontend/content move PR; keep backend if green. | Low | Product assets still exist in Dreamverse repo. | +| 4 | Revert individual generic promotion PR; temporarily keep product-local shim. | Medium | Avoid reverting unrelated generic backend changes. | +| 5 | Restore prompt fork from previous commit; keep shim behind flag if useful. | Medium | Prompt behavior rollback only. | +| 6 | Disable monorepo deploy workflows; re-enable Dreamverse repo CI/deploy. | Low | Code can remain in monorepo while deploy routes old repo. | +| 7 | Unarchive Dreamverse repo; restore from backup branch; turn off monorepo deploy. | Medium | Requires external link rollback. | + +Rollback principles: + +- Never archive Dreamverse before monorepo deploy is proven. +- Keep each phase as a separate PR or commit group. +- Keep generic backend promotions independent from product moves. +- Keep `apps*` wheel exclusion in place even if product phases are reverted. +- If frontend migration fails, do not roll back generic backend work. + +--- + +## Open questions / decisions needed + +| Decision | Needed by | Default / note | Source | +|---|---|---|---| +| `cerebras_ifm` provider path | Phase 5 | Dreamverse-side custom provider unless another public user exists | [DR-2](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L211-L229) | +| `video_position_offset_sec` semantics | Phase 4 | Decide persistent vs per-segment; decision is overdue | [VPO](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/integration-review.md#L361-L364) | +| SessionStore/BlobStore lifecycle | Phase 4 | Define TTL/LRU/hard max/blob cleanup/disconnect expiry | [SBS](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L277-L292) | +| Health route response shapes | Phase 4 | Match Dreamverse `/healthz`, `/readyz`, `/status` before FE switch | [health routes](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L69-L99) | +| Benchmark destination | Phase 4 | Pick `fastvideo/tests/benchmarks/` or root `benchmarks/` before moving files | migration table above | +| Standalone upsampler CLI | Deferred | Defer or port to FastVideo CLI | [upsampler](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/integration-review.md#L239-L258) | +| Layerwise offload utility | Deferred | Defer unless a deployment requires it | [offload](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/integration-review.md#L224-L238) | + +--- + +## Action items + +| # | Pri | Effort | Phase | Owner | Action | +|---:|---|---|---|---|---| +| 1 | P0 | L | 0 | FastVideo backend | Land #1288 and update memory state. | +| 2 | P0 | S | 1 | Build | Add uv workspace, `apps*` excludes, web pre-commit exclude, scoped `.gitignore`. | +| 3 | P0 | S | 1 | Docs | Add `docs/contributing/dreamverse-development.md` and optional `mkdocs.yml` nav. | +| 4 | P1 | M | 2 | Product backend | Move backend files and add import contract test. | +| 5 | P1 | S | 2 | Runtime | Trace D-8 `ltx2_image_crf` and add/adjust test. | +| 6 | P1 | M | 3 | Frontend | Move Next.js frontend and land frontend CI. | +| 7 | P2 | S | 3 | Examples | Copy `streaming_demo.yaml` to `examples/serving/streaming_demo.yaml`. | +| 8 | P1 | M-L | 4 | Streaming | Add `/healthz`, `/readyz`, `/status` to `build_app` with tests. | +| 9 | P2 | M | 4 | Streaming | Add `GpuPool.run_async()` and cancellation propagation. | +| 10 | P2 | S | 4 | Audio/runtime | Decide VPO semantics and encode in tests. | +| 11 | P2 | M | 4 | Runtime | Define SessionStore/BlobStore lifecycle policy. | +| 12 | P1 | M | 5 | Prompt | Replace prompt enhancer fork with `_internal_compat.py` shim. | +| 13 | P1 | S-M | 5 | Product | Decide and implement `cerebras_ifm` path. | +| 14 | P1 | M | 6 | CI | Prove split backend/frontend CI and no FastVideo CI noise on frontend-only changes. | +| 15 | P1 | M | 6 | Release | Add product deploy workflows from monorepo paths. | +| 16 | P2 | S | 7 | Release | Archive Dreamverse repo after redirect commit and monorepo deploy proof. | +| 17 | P3 | S-M | Deferred | CLI | Decide standalone upsampler CLI. | +| 18 | P3 | M | Deferred | Performance | Defer layerwise offload until deployment evidence exists. | + +--- + +## Cross-references + +- Repo paths: [README](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/README.md#L73-L80). +- Typed API and schema: [design core](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L24-L43), [schema surface](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L45-L72). +- Continuation state: [cross-repo mapping](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L108-L146). +- Streaming routes: [route contract](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L232-L259). +- GpuPool and router decisions: [D-12](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L47-L116), [D-15](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L118-L201). +- Open work and verification: [open threads](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L15-L45), [gates](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L480-L498). +- Runbook: [verification commands](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/runbook.md#L79-L124). +- Previous tradeoff analysis: [integration review](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/integration-review.md#L371-L563). + +--- + +## Comparison to `integration-review.md` (now superseded for recommendation) + +`integration-review.md` recommended constrained Option D: generic backend in +FastVideo, Dreamverse product in a separate repo +([recommendation](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/integration-review.md#L543-L563)). + +The user chose Option B+ instead. + +Changed recommendation: Dreamverse product moves into `apps/dreamverse/`; generic backend stays at `fastvideo.entrypoints.streaming.*`; Dreamverse server does not become `fastvideo.entrypoints.dreamverse.*`; frontend remains standalone with no root `package.json`; FastVideo PyPI excludes `apps*`. + +Still authoritative from `integration-review.md`: drift audit findings, OSS comparison material not contradicted by Option B+, health route gap, DR-1/DR-2 prompt work, D-8 `ltx2_image_crf`, VPO/SBS decisions, missing public streaming demo config, and the decision to defer layerwise offload / standalone upsampler CLI unless product need is proven. + +Operationally, this plan is the execution document. Use it for Phase 1 onward. diff --git a/.agents/memory/dreamverse-integration/integration-review.md b/.agents/memory/dreamverse-integration/integration-review.md new file mode 100644 index 0000000000..504f7a7178 --- /dev/null +++ b/.agents/memory/dreamverse-integration/integration-review.md @@ -0,0 +1,888 @@ +# Integration Review — Drift Audit + Path Forward + +> # ⚠️ DEPRECATED — superseded by [integration-plan.md](integration-plan.md) +> +> This document recommended **Option D** (Dreamverse stays a separate repo; +> generic backend merges into FastVideo). On 2026-05-05 the team chose +> **Option B+** instead (Dreamverse FE + product server move into FastVideo +> as `apps/dreamverse/`; generic backend stays at +> `fastvideo.entrypoints.streaming.*` per Option D's principle). +> See [decisions-log.md D-18](decisions-log.md#d-18) for the strategy +> reversal rationale and [integration-plan.md](integration-plan.md) for the +> executable migration plan. +> +> **What's still authoritative in this file:** +> - **Part 1 — Drift audit** (the 17-row drift summary table). The drift +> findings remain valid; the migration plan in `integration-plan.md` +> folds them into specific phases. +> - **OSS precedent citations** (vLLM, BentoML, Ray Serve, TGI+ChatUI, +> Transformers.js, ComfyUI, AUTOMATIC1111). Reused in `integration-plan.md`. +> +> **What's superseded:** +> - **Part 2 — Recommendation (Option D)**. Replaced by Option B+ in the +> new plan. Read `integration-plan.md` for the current decision. +> - **Part 3 — Action items**. Replaced by the phased migration plan. +> +> Kept in tree for historical reference and audit trail. Do not delete. + +**Last updated:** 2026-05-05 (deprecated header added). + +**Scope:** FastVideo public `will/ltx2_sr_port` at the requested audit +anchor `b36bdbc9`; Dreamverse `will/integrate-public-fastvideo` at +`ec8ef92`; FastVideo-internal `will/rebase-nbv` as read-only comparison. + +**Memory-dir context:** the current integration memory snapshot tracks the +same public mega-PR lineage as `will/ltx2_sr_port`, with PRs #1257, +#1258, #1284, and #1286 already merged, #1287 closed, and #1288 open as +the consolidated landing vehicle for LTX-2 SR runtime, NVFP4, +`generate_async`, Dynamo contract, and memory-dir cleanup. Source: +[memory index](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/README.md#L8-L19) +and [D-17](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L19-L45). + +**Bottom line:** Zero core typed API drift — typed construction, typed +continuation state, NVFP4 wiring, and Dynamo-facing async events are either +already public or in #1288. **Real drift remains on the realtime-runtime +contract surface (`/healthz` / `/readyz` / `/status` routes per +[cross-repo-surfaces.md](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L74-L88)) +and on operational/product edges**: stale Dreamverse docs/scripts, a +1933-LOC Dreamverse prompt-enhancer fork, two unresolved per-session +fields (`ltx2_image_crf` D-8, `video_position_offset_sec` VPO), one +missing example config, and two internal-only utilities whose product +relevance is not yet proven. + +--- + +## Part 1 — Drift audit + +### Methodology + +1. **Compared three repositories and branches.** + - FastVideo public: `/home/william5lin/FastVideo`, branch + `will/ltx2_sr_port`. + - Dreamverse: `/home/william5lin/Dreamverse`, branch + `will/integrate-public-fastvideo`. + - FastVideo-internal: `/home/william5lin/FastVideo-internal`, branch + `will/rebase-nbv`. + - Canonical repo paths are listed in the integration memory index: + [repo paths](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/README.md#L72-L79). + +2. **Scoped the audit to the ultimate integration goal.** + - Dreamverse should depend on public `fastvideo`, not + `FastVideo-internal`. + - FastVideo should own the reusable backend subset that Dreamverse + currently needs from internal: streaming runtime, GPU pool, router, + prompt enhancer, NVFP4, continuation state, and typed generation. + - Dynamo should consume FastVideo through typed public Python APIs, not + through private modules. + - The three Dreamverse surfaces are documented as pipeline construction, + realtime runtime, and continuation state: + [cross-repo surfaces](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L13-L20). + +3. **Separated intentional refactor from drift.** + - A path rename is not drift if the public branch contains the same + responsibility under the typed design. + - A deleted file is not drift if the public design intentionally + consolidated it. + - A private alias is not drift if the public schema exposes a typed + replacement with contract tests. + - This matches the typed-public-boundary rule in + [design.md](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L24-L43). + +4. **Used memory docs for rationale and worktree files for concrete proof.** + - API schema and public exports: + [schema](file:///home/william5lin/FastVideo/fastvideo/api/schema.py#L68-L85), + [api exports](file:///home/william5lin/FastVideo/fastvideo/api/__init__.py#L49-L109). + - Streaming server current routes: + [build_app](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/server.py#L88-L160). + - Dreamverse dependency state: + [pyproject server extra](file:///home/william5lin/Dreamverse/pyproject.toml#L17-L22), + [uv lock editable source](file:///home/william5lin/Dreamverse/uv.lock#L716-L722). + - Contract tests: + [Dreamverse shape](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dreamverse_shape.py#L1-L26), + [Dynamo shape](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dynamo_shape.py#L1-L19), + [generate_async](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_generate_async.py#L1-L7). + +5. **Did not treat product-only Dreamverse behavior as FastVideo drift.** + - Dreamverse keeps a local product server and Next.js UI today: + [README baseline](file:///home/william5lin/Dreamverse/README.md#L5-L16). + - Product-only routes, curated presets, devtools, and frontend-specific + behavior belong in Dreamverse unless a second non-Dreamverse consumer + needs them. + +6. **Risk scale used below.** + - **P0:** blocks Dreamverse from running without FastVideo-internal. + - **P1:** blocks clean `BE_FLAVOR=fastvideo` or Dynamo/public API use. + - **P2:** reproducibility or maintenance drag. + - **P3:** optional parity or future memory/perf improvement. + +### Findings: zero core typed API drift + +The public branch is aligned with the goal on the **core typed API +surface** (construction, request, continuation state, async events). +The table below lists items that look like drift only if compared by +path name or legacy field name. They are intentional public refactors +or already guarded by tests. **Note:** the realtime-runtime _contract_ +surface (FE-required health routes) is a separate matter — see "real +drift items" §4 below. + +| Investigated item | Drift? | Evidence | Conclusion | +|---|---:|---|---| +| Dreamverse surface 1: pipeline construction | No | Dreamverse migrated from flat kwargs to typed `GeneratorConfig` at `d80c2a8`; mapping documented in [cross-repo surfaces](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L22-L47). | Stable public surface exists. | +| Dreamverse surface 2: realtime runtime | No on architecture; some route work remains | Runtime migration target is public `streaming/`, not internal `realtime/`: [streaming upstream](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L14-L31). | Rename/refactor is intentional. | +| Dreamverse surface 3: continuation state | No | Public typed `ContinuationState` plus LTX-2 state mapping are documented in [cross-repo surfaces](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L108-L146). | Public state is a superset of Dreamverse's data carrier. | +| Internal `fastvideo/entrypoints/realtime/` | No | Public design chooses parallel `fastvideo/entrypoints/streaming/`: [layout decision](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L55-L60), [current build_app](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/server.py#L88-L160). | Intentional rename plus typed-config rewrite. | +| Internal `configs/sample/` presets | No | Public PR 4 intentionally deleted `configs/sample/` and moved defaults to per-family presets plus `fastvideo/api/sampling_param.py`: [design](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L194-L205), [PR roadmap](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/pr-roadmap.md#L21-L29). | Intentional consolidation. | +| LTX-2 pipeline presets | No | Public target is model-owned named presets and per-family colocation: [design](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L175-L205). | Public layout matches design. | +| Internal `use_fp4_linear` flag | No | Public typed quant carrier is `engine.quantization.transformer_quant`; schema field exists in [schema](file:///home/william5lin/FastVideo/fastvideo/api/schema.py#L68-L85), compat resolves it in [compat.py](file:///home/william5lin/FastVideo/fastvideo/api/compat.py#L267-L279). | Replaced by typed NVFP4 surface. | +| Public-only `transformer_quant` field | No | Public `FastVideoArgs` pins typed quant to `dit_config.quant_config`: [fastvideo_args](file:///home/william5lin/FastVideo/fastvideo/fastvideo_args.py#L220-L228), [apply logic](file:///home/william5lin/FastVideo/fastvideo/fastvideo_args.py#L260-L279). | Public superset, not drift. | +| Internal `config_model_path` | No | Public typed home is `generator.pipeline.components.config_root`: [design mapping](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L261-L269), [compat mapping](file:///home/william5lin/FastVideo/fastvideo/api/compat.py#L295-L299). | Alias is covered. | +| Internal flat video request fields | No | Public `GenerationRequest` nests `inputs`, `sampling`, `runtime`, `output`, `state`, `extensions`: [schema](file:///home/william5lin/FastVideo/fastvideo/api/schema.py#L193-L204). Internal legacy fields live in internal protocol at [protocol.py](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/openai/protocol.py#L64-L82). | Intentional request refactor. | +| Dreamverse typed init kwargs | No | Contract test asserts current Dreamverse load kwargs all land on typed fields, not `experimental`: [test_dreamverse_shape](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dreamverse_shape.py#L44-L135). | Guard in place. | +| Dreamverse request path | No | Contract test asserts request fields round-trip through typed `GenerationRequest`: [test_dreamverse_shape](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dreamverse_shape.py#L153-L197). | Guard in place. | +| Dynamo native backend shape | No | FastVideo's only obligation is stable typed Python API: [cross-repo contract](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L188-L210). | Dynamo should stay out of FastVideo. | +| `generate_async` event API | No | API exists in [video_generator](file:///home/william5lin/FastVideo/fastvideo/entrypoints/video_generator.py#L264-L332), event types exist in [results.py](file:///home/william5lin/FastVideo/fastvideo/api/results.py#L109-L164). | #1288 covers the async contract. | +| Dynamo request mapping | No | Authoritative source is the contract test [test_dynamo_shape](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dynamo_shape.py#L90-L175) which asserts `req.prompt`, `req.sampling.{height,width,num_frames,fps,num_inference_steps,guidance_scale,seed,negative_prompt}`, and `req.inputs.{image_path,video_path}` against the actual nested [`GenerationRequest` schema](file:///home/william5lin/FastVideo/fastvideo/api/schema.py#L193-L204). The `streaming-server.md` Dynamo mapping table mis-cites a `prompt -> sampling.prompt` path that no longer exists; the test is correct, the doc is stale and tracked for refresh. | Guard in place; companion doc needs minor refresh. | +| Public API exports | No | `VideoEvent`, `VideoResult`, and typed schema classes are exported from [fastvideo.api](file:///home/william5lin/FastVideo/fastvideo/api/__init__.py#L49-L109). | Integration imports resolve. | +| FastVideo-internal FP4/NVFP4 paths | No | Public NVFP4 files and roles are documented in [quantization](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/quantization.md#L24-L35); actual `NVFP4Config` documents lazy FlashInfer and public naming in [nvfp4_config.py](file:///home/william5lin/FastVideo/fastvideo/layers/quantization/nvfp4_config.py#L1-L19). | Public is typed superset. | +| AbsMaxFP8 refactor | No for Dreamverse | Public quant registry includes `AbsMaxFP8` and `NVFP4`: [quantization init](file:///home/william5lin/FastVideo/fastvideo/layers/quantization/__init__.py#L1-L8). AbsMaxFP8 failure is tracked as separate tech debt: [open threads](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L100-L117). | Not Dreamverse blocker. | +| Internal realtime API regression test | No | Public contract tests replace it: [Dreamverse contract](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dreamverse_shape.py#L1-L26), [Dynamo contract](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dynamo_shape.py#L1-L19), [generate_async tests](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_generate_async.py#L91-L230). | Better scoped guards exist. | +| Dreamverse dependency declaration | No | `server` extra declares `fastvideo>=0.1.7`: [pyproject](file:///home/william5lin/Dreamverse/pyproject.toml#L17-L22). Dev lock resolves editable public `../FastVideo`: [uv.lock](file:///home/william5lin/Dreamverse/uv.lock#L716-L722), [package source](file:///home/william5lin/Dreamverse/uv.lock#L777-L780). | Dependency is already switched in metadata/lock. | + +#### Core conclusion for the zero-typed-drift section + +The public typed API no longer needs to mirror `FastVideo-internal` file +paths. The correct test is whether Dreamverse and Dynamo can express their +needs through public typed objects and public entrypoints. On that test, +the **typed core** is covered (construction, request, continuation, +async events). The **runtime contract** still has health-route gaps — +see real drift §4. On the **typed core**: + +- `GeneratorConfig` and `GenerationRequest` cover construction and calls: + [schema surface](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L45-L72). +- `ServeConfig.streaming` covers the server envelope: + [schema](file:///home/william5lin/FastVideo/fastvideo/api/schema.py#L244-L279). +- `generate_async` covers streaming, OpenAI, and Dynamo on one substrate: + [video_generator](file:///home/william5lin/FastVideo/fastvideo/entrypoints/video_generator.py#L264-L332). +- Contract tests now encode the cross-repo shapes: + [Dreamverse](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dreamverse_shape.py#L70-L214), + [Dynamo](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dynamo_shape.py#L170-L331), + [async events](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_generate_async.py#L91-L273). + +### Findings: real drift items requiring action + +#### 1. Dreamverse README and bootstrap script still point at FastVideo-internal + +- **Priority:** P0 for a clean public-dependency story. +- **Effort:** Small. +- **Owner:** Dreamverse repo. +- **Evidence:** Dreamverse metadata already points at public FastVideo: + [pyproject](file:///home/william5lin/Dreamverse/pyproject.toml#L17-L22), + [uv source](file:///home/william5lin/Dreamverse/pyproject.toml#L54-L61), + [uv.lock](file:///home/william5lin/Dreamverse/uv.lock#L716-L722). +- **Drift:** README still tells users that `uv` resolves from + `../FastVideo-internal` and that bootstrap expects `../FastVideo-internal`: + [README](file:///home/william5lin/Dreamverse/README.md#L76-L109). +- **Drift:** bootstrap script still defaults to cloning the private repo and + verifying imports from that clone: + [script defaults](file:///home/william5lin/Dreamverse/.agents/skills/bootstrap-fastvideo-private-fork/scripts/bootstrap_fastvideo_private.sh#L7-L11), + [script clone flow](file:///home/william5lin/Dreamverse/.agents/skills/bootstrap-fastvideo-private-fork/scripts/bootstrap_fastvideo_private.sh#L33-L63), + [script import assertion](file:///home/william5lin/Dreamverse/.agents/skills/bootstrap-fastvideo-private-fork/scripts/bootstrap_fastvideo_private.sh#L66-L88). +- **Action:** Replace private-fork bootstrap with public FastVideo bootstrap + or delete the bootstrap once PyPI publication is the default path. +- **Do not overreach:** no FastVideo code change required. + +#### 2. Dreamverse carries a 1933-line prompt-enhancer fork + +- **Priority:** P1. +- **Effort:** Medium. +- **Owner:** Dreamverse repo, after public prompt enhancer is available. +- **Evidence:** Dreamverse local fork starts at + [server/prompt_enhancer.py](file:///home/william5lin/Dreamverse/server/prompt_enhancer.py#L1-L80). +- **Public replacement:** FastVideo now has provider-agnostic + `PromptEnhancer` with `enhance`, `auto_extend`, `rewrite`, and + `register_provider`: + [public enhancer](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/prompt/enhancer.py#L66-L142). +- **Provider extension point:** custom providers implement `LLMProvider`: + [provider protocol](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/prompt/providers/base.py#L63-L75). +- **Tracking:** DR-1 in open threads already defines the compat-shim shape: + [DR-1](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L174-L206). +- **Action:** Replace the fork with a small Dreamverse shim that adapts + public `LLMResponse` to Dreamverse's product response objects and keeps + only product-only extras. +- **Do not overreach:** do not merge Dreamverse's full prompt product layer + into FastVideo unless a second consumer needs the same semantics. + +#### 3. `cerebras_ifm` provider is unresolved + +- **Priority:** P1 if Dreamverse needs IFM in production; P2 otherwise. +- **Effort:** Small decision plus small/medium implementation. +- **Owner:** Team decision; implementation either Dreamverse-side or public. +- **Public state:** `PromptEnhancerConfig.provider` is currently + `Literal["cerebras", "groq"]`: + [schema](file:///home/william5lin/FastVideo/fastvideo/api/schema.py#L229-L235). +- **Design note:** public Literal excludes `cerebras_ifm` today: + [streaming-server D-3](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L61-L100). +- **Tracking:** DR-2 already frames the public-vs-Dreamverse decision: + [DR-2](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L211-L229). +- **Recommended default:** implement IFM as a Dreamverse-side custom provider + registered through `enhancer.register_provider(...)` unless there is a + non-Dreamverse public user. + +#### 4. `/healthz`, `/readyz`, and `/status` are not in public `build_app` + +- **Priority:** P1 for `BE_FLAVOR=fastvideo` frontend compatibility. +- **Effort:** Medium/Large because route shapes need tests. +- **Owner:** FastVideo public. +- **Public current state:** `build_app` exposes `GET /health` and + `WS /v1/stream`: + [server.py](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/server.py#L126-L160). +- **Dreamverse expected state:** Dreamverse exposes `GET /healthz`, + `GET /readyz`, and `GET /status`: + [routes/health.py](file:///home/william5lin/Dreamverse/server/routes/health.py#L34-L79). +- **Tracking:** open item #1 documents route ownership and files likely to + touch: + [open threads](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L69-L99). +- **Design note:** `/curated-presets`, `/prompt-system-config`, and devtools + stay Dreamverse-side, with feature detection: + [streaming route contract](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L232-L259). + +#### 5. `fastvideo/models/layerwise_offload.py` exists only internally + +- **Priority:** P3 unless memory-tight Dreamverse deployments require it. +- **Effort:** Medium if adopted; low if documented as deferred. +- **Owner:** FastVideo public only if a concrete deployment needs it. +- **Internal evidence:** internal file defines async layerwise CPU offload + manager with pinned CPU memory and prefetch stream: + [layerwise_offload.py](file:///home/william5lin/FastVideo-internal/fastvideo/models/layerwise_offload.py#L1-L20), + [prefetch path](file:///home/william5lin/FastVideo-internal/fastvideo/models/layerwise_offload.py#L127-L180). +- **Public state:** no equivalent public file was identified in this audit. +- **Action:** defer unless Dreamverse or another public deployment hits a + memory ceiling that cannot be handled by existing offload knobs. +- **Decision rule:** if adopted, port as a generic offload utility with + tests; do not make it Dreamverse-specific. + +#### 6. Standalone LTX-2 upsampler CLI exists only internally + +- **Priority:** P2 for reproducibility; P3 for product runtime. +- **Effort:** Small/Medium after scope decision. +- **Owner:** FastVideo public if standalone upsampling is a supported user + workflow. +- **Internal utility:** `upscale_video_file(...)` reads an existing video, + prepares frame count/resolution, loads VAE + upsampler, and writes an mp4: + [upsample.py](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/upsample.py#L120-L180), + [write tail](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/upsample.py#L181-L202). +- **Internal CLI:** `fastvideo upsample` wrapper exists internally: + [cli/upsample.py](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/cli/upsample.py#L15-L35), + [CLI args](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/cli/upsample.py#L48-L130). +- **Public related functionality:** LTX-2 SR refine stage covers the + in-pipeline latent upsample/refine path: + [ltx2_refine.py](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/stages/ltx2_refine.py#L1-L22), + [upsample stage](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/stages/ltx2_refine.py#L116-L180). +- **Action:** decide whether standalone file-to-file upsampling is a public + CLI promise or whether the SR refine stage is sufficient. + +#### 7. Reproducible streaming demo config lives only in Dreamverse + +- **Priority:** P2. +- **Effort:** Small. +- **Owner:** FastVideo public. +- **Evidence:** canonical demo config currently lives at + [Dreamverse/serve_configs/streaming_demo.yaml](file:///home/william5lin/Dreamverse/serve_configs/streaming_demo.yaml#L1-L12). +- **Config content:** it documents LTX-2 distilled model, one GPU, + no offload, compile settings, NVFP4, refine overrides, default request, + and streaming settings: + [generator block](file:///home/william5lin/Dreamverse/serve_configs/streaming_demo.yaml#L31-L87), + [streaming block](file:///home/william5lin/Dreamverse/serve_configs/streaming_demo.yaml#L108-L149). +- **Memory pointer:** design.md already treats this as the canonical + example: + [design YAML example](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L235-L239). +- **Action:** copy/adapt it into + `examples/serving/streaming_demo.yaml` with public-safe comments. + +#### 8. LTX-2 stage equivalence is a verification gap, not proven drift + +- **Priority:** P2. +- **Effort:** Medium if parity checks are added; small if only manual audit. +- **Owner:** FastVideo public. +- **Public state:** model-specific LTX-2 stages are colocated under + `fastvideo/pipelines/basic/ltx2/stages/`, consistent with the target + layout in [design.md](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/design.md#L175-L205). +- **Example public stage:** `ltx2_refine.py` explicitly says it is a + public-side port of the internal stage and describes the three-stage SR + flow: + [ltx2_refine.py](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/stages/ltx2_refine.py#L1-L22). +- **Action:** verify behavior for the six internal `ltx2_*` stage files + against public colocated stages. If a mismatch is found, file it as a + real drift item with a failing parity test. + +### Findings: deferred / accepted residual + +These items should not block the public-dependency transition. + +1. **StepVideo residual.** + - Dreamverse's model registry is LTX-2/LTX-2.3 only: + [Dreamverse config](file:///home/william5lin/Dreamverse/server/config.py#L28-L45). + - Internal local tests even stub StepVideo modules to keep LTX registry + tests focused: + [test_ltx2_registry.py](file:///home/william5lin/FastVideo-internal/tests/local_tests/test_ltx2_registry.py#L38-L61). + - Conclusion: accepted low-priority deferral unless Dreamverse adds a + StepVideo model. + +2. **Internal debug-only `FastVideoArgs` fields.** + - Internal debug fields exist around `FastVideoArgs` and stage/model sums: + [internal grep source](file:///home/william5lin/FastVideo-internal/fastvideo/fastvideo_args.py#L200-L203). + - They are debug-only and not a public user-facing integration surface. + - Conclusion: low-priority; do not add to public schema unless a debug + workflow requires them. + +3. **Private request aliases.** + - Public request schema is nested and strict: + [GenerationRequest](file:///home/william5lin/FastVideo/fastvideo/api/schema.py#L193-L204). + - Legacy OpenAI flat fields are compatibility input, not the canonical + public API: + [internal protocol](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/openai/protocol.py#L64-L82). + - Conclusion: no action beyond current compat tests. + +4. **`experimental["pipeline_config"]` escape hatch.** + - Dreamverse currently uses an explicit in-memory quant config because + typed `transformer_quant: "NVFP4"` does not expose `layer_profile`: + [quantization](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/quantization.md#L86-L97). + - Open thread #4 tracks `layer_profile`: + [open threads](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L244-L260). + - Conclusion: defer broader typed carrier design; add `layer_profile` + first if Dreamverse needs base/refine profile selection. + +5. **Router sticky routing and active-active semantics.** + - Public router intentionally ships active-passive first and defers + sticky/weighted routing: + [D-15](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L118-L155). + - Follow-ups are tracked: + [D-15 action items](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L175-L201). + - Conclusion: not drift; defer until load-balancing needs are real. + +6. **AbsMaxFP8 failure.** + - Pre-existing and not introduced by NVFP4: + [state](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/state.md#L154-L159), + [quantization](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/quantization.md#L202-L214). + - Conclusion: fix separately; not a Dreamverse public-dependency blocker. + +### Drift summary table + +| # | Item | Priority | Effort | Status | Tracked where | Next action | +|---:|---|---|---|---|---|---| +| 1 | Dreamverse README still names `../FastVideo-internal` | P0 | S | Real drift | [README lines](file:///home/william5lin/Dreamverse/README.md#L76-L109) | Update docs to public FastVideo / PyPI path. | +| 2 | Dreamverse private bootstrap clones internal repo | P0 | S | Real drift | [bootstrap script](file:///home/william5lin/Dreamverse/.agents/skills/bootstrap-fastvideo-private-fork/scripts/bootstrap_fastvideo_private.sh#L7-L11) | Replace or delete private bootstrap. | +| 3 | Dreamverse `prompt_enhancer.py` fork | P1 | M | Real drift | [DR-1](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L174-L206) | Build compat shim over public enhancer. | +| 4 | `cerebras_ifm` provider path | P1/P2 | S-M | Real drift / decision | [DR-2](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L211-L229) | Choose public provider vs Dreamverse custom provider. | +| 5 | Health route mismatch | P1 | M-L | Real drift | [open item #1](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L69-L99) | Add `/healthz`, `/readyz`, `/status` to public build_app. | +| 6 | Missing public streaming demo config | P2 | S | Real drift | [Dreamverse config](file:///home/william5lin/Dreamverse/serve_configs/streaming_demo.yaml#L1-L12) | Add `examples/serving/streaming_demo.yaml`. | +| 7 | Standalone upsampler CLI | P2/P3 | S-M | Real drift if standalone CLI is desired | [internal CLI](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/cli/upsample.py#L15-L35) | Decide CLI promise; port or defer. | +| 8 | Layerwise offload utility | P3 | M | Optional internal-only residual (no Dreamverse deployment requires it today) | [internal manager](file:///home/william5lin/FastVideo-internal/fastvideo/models/layerwise_offload.py#L15-L20) | Defer until memory-tight deployment needs it. | +| 9 | LTX-2 stage equivalence | P2 | S-M | Verification gap | [public refine stage](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/stages/ltx2_refine.py#L1-L22) | Add targeted parity audit/test if needed. | +| 10 | StepVideo | P3 | M | Accepted residual | [Dreamverse model registry](file:///home/william5lin/Dreamverse/server/config.py#L28-L45) | No action unless Dreamverse adds StepVideo. | +| 11 | Debug-only fields | P3 | S | Accepted residual | [internal args](file:///home/william5lin/FastVideo-internal/fastvideo/fastvideo_args.py#L200-L203) | Do not publicize unless needed. | +| 12 | `layer_profile` typed quant knob | P2 | M | Tracked gap | [open item #4](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L244-L260) | Add typed layer profile if Dreamverse drops escape hatch. | +| 13 | `ltx2_image_crf` per-segment field flow (D-8) | P1 | S | Open verification gap — Dreamverse still passes `ltx2_image_crf=0.0` per [Dreamverse video_generation.py](file:///home/william5lin/Dreamverse/server/video_generation.py#L420-L435); needs trace-through to confirm it lands on `request.stage_overrides.refine.image_crf` rather than being silently dropped | [D-8 in open-threads](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L52-L68) | 10-min trace + add a Dreamverse-shape contract test pinning the field. | +| 14 | `video_position_offset_sec` semantics (VPO) | P1 | S | Open decision — persistent-vs-per-segment ambiguity unresolved | [VPO in open-threads](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L120-L144) | Confirm semantics with audio team; document + add test. Decision deadline was "before PR 7.6 emits state" — that PR (7.6 / #1257) is now MERGED, so the decision is overdue. | +| 15 | `GpuPool` ABC docstring missing experimental caveat (D-12-A) | P3 | trivial | Tracked gap — `GpuPool` ABC at [gpu_pool.py:74-83](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/gpu_pool.py#L74-L83) lacks the "API may change post-PR-7.10; experimental / server-internal" caveat | [D-12-A](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L301-L313) | Edit docstring; trivial. | +| 16 | `GpuPool.run_async()` migration (D-12-B) | P2 | M | Tracked gap — `GpuPool.run() -> Any` should become `run_async() -> AsyncIterator[VideoEvent]` per D-12 / D-12-B | [D-12-B](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L317-L327) | Land alongside #1288 merge or in immediate follow-up. | +| 17 | `SessionStore` / `BlobStore` lifecycle policy (SBS) | P2 | M | Tracked gap — in-memory defaults have no eviction/TTL/blob-cleanup policy | [SBS](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L278-L294) | Streaming server design pass needed before high-traffic deployment. | +| 13 | Router sticky / active-active | P3 | M | Deferred | [D-15](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L175-L201) | Defer until reconnect/load evidence. | +| 14 | AbsMaxFP8 test failure | P2 | S | Separate tech debt | [state](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/state.md#L154-L159) | Fix outside Dreamverse migration. | +| 15 | Dynamo backend package | P1 | External | Not FastVideo drift | [Dynamo contract](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L188-L210) | Reopen Dynamo-side PR after public API lands. | + +--- + +## Part 2 — Integration path tradeoffs + +### The four options + +#### Option A — Status quo: Dreamverse stays separate and depends on `fastvideo` + +**Shape** + +- FastVideo remains the Python library and reusable backend runtime. +- Dreamverse remains the product repo with FastAPI product glue and Next.js + frontend. +- Dreamverse `server` extra depends on `fastvideo>=0.1.7`: + [pyproject](file:///home/william5lin/Dreamverse/pyproject.toml#L17-L22). +- Local development can keep using editable `../FastVideo` until PyPI + publication catches up: + [uv.lock](file:///home/william5lin/Dreamverse/uv.lock#L716-L722). + +**What it solves** + +- Directly satisfies "Dreamverse depends on public FastVideo". +- Keeps frontend release cadence independent. +- Keeps product-specific prompts, routes, and UI in the product repo. +- Minimizes FastVideo packaging and CI growth. + +**What it does not solve by itself** + +- Does not remove Dreamverse prompt-enhancer fork unless DR-1 is executed. +- Does not give Dreamverse FE compatibility with public `build_app` until + health routes migrate. +- Does not make Dreamverse server itself reusable as a public entrypoint. + +**Best fit** + +- Default for the next release if the goal is to stop using + FastVideo-internal quickly and safely. + +#### Option B — Dreamverse as a subfolder under FastVideo + +**Shape** + +- One repository: FastVideo contains `dreamverse/server/` and + `dreamverse/apps/web/`. +- Dreamverse can remain a separate package in the same repo, or FastVideo's + build can ignore Dreamverse by default. +- CI must understand Python library tests plus Next.js install/build/test. + +**What it solves** + +- Eliminates sibling-checkout drift. +- Makes cross-repo integration changes atomic. +- Easier for a single reviewer to see library and product changes together. + +**Costs** + +- Adds frontend dependency management to a Python ML library repo. +- Couples clone size, CI setup, issue tracking, and review load. +- Forces maintainers to decide whether product assets are included in source + distributions, wheels, docs, and release notes. + +**Best fit** + +- Only if Dreamverse becomes the primary FastVideo product surface and the + team accepts a product monorepo. + +#### Option C — Full merge into `fastvideo.entrypoints.dreamverse.*` + +**Shape** + +- Dreamverse backend becomes FastVideo code. +- Public import becomes something like + `from fastvideo.entrypoints.dreamverse import build_app`. +- CLI becomes `fastvideo dreamverse-serve --config dreamverse.yaml`. +- Frontend either ships as static assets in the package or as a frontend + extra. + +**What it solves** + +- One namespace and one release train for library plus product backend. +- No dependency boundary between Dreamverse server and FastVideo internals. +- Product route contract can be tested entirely inside FastVideo CI. + +**Costs** + +- Maximally expands FastVideo's public/security surface. +- Locks product experiments to FastVideo release cadence. +- Makes private prompt/provider/product assumptions look like framework API. +- Has weak precedent for a Python ML library plus Next.js product being merged + into the library namespace. + +**Best fit** + +- Only if Dreamverse is no longer a separate product and becomes the + canonical FastVideo UI/serving mode. + +#### Option D — Hybrid: backend merges, frontend stays separate + +**Shape** + +- Reusable backend components merge into public FastVideo. +- Frontend stays in a separate Dreamverse UI repo or Dreamverse product repo. +- The backend should be generic where possible: `fastvideo.entrypoints.streaming`, + not product-only names, unless product-only routes are intentionally + accepted as public API. +- This matches the current trajectory: streaming server, GPU pool, prompt + enhancer, safety/rewrite/session logging, router, NVFP4, and + `generate_async` are public-side work already tracked in the PR roadmap: + [pr-roadmap](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/pr-roadmap.md#L19-L42). + +**What it solves** + +- Removes FastVideo-internal dependency for reusable backend pieces. +- Keeps product frontend cadence independent. +- Gives non-Dreamverse users a streaming backend and typed API without + carrying the Dreamverse app. +- Gives Dynamo a stable library API while leaving Dynamo package code in + Dynamo: + [Dynamo contract](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L188-L210). + +**Costs** + +- Requires careful boundary discipline: generic streaming/server code in + FastVideo; product routes/prompts/presets in Dreamverse. +- Requires contract tests to prevent drift. +- Some Dreamverse compatibility routes may become public and need support. + +**Best fit** + +- Best long-term target if the team wants FastVideo to own serving/runtime + infrastructure while keeping Dreamverse as a separately evolving product. + +### Comparison matrix + +| Criterion | A. Separate dep | B. Subfolder monorepo | C. Full namespace merge | D. Hybrid backend merge | +|---|---|---|---|---| +| Alignment with stated goal | High: Dreamverse depends on public package | Medium: no external dep, but product becomes repo-local | Medium: dependency disappears by absorption | High: reusable backend in public, product separate | +| Time to remove `FastVideo-internal` | Fastest | Medium | Slowest | Medium-fast | +| Build complexity | Low | High: Python + Next.js in one repo | High: Python package plus static/frontend extras | Medium: Python backend only in FastVideo | +| Release cadence | Independent | Coupled clone; releases can still be separate but more friction | Fully coupled | Backend coupled to FastVideo, frontend independent | +| Security surface in FastVideo | Low | Medium/High | Highest | Medium | +| Contributor friction | Low for both repos | Higher for library contributors | Highest; product assumptions in library | Medium; clear backend boundary needed | +| Dependency management | Normal package pin | Workspace/monorepo tooling needed | FastVideo extras/static asset decisions needed | FastVideo extras for backend; FE out-of-tree | +| CI cost | Low/medium | High | High | Medium | +| Contract-test value | High; cross-repo contract tests are essential | Medium; same repo but still useful | Medium; less boundary pressure | High; generic backend vs product boundary | +| Precedent strength | Strong: library/server plus external UI patterns exist | Mixed | Weak for Python ML library + Next.js inside namespace | Strongest match: in-tree server/backend, external UI | +| Packaging risk | Low | Medium/high | High | Medium | +| Future Dynamo fit | Strong | Strong if API remains clean | Risky if product API bleeds in | Strong | +| Frontend iteration speed | Highest | Lower | Lowest | Highest | +| Risk of product-specific API leakage | Low | Medium | High | Medium; controllable with naming discipline | +| Reversibility | High | Medium | Low | Medium/high | + +### OSS precedents (with citations) + +| Pattern | Project | What it supports | Citation | +|---|---|---|---| +| Library plus in-tree server | vLLM | A Python ML library can ship an in-tree OpenAI-compatible server while clients remain external. | https://github.com/vllm-project/vllm/blob/bcf5cac9fb956788f649d1f5297b74c886a9d6d3/README.md#L64-L74 | +| Service packaging | BentoML | Packaging model + service + dependencies is supported, but CWD packaging creates discipline needs. | https://github.com/bentoml/BentoML/blob/32230a5276a8da8b23c4a06a9ec6272c1993451a/docs/source/build-with-bentoml/asgi.rst#L5-L18 | +| YAML-driven production serving | Ray Serve | Production updates should avoid in-place mutation; use new deployment/traffic switch. | https://docs.ray.io/en/latest/serve/advanced-guides/inplace-updates.html | +| Library/server plus external UI | TGI + ChatUI | Server can live with backend project while UI is separate. | https://github.com/huggingface/text-generation-inference/blob/b4adbf2f6e2e721280bd0ea5f91d70f7d033f5ed/docs/source/basic_tutorials/consuming_tgi.md#L182-L186 | +| Lean library plus examples elsewhere | Transformers.js | Library stays lean; demos/examples can live outside core. | https://github.com/huggingface/transformers.js/blob/f7487c737aa8cafbc106c9adf69dc9578c8f3fe0/README.md#L26-L34 | +| Product monorepo that later split frontend | ComfyUI | Product UI/server monorepo can hit release-cadence mismatch and split FE later. | https://github.com/comfyanonymous/ComfyUI/blob/fed8d5efa6b70d5b24c4c33cb643bfccc39d45b5/README.md#L131-L149 and https://github.com/Comfy-Org/ComfyUI_frontend/blob/60f789d58070a9d1d789b260f83c36d7293a39f0/README.md#L31-L60 | +| Tightly coupled UI/server product | AUTOMATIC1111 SD WebUI | Product repos can couple UI/server tightly, but security surface becomes product-sized. | https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/82a973c04367123ae98bd9abdf80d9eda9b910e2/webui.py#L48-L104 | + +#### Precedent synthesis + +- Strong precedents exist for a Python ML library shipping a server entrypoint. +- Strong precedents exist for keeping frontend/product UI out of the backend + library repo. +- The cited set does not contain a clean precedent for merging a Next.js + product into a Python ML library namespace. +- The most applicable pattern is **backend/server in the ML project, + product UI outside**. + +### Recommendation + +#### Recommend Option D, constrained: backend merges as generic FastVideo streaming; frontend stays separate + +Recommendation: follow **Option D** as the long-term architecture, but keep +the backend merge generic. In practice, this means continuing the current +public FastVideo path: + +- `fastvideo.entrypoints.streaming.*` owns reusable streaming runtime. +- `fastvideo.entrypoints.streaming.gpu_pool` owns generic GPU worker pools. +- `fastvideo.entrypoints.streaming.prompt.*` owns provider-agnostic prompt + operations. +- `fastvideo.entrypoints.streaming.router.*` owns FastVideo-aware routing. +- `fastvideo.api` owns typed construction, requests, results, events, and + continuation state. +- Dreamverse keeps product-only FE, curated presets, prompt UX, product + routes, and launch scripts. + +This is effectively the path already underway in PRs #1257, #1258, #1284, +#1286, and #1288: +[PR roadmap](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/pr-roadmap.md#L21-L42). + +#### Why not Option A as the final answer? + +Option A is the fastest near-term release posture and should be used as the +immediate migration posture. However, plain status quo is not enough for +the ultimate goal because reusable backend pieces still need to live in +public FastVideo so Dreamverse can stop reaching into internal code. That +work is already partly complete: + +- GPU pool: [D-12](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L47-L116). +- Prompt enhancer: [PR roadmap 7.7](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/pr-roadmap.md#L32-L35). +- Streaming auxiliaries: [PR roadmap 7.8](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/pr-roadmap.md#L35-L36). +- Router: [D-15](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L118-L155). +- `generate_async`: [streaming-server unlock PR](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L314-L345). + +So the practical answer is: + +- **Near term:** Option A operationally, after docs/scripts are fixed. +- **Architecture target:** Option D, with generic backend ownership in + FastVideo and product ownership in Dreamverse. + +#### Why not Option B? + +Option B makes cross-repo coordination easier but imports frontend build, +package, and CI complexity into FastVideo. That is unnecessary while a +normal package dependency plus contract tests can guard the integration. +FastVideo's current repo structure is a Python package with examples and +docs, not a product monorepo: +[codebase map](file:///home/william5lin/FastVideo/.agents/memory/codebase-map/README.md#L5-L75). + +#### Why not Option C? + +Option C makes the product backend a public FastVideo namespace. That is +only appropriate if the team wants to support Dreamverse as a first-class +FastVideo product surface. Today the known public obligations are generic: +typed requests, streaming server, GPU pool, prompt provider protocol, +router, NVFP4, and Dynamo event APIs. Product-only Dreamverse behavior does +not need to become framework API. + +#### Conditions that would change the recommendation + +Move from constrained D toward **C** only if all of these become true: + +1. Dreamverse is declared the canonical FastVideo serving product. +2. Product routes such as curated presets and prompt-system config are + accepted as public FastVideo API. +3. FastVideo maintainers accept the security and support surface. +4. Release cadence for product UX and FastVideo core is intentionally + coupled. +5. Frontend packaging/static asset strategy is explicitly owned by + FastVideo. + +Move from constrained D back toward **A** if any of these become true: + +1. Prompt enhancement, router, or GPU pool turn out to be Dreamverse-only. +2. No second user appears for the streaming backend outside Dreamverse. +3. FastVideo maintainers want to minimize serving surface and publish only + Python library APIs. +4. Dreamverse needs product changes faster than FastVideo can release. +5. Security review rejects in-tree serving/router responsibilities. + +### Migration sketch for the recommended path + +#### Phase 0 — Land the public backend stack + +- **Effort:** Large, already in flight. +- **Owner:** FastVideo public. +- **Files:** #1288 scope, especially `fastvideo/api/`, + `fastvideo/entrypoints/video_generator.py`, + `fastvideo/entrypoints/streaming/`, LTX-2 pipeline stages, NVFP4 files, + and contract tests. +- **Exit criteria:** #1288 merges; public `fastvideo.api.VideoEvent` and + `VideoGenerator.generate_async` are available: + [results.py](file:///home/william5lin/FastVideo/fastvideo/api/results.py#L109-L164), + [video_generator.py](file:///home/william5lin/FastVideo/fastvideo/entrypoints/video_generator.py#L264-L332). + +#### Phase 1 — Fix Dreamverse dependency docs and bootstrap + +- **Effort:** Small. +- **Owner:** Dreamverse. +- **Files:** + - [README.md](file:///home/william5lin/Dreamverse/README.md#L76-L109) + - [bootstrap script](file:///home/william5lin/Dreamverse/.agents/skills/bootstrap-fastvideo-private-fork/scripts/bootstrap_fastvideo_private.sh#L7-L11) + - [pyproject.toml](file:///home/william5lin/Dreamverse/pyproject.toml#L17-L22) + - [uv.lock](file:///home/william5lin/Dreamverse/uv.lock#L716-L722) +- **Exit criteria:** no user-facing docs or scripts mention + `FastVideo-internal` as the expected dependency path. + +#### Phase 2 — Add public health/readiness/status route compatibility + +- **Effort:** Medium/Large. +- **Owner:** FastVideo public. +- **Files likely to touch:** + - `fastvideo/entrypoints/streaming/server.py::build_app` + - new `fastvideo/entrypoints/streaming/health.py` + - tests under `fastvideo/tests/entrypoints/streaming/` +- **Source route shapes:** + [Dreamverse health routes](file:///home/william5lin/Dreamverse/server/routes/health.py#L34-L79). +- **Tracking:** [open item #1](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L69-L99). +- **Exit criteria:** Dreamverse FE can target public `build_app` for + `/healthz`, `/readyz`, `/status`, and `/v1/stream`; product-only routes + remain feature-detected. + +#### Phase 3 — Replace Dreamverse prompt enhancer fork + +- **Effort:** Medium. +- **Owner:** Dreamverse. +- **Files likely to touch:** + - new `Dreamverse/server/prompting/_internal_compat.py` + - `Dreamverse/server/runtime.py` + - `Dreamverse/server/main.py` + - `Dreamverse/server/prompt_enhancer.py` +- **Public API:** + [PromptEnhancer](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/prompt/enhancer.py#L66-L142), + [LLMProvider](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/prompt/providers/base.py#L63-L75). +- **Tracking:** [DR-1](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L174-L206). +- **Exit criteria:** Dreamverse no longer carries a full local fork for the + generic prompt operations public FastVideo already owns. + +#### Phase 4 — Decide and implement `cerebras_ifm` + +- **Effort:** Small decision plus small/medium implementation. +- **Owner:** Team decision, then Dreamverse or FastVideo. +- **Default recommendation:** Dreamverse-side custom provider. +- **Public schema source:** + [PromptEnhancerConfig](file:///home/william5lin/FastVideo/fastvideo/api/schema.py#L229-L235). +- **Tracking:** [DR-2](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L211-L229). +- **Exit criteria:** Dreamverse IFM provider works after prompt fork removal. + +#### Phase 5 — Move streaming demo config into FastVideo examples + +- **Effort:** Small. +- **Owner:** FastVideo public. +- **Source:** + [Dreamverse streaming_demo.yaml](file:///home/william5lin/Dreamverse/serve_configs/streaming_demo.yaml#L1-L149). +- **Target:** `examples/serving/streaming_demo.yaml`. +- **Exit criteria:** users can reproduce the typed streaming path from the + FastVideo repo without checking out Dreamverse. + +#### Phase 6 — Remove `experimental["pipeline_config"]` where practical + +- **Effort:** Medium for `layer_profile`; Large for a full typed + `dit_config.quant_config` carrier. +- **Owner:** FastVideo public, then Dreamverse cleanup. +- **Tracking:** + [open item #4](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L244-L260), + [quantization follow-up](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/quantization.md#L175-L200). +- **Exit criteria:** Dreamverse can express its quant layer profile through + typed config instead of in-memory mutation. + +#### Phase 7 — Decide standalone upsampler CLI + +- **Effort:** Small/Medium. +- **Owner:** FastVideo public. +- **Input:** internal standalone utility + [upsample.py](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/upsample.py#L120-L180) + and internal CLI + [cli/upsample.py](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/cli/upsample.py#L48-L130). +- **Public alternative:** SR refine stage already covers in-pipeline latent + upsampling: + [ltx2_refine.py](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/stages/ltx2_refine.py#L116-L180). +- **Exit criteria:** explicit decision: port CLI, document refine-stage-only + support, or defer. + +#### Phase 8 — Validate LTX-2 stage parity and offload residuals + +- **Effort:** Small/Medium for stage parity; Medium for layerwise offload. +- **Owner:** FastVideo public. +- **Stage source:** + [public LTX-2 stages](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/stages/). +- **Offload source:** + [internal layerwise offload](file:///home/william5lin/FastVideo-internal/fastvideo/models/layerwise_offload.py#L15-L20). +- **Exit criteria:** no known behavior gap between internal and public LTX-2 + stages; offload is either deliberately deferred or ported with tests. + +### Open questions + +1. **Which provider path for `cerebras_ifm`?** + - Public provider or Dreamverse-side custom provider? + - Default recommendation: Dreamverse-side unless there is another user. + - Source: [DR-2](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L211-L229). + +2. **Should public FastVideo support standalone LTX-2 file upsampling?** + - If yes, port internal CLI. + - If no, document that SR support is pipeline-refine only. + - Sources: [internal CLI](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/cli/upsample.py#L15-L35), + [public refine stage](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/stages/ltx2_refine.py#L1-L22). + +3. **Does Dreamverse need layerwise CPU offload?** + - If memory-tight deployments require it, port as generic FastVideo. + - Otherwise defer. + - Source: [internal offload manager](file:///home/william5lin/FastVideo-internal/fastvideo/models/layerwise_offload.py#L15-L20). + +4. **How much Dreamverse route surface should FastVideo own?** + - Health/readiness/status should migrate because they are part of + streaming-server compatibility. + - Curated presets and prompt-system config should stay Dreamverse-side + unless product policy changes. + - Source: [route contract](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/streaming-server.md#L232-L259). + +5. **Should `layer_profile` be the only near-term quant typed addition?** + - Adding `layer_profile` is bounded. + - A typed carrier for arbitrary mutated `PipelineConfig` is larger design + work. + - Source: [quantization follow-ups](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/quantization.md#L175-L200). + +6. **When does Option D become Option C?** + - Only if Dreamverse backend routes become public FastVideo product API. + - Until then, keep generic streaming code in FastVideo and product code in + Dreamverse. + +--- + +## Part 3 — Action items + +1. **P0 / S — Update Dreamverse README dependency notes.** + - Replace `../FastVideo-internal` with public FastVideo instructions. + - Preserve local editable `../FastVideo` dev flow where useful. + - Source: [README stale lines](file:///home/william5lin/Dreamverse/README.md#L76-L109). + +2. **P0 / S — Replace or remove private FastVideo bootstrap script.** + - Current script clones `FastVideo-internal` and verifies imports from it. + - Source: [script](file:///home/william5lin/Dreamverse/.agents/skills/bootstrap-fastvideo-private-fork/scripts/bootstrap_fastvideo_private.sh#L7-L11). + +3. **P1 / M-L — Add `/healthz`, `/readyz`, and `/status` to public `build_app`.** + - Keep `/curated-presets` and prompt-system config in Dreamverse. + - Source: [open item #1](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L69-L99). + +4. **P1 / M — Replace Dreamverse prompt-enhancer fork with compat shim.** + - Wrap public `PromptEnhancer`. + - Keep only Dreamverse-specific metadata and product fallback behavior. + - Source: [DR-1](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L174-L206). + +5. **P1 / S-M — Decide `cerebras_ifm` provider path.** + - Default: Dreamverse custom provider via `register_provider`. + - Source: [DR-2](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L211-L229). + +6. **P2 / S — Add `examples/serving/streaming_demo.yaml` to FastVideo.** + - Start from Dreamverse config and remove Dreamverse-private comments. + - Source: [streaming_demo.yaml](file:///home/william5lin/Dreamverse/serve_configs/streaming_demo.yaml#L1-L149). + +7. **P2 / M — Verify each public LTX-2 colocated stage against internal behavior.** + - Start with refine, denoising, latent prep, image conditioning, text + encoding, and audio decoding. + - Source: [public refine stage](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/stages/ltx2_refine.py#L1-L22). + +8. **P2 / M — Add typed `transformer_quant_layer_profile` if Dreamverse needs it.** + - Thread schema → compat → `FastVideoArgs._apply_transformer_quant`. + - Source: [open item #4](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L244-L260). + +9. **P2 / S-M — Decide standalone LTX-2 upsampler CLI support.** + - Port internal CLI only if file-to-file upsampling is a public workflow. + - Source: [internal upsample CLI](file:///home/william5lin/FastVideo-internal/fastvideo/entrypoints/cli/upsample.py#L15-L35). + +10. **P2 / S — Fix pre-existing AbsMaxFP8 test failure separately.** + - Do not block Dreamverse migration on it. + - Source: [open item #2](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/open-threads.md#L100-L117). + +11. **P2 / S-M — Document public streaming install extras and dependencies.** + - Include router `websockets`, prompt enhancer provider SDKs, and optional + safety classifier extras. + - Source: [D-16 dependency note](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L224-L242). + +12. **P2 / S — Keep contract tests in the FastVideo CI path.** + - Guard Dreamverse shape, Dynamo shape, and async events. + - Sources: [Dreamverse test](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dreamverse_shape.py#L1-L26), + [Dynamo test](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_dynamo_shape.py#L1-L19), + [async test](file:///home/william5lin/FastVideo/fastvideo/tests/contract/test_generate_async.py#L1-L7). + +13. **P3 / M — Defer layerwise offload until a deployment needs it.** + - Port only as generic FastVideo utility with tests. + - Source: [internal offload](file:///home/william5lin/FastVideo-internal/fastvideo/models/layerwise_offload.py#L15-L20). + +14. **P3 / M — Defer StepVideo public parity for this integration.** + - Dreamverse model registry is LTX-2/LTX-2.3 only. + - Source: [Dreamverse config](file:///home/william5lin/Dreamverse/server/config.py#L28-L45). + +15. **P3 / S — Do not add debug-only fields to public schema by default.** + - Keep them private unless there is a user-facing debugging workflow. + - Source: [internal debug args](file:///home/william5lin/FastVideo-internal/fastvideo/fastvideo_args.py#L200-L203). + +16. **P3 / M — Keep router active-active and sticky routing deferred.** + - Add only when session-routing evidence justifies it. + - Source: [D-15 action items](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L175-L201). + +17. **P3 / S — Preserve Dynamo as an external backend package.** + - FastVideo should expose typed API; Dynamo code lives in Dynamo. + - Source: [Dynamo contract](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/cross-repo-surfaces.md#L188-L210). + +18. **P3 / S — After #1288 merges, update memory-dir state.** + - Mark item D resolved and update branch tips. + - Source: [runbook post-merge steps](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/runbook.md#L51-L70). + +19. **P3 / S — Remove stale split-PR mental model from follow-up docs.** + - #1288 is the current vehicle; split bookmarks are historical. + - Source: [D-17 implications](file:///home/william5lin/FastVideo/.agents/memory/dreamverse-integration/decisions-log.md#L34-L45). + +20. **P3 / S — Keep product-only Dreamverse frontend out of FastVideo unless explicitly re-scoped.** + - This preserves release cadence and avoids packaging bloat. + - Source: [Dreamverse baseline](file:///home/william5lin/Dreamverse/README.md#L5-L16). diff --git a/.agents/memory/dreamverse-integration/open-threads.md b/.agents/memory/dreamverse-integration/open-threads.md new file mode 100644 index 0000000000..96e4fa1c92 --- /dev/null +++ b/.agents/memory/dreamverse-integration/open-threads.md @@ -0,0 +1,531 @@ +# Open Threads — Active Follow-Ups + +Live work items with priority, effort estimate, dependencies, and +recommended next action. + +For why each item is open see [decisions-log.md](decisions-log.md). For +PR-level context see [pr-roadmap.md](pr-roadmap.md). + +**Last updated:** 2026-05-05 (D-20 broken-pipe root cause + fix landed on +`will/dreamverse-monorepo` @ `5eaf0a13`; added new thread D-20-CP for +cherry-picking the public-API audio routing fix to `will/ltx2_sr_port` +so it lands in PR #1288. Earlier: strategy reversal — PR #1287 CLOSED, +replaced by mega-PR #1288 on `will/ltx2_sr_port` @ `b36bdbc9` covering +the full 6-layer stack at once. See [decisions-log.md D-17](decisions-log.md#d-17). +Item D resolution gate is now #1288 merge instead of #1287; same content, +different vehicle.). + +## Priority overview + +| # | Pri | Item | Effort | Unblocks | +|---|---|---|---|---| +| **D-20-CP** | High | Cherry-pick `[fix] api: route LTX-2 audio kwargs through batch.extra; strict update` (`265ce1a6`) onto `will/ltx2_sr_port` so it lands in PR #1288 | 15 min | Surfaces the public-API audio-conditioning fix in the mega-PR rather than waiting for `will/dreamverse-monorepo` to fold in. Tests already pass (185/185 api). | +| **~~D-22~~** | ~~Med~~ | ~~Per-chunk timing instrumentation in `stream_fmp4` and the controller's AV relay loop~~ | ~~M~~ | ✅ **Resolved 2026-05-06** in `bade2c0a`. `av_streaming.stream_fmp4` now records `av_wav_write_ms`, `av_ffmpeg_spawn_ms`, `av_first_chunk_ms`, `av_chunk_interval_ms_{min,median,p95,max}`, `av_chunk_publish_ms_{median,p95}`, `av_chunk_read_ms_{median,p95}` into the timings dict; `gpu_pool.handle_command` prints a one-line summary per segment so they show up directly in the deploy log. **Controller-side WS-send instrumentation is the remaining unaddressed slice** — see new D-22-CTL. | +| **D-22-CTL** | Low | Controller-side AV relay timing in `apps/dreamverse/server/session/controller.py` (between media event arrival and ws_send_bytes). | S | The worker side is now fully attributed by D-22. The controller-side per-chunk WS-send overhead is the still-unmeasured slice of the 700ms gap between `worker_e2e` and `main_user_step`. Add `t_ws_send_ms` per chunk in the AV relay loop, surface as `controller_ws_send_ms_{median,p95}` in the segment summary log line. | +| **D-23** | Med | On NVENC-capable hosts (RTX 50-series / T4 / A10 / H100 PCIe), benchmark `h264_nvenc` vs `libx264` and decide whether to default `--nvenc=true` for that SKU | S benchmark + S decision | Stutter mitigation depends on hardware; B200 needs different fix path (D-24). | +| **D-24** | Low | For B200-class deploys without NVENC, prototype gen-N+1 // encode-N pipelining or FE buffer pre-fill | L | Architectural change required; benchmark suggests ~700ms can be hidden if we pipeline. Ship-blocker only when realtime stutter becomes user-visible on B200 deploys. | +| **D-8** | High | Verify `ltx2_image_crf` post-`d80c2a8` | 10 min | Confirms typed stage-override path actually flows; closes a latent silent-drop bug | +| **1** | High | Migrate `/healthz`+`/readyz`+`/status` into FastVideo `build_app` | M-L | Closes BE_FLAVOR=fastvideo FE-compatibility; closes streaming-upstream contract debt | +| **2** | High | Fix pre-existing AbsMaxFP8 test failure | S | Self-contained quantization tech debt | +| **VPO** | High | Decide `video_position_offset_sec` semantics (a vs b) | 30 min | Unblocks PR 7.6 state emission | +| **D** | 🟢 in flight | Implement `generate_async` — content shipped in mega-PR **#1288** on `will/ltx2_sr_port` @ `b36bdbc9` (was #1287, CLOSED + re-routed per [D-17](decisions-log.md#d-17)) | L | Closes Q-5/Q-9/PR-7.5 TODOs simultaneously; enables Dynamo backend; unblocks audio re-encode; enables `GpuPool.run_async()` migration (D-12-B). Resolution gate: #1288 merge. | +| **DR-1** | High | Dreamverse: create `prompting/_internal_compat.py` shim + replace local `prompt_enhancer.py` (1933 LOC) — **PR #1258 has merged (`f673423b`); now actionable** | M (~150-200 LOC shim, replace upstream wiring) | Lets Dreamverse stop carrying a 1933-LOC fork | +| **DR-2** | Med | Decide `cerebras_ifm` provider path: (a) public Literal + `CerebrasIFMProvider` shipped, OR (b) Dreamverse-side custom provider via `enhancer.register_provider(...)` | S (decision) + S-M (impl) | Resolves the cerebras_ifm gap left by PR #1258. Same item as legacy #3 below; DR-2 is the Dreamverse-side framing. | +| **3** | Med | Add `cerebras_ifm` to `PromptEnhancerConfig.provider` Literal + provider | S-M | Public-side resolution if DR-2 picks (a) | +| **4** | Med | Expose `layer_profile` on typed `engine.quantization` | M | Removes Dreamverse's `experimental["pipeline_config"]` dodge for stage profiles | +| **5** | Med | Design typed `dit_config.quant_config` carrier | L design + L impl | Removes broader `experimental["pipeline_config"]` escape hatch | +| **SBS** | Med | `SessionStore` / `BlobStore` lifecycle policy | M design | Needed in PR 7.5 design pass | +| **D-12-A** | Med | Update `GpuPool` ABC docstring: mark "API may change post-PR-7.10; experimental / server-internal" | trivial | Prevents accidental promotion of streaming-internal API to framework-level | +| **D-12-B** | Med | Replace `GpuPool.run() -> Any` with `run_async() -> AsyncIterator[VideoEvent]` in PR 7.10 cycle | M | Closes the streaming-server cancellation TODO; converges with `generate_async` | +| **D-13-A** | Med | Document `fastvideo.entrypoints.streaming.prompt.*` in user-facing docs as "streaming-server scoped"; avoid framework-level framing | trivial (docs only) | Keeps future move to `fastvideo.prompt.*` cheap | +| **D-13-B** | Low | Add optional `client_factory` parameter to `LLMProvider` for `httpx.AsyncClient` pooling | S | Only if metrics show connect/TLS overhead is meaningful | +| **D-12-C** | Low | Avoid locking `PoolAssignment.gpu_id: int` as public; rename to `worker_id` (already exists) or add `device_ids: list[int]` for topology-aware pooling | S | Future multi-GPU-per-worker refactor stays cheap | +| **6** | Low | Audio attention quantization profile + test update | S | Future audio quant exploration | +| **7** | Low | Schema parity inventory cleanup (env-driven prompt fields) | S-M | Long-term consistency | +| **8** | Low | Stale `apps/web/test-results/` dir cleanup | trivial | Cosmetic | +| **11** | Low | Promote LTX-2 prompt orchestration (locked segments, segment_prompts JSON shape, rollout id/label) to `fastvideo.entrypoints.streaming.prompt.ltx2_orchestration` | M | Resolves Q-2 from decisions-log when a second LTX-2-style consumer appears | +| **12** | Low | When streaming server starts using `PromptSafetyFilter`, ensure operator-visible logging on `SafetyDecision.UNAVAILABLE` results | trivial | Surfaces degraded-safety state to operators (per D-14 Watch-Out item) | +| **13** | Low | When sticky session routing is needed, add `ReplicaRegistry.select(routing_key: str | None = None)` and document where `session_id` lives (WS URL/header preferred over first JSON frame) | M | Forward-compat from D-15 — keeps the door open without buffering/peeking | +| **14** | Low | At higher load, add `_bridge_session()` max-size + timeout limits OR recommend Envoy/HAProxy in front | S-M | The libraries' basic backpressure suffices for MVP; document the limit per D-15 | +| **15** | Low | If active-active multi-primary becomes a requirement, define behavior (round-robin within healthy primaries, weighted, sticky-by-key) | M | Currently `RouterConfig.__post_init__` rejects multi-primary; D-15 deferred until evidence | +| **~~Source-doc disposition~~** | ~~Med~~ | ~~Disposition of 7 untracked source docs~~ | ~~trivial~~ | ✅ **Resolved 2026-05-03** — moved into [source-archive/](source-archive/) | +| **~~9~~** | ~~Low~~ | ~~Commit-message cleanup: PR 8's 3 commits still have `[8/n] Improve API:` prefix~~ | ~~S~~ | ✅ **Resolved 2026-05-04** — bundled into the will/api_7.8 prep rebase. PR 8's 3 commits now read `[type] streaming: ...` | +| **~~10~~** | ~~Low~~ | ~~Commit-message cleanup: PR 7.8/7.9 commits have `streaming: streaming X` duplication~~ | ~~S~~ | ✅ **Resolved 2026-05-04** — bundled into the will/api_7.8 prep rebase. 3 commits dedup'd. | + +--- + +## High priority + +### D-20-CP: Cherry-pick public-API audio routing fix to `will/ltx2_sr_port` + +**Why:** Commit `265ce1a6` (`[fix] api: route LTX-2 audio kwargs through batch.extra; strict update`) lives only on `will/dreamverse-monorepo` today. It touches public FastVideo surface (`fastvideo/entrypoints/video_generator.py`, `fastvideo/api/sampling_param.py`, plus a new regression test). For PR #1288 to ship a coherent public API — including the strict `SamplingParam.update()` — this commit needs to also land on `will/ltx2_sr_port`. + +**Action:** + +1. `git checkout will/ltx2_sr_port` +2. `git cherry-pick 265ce1a6` (clean; only touches `fastvideo/` paths that exist on both branches) +3. `pre-commit run --files fastvideo/entrypoints/video_generator.py fastvideo/api/sampling_param.py fastvideo/tests/api/test_extra_overrides_routing.py` +4. `pytest fastvideo/tests/api/ -q` (expect 185 passed) +5. `git push origin will/ltx2_sr_port` (fast-forward, no force) +6. `git checkout will/dreamverse-monorepo` (return to default working branch per runbook) + +**Outcome:** PR #1288 picks up the fix automatically (its head IS `will/ltx2_sr_port`). The cherry-pick lives on both branches as separate SHAs; they'll dedupe naturally on any future rebase. + +**Effort:** 15 minutes (cherry-pick + lint + test + push). + +**Dependencies:** None. Tests already pass; no rebase conflicts expected. + +**Files touched (same on both branches):** + +- `fastvideo/entrypoints/video_generator.py` +- `fastvideo/api/sampling_param.py` +- `fastvideo/tests/api/test_extra_overrides_routing.py` (new file) + +### D-8: Verify `ltx2_image_crf` typed flow post-`d80c2a8` + +**Why:** Apr 26 dreamverse_review documented this field getting silently +dropped by the public `SamplingParam`. May 2 `d80c2a8` (Dreamverse) +refactored to typed `GeneratorConfig` + `preset_overrides`. Whether +`image_crf` now flows through `request.stage_overrides.refine.image_crf` +(per [design.md](design.md) mapping) or is still dropped is unverified. + +**Action:** +1. Read [`Dreamverse/server/video_generation.py`](file:///home/william5lin/Dreamverse/server/video_generation.py) + post-`d80c2a8` for `image_crf` handling +2. Trace through to FastVideo's `request.stage_overrides.refine.image_crf` +3. Confirm runtime consumption in [`fastvideo/pipelines/basic/ltx2/`](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/) + +**Effort:** 10 min, no code changes. + +**Outcome:** Either confirms working OR identifies bug → opens fix item. + +### Item #1: Migrate `/healthz`+`/readyz`+`/status` into `build_app` + +**Why:** Today +[`fastvideo.entrypoints.streaming.server.build_app`](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/server.py) +exposes only `/health` + `/v1/stream`. Dreamverse FE expects all of +`/healthz`, `/readyz`, `/status`, `/curated-presets`, +`/prompt-system-config`, devtools. + +The streaming-server-upstream plan (line 84) explicitly lists +`/healthz`+`/readyz`+`/status` as part of the contract that the upstream +of `realtime/` → `streaming/` must preserve. They were deferred from +PR 7.5's MVP. `/curated-presets` and `/prompt-system-config` are +operator-side and stay in Dreamverse (FE feature-detects). + +**Action:** +1. Read PR 7.5 (#1251) `build_app` to scope what's there +2. Read [`Dreamverse/server/routes/health.py`](file:///home/william5lin/Dreamverse/server/routes/health.py) + for the route shapes Dreamverse already consumes +3. Propose route migration as commit on top of `will/api_7.5` or as + part of PR 7.10 cycle +4. Land + +**Effort:** Medium-Large (route shapes need preservation; tests). + +**Dependencies:** None blocking; can land anytime. + +**Files likely to touch:** +- `fastvideo/entrypoints/streaming/server.py::build_app` +- New `fastvideo/entrypoints/streaming/health.py` +- Tests in `fastvideo/tests/entrypoints/streaming/` + +### Item #2: AbsMaxFP8 pre-existing test failure + +**Why:** [`fastvideo/tests/ops/quantization/test_absmax_fp8.py::test_create_weights_rejects_invalid_dtype`](file:///home/william5lin/FastVideo/fastvideo/tests/ops/quantization/test_absmax_fp8.py) +fails with `AssertionError not raised`. Pre-existing on `main`; verified +NOT introduced by NVFP4 work via `git stash`. + +**Action:** +1. `git log --oneline fastvideo/tests/ops/quantization/test_absmax_fp8.py` + to find when it last passed +2. Either: + - Restore the assert in `AbsMaxFP8LinearMethod.create_weights` if + intentional behavior was lost + - Drop the test if assert is no longer correct +3. Verify + +**Effort:** Small. + +**Dependencies:** None. + +### Item VPO: `video_position_offset_sec` semantics + +**Why:** Per +[`fastvideo/pipelines/basic/ltx2/continuation.py`](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/continuation.py), +`LTX2ContinuationState.video_position_offset_sec` exists as a state +field. Two valid interpretations: + +- **(a) Persistent across segments** — accumulating time offset for long + sessions; useful for time-coherent audio chaining. +- **(b) Per-segment hint that rides on the carrier** — runtime + overwrites every time; field is harmless redundancy. + +Dreamverse computes `prefix_sec = float(audio_extra) / 24.0` per segment +in `apply_audio` and currently does NOT persist it on +`ContinuationState`. Field's docstring leans toward (b). + +**Decision deadline:** before PR 7.6 starts emitting/consuming the +field (PR 7.6 branch is ready, not yet PR'd). + +**Action:** +1. Confirm field's intended semantics with audio team +2. If (a): document the accumulation rule explicitly + add tests +3. If (b): leave docstring as-is + add test confirming overwrite + +**Effort:** 30 min discussion + small implementation. + +### Item D: Implement `generate_async` (PR 7.10) + +**Why:** Highest leverage. Closes: + +- D-5 / Q-5: audio re-encode for cross-segment continuity +- Q-9: Dynamo progress passthrough (deferred) +- PR 7.5's mid-segment cancellation TODO +- Unblocks Dynamo native backend integration +- **D-12-B**: enables `GpuPool.run() -> run_async() -> AsyncIterator[VideoEvent]` migration + +**Action:** See [streaming-server.md](streaming-server.md) "PR 7.10 — the +unlock PR" section for scoping. + +**Effort:** Large. + +**Dependencies:** Best after PR 7.6 lands (gpu_pool upstream). + +**Files:** +- `fastvideo/entrypoints/video_generator.py` — add `generate_async`, + refactor `generate_video` as wrapper +- `fastvideo/api/results.py` — add `VideoEvent`/`VideoProgressEvent`/ + `VideoPartialEvent`/`VideoFinalEvent` +- `fastvideo/entrypoints/streaming/server.py` — consume `generate_async`, + remove TODO markers +- `fastvideo/entrypoints/streaming/gpu_pool.py` — add `run_async()` + forwarding events from worker to caller +- New `fastvideo/tests/entrypoints/test_generate_async.py` +- New `fastvideo/tests/contract/test_dynamo_shape.py` (already in PR 8) + +### Item DR-1: Dreamverse — replace local `prompt_enhancer.py` with public + compat shim + +**Why:** Today Dreamverse carries `Dreamverse/server/prompt_enhancer.py` +(1933 LOC) — a local copy/derivative of the FastVideo-internal version. +After PR #1258 merges, Dreamverse should switch to the public +`fastvideo.entrypoints.streaming.prompt.PromptEnhancer` and delete most +of the local module. + +**Migration shape:** + +1. **Create** `Dreamverse/server/prompting/_internal_compat.py` (~150-200 LOC): + - Wraps public `PromptEnhancer.enhance()` → returns `EnhanceResult` shape Dreamverse expects + - Wraps public `PromptEnhancer.auto_extend()` — JSON-parses `LLMResponse.content` into `{"next_prompt": "..."}` + - Wraps public `PromptEnhancer.rewrite()` — JSON-parses into `{"segment_prompts": [...]}` with lenient fallback for malformed JSON + - Layers locked-segment + rollout_id + rollout_label metadata back on top +2. **Update** `Dreamverse/server/runtime.py + main.py` — replace `from prompt_enhancer import PromptEnhancer` with `from prompting._internal_compat import PromptEnhancer` +3. **Delete most of** `Dreamverse/server/prompt_enhancer.py` (1933 LOC). Keep only the bits that don't have a public equivalent: + - Race-based parallel fallback (`_run_provider_race`) — Dreamverse-specific tail-latency optimization + - `cerebras_ifm` provider — pending DR-2 decision + - Multi-classifier prompt safety (NSFW + hate-speech chained) — public ships single classifier +4. **Tests** — verify Dreamverse session controllers still see the expected response shapes through the shim + +**Effort:** Medium (~150-200 LOC shim + replace upstream wiring + delete 1700+ LOC local module + test fixture updates). + +**Dependencies:** +- PR #1258 must merge first (publishes `fastvideo.entrypoints.streaming.prompt.*`) +- DR-2 informs the cerebras_ifm path + +**Files:** +- New: `Dreamverse/server/prompting/_internal_compat.py` +- Modified: `Dreamverse/server/runtime.py`, `Dreamverse/server/main.py` +- Mostly deleted: `Dreamverse/server/prompt_enhancer.py` + +--- + +## Medium priority + +### Item DR-2: Decide `cerebras_ifm` provider path + +**Why:** Public PR #1258's `PromptEnhancerConfig.provider` is +`Literal["cerebras", "groq"]`. Internal supports `"cerebras_ifm"` (the +Cerebras IFM API endpoint with different auth). Dreamverse needs +`cerebras_ifm` working post-migration. + +Two options: + +| Option | Approach | Pros | Cons | +|---|---|---|---| +| **(a) Public** | Add `"cerebras_ifm"` to public Literal + ship `CerebrasIFMProvider` in `fastvideo/entrypoints/streaming/prompt/providers/cerebras_ifm.py` | Discoverable; users with IFM access can use typed config | Adds ~50 LOC + Literal extension to public surface | +| **(b) Dreamverse-side** | Implement `CerebrasIFMProvider` Dreamverse-side as a custom `LLMProvider`, register via `enhancer.register_provider(CerebrasIFMProvider())` | Zero public surface change; private endpoint stays private | Slightly more boilerplate Dreamverse-side; not surfaced to non-Dreamverse users | + +**Recommendation:** Option (b) is more contained. Option (a) is more +discoverable. Default to (b) unless there's a third-party user who needs +IFM access. The Dreamverse-side PR carrying DR-1 is the natural place to +make this decision. + +**Effort:** Small (decision) + Small-Medium (implementation). + +**Dependencies:** DR-1 (compat shim creation). + +### Item #3: `cerebras_ifm` provider in public Literal + +**Why:** Same item as DR-2 from the public-side framing. If DR-2 picks +option (a), this is the implementation. If DR-2 picks option (b), this +item is closed without implementation. + +**Action:** See DR-2. + +**Effort:** S-M. + +### Item #4: Expose `layer_profile` on typed `engine.quantization` + +**Why:** Today `transformer_quant: "NVFP4"` always constructs +`NVFP4Config()` with default `layer_profile="refine"`. Dreamverse +dodges via `experimental["pipeline_config"]`. + +**Action:** +1. Add `transformer_quant_layer_profile: str | None = None` to + `QuantizationConfig` in [`schema.py`](file:///home/william5lin/FastVideo/fastvideo/api/schema.py) +2. Thread through [`compat.py`](file:///home/william5lin/FastVideo/fastvideo/api/compat.py) +3. Update `_apply_transformer_quant` in + [`fastvideo_args.py`](file:///home/william5lin/FastVideo/fastvideo/fastvideo_args.py) + to pass profile +4. Update Dreamverse to drop the `experimental["pipeline_config"]` + dodge in favor of typed knob +5. Tests in [`test_typed_quant_flow.py`](file:///home/william5lin/FastVideo/fastvideo/tests/api/test_typed_quant_flow.py) + +**Effort:** Medium. + +**Files:** schema.py, compat.py, fastvideo_args.py, test_typed_quant_flow.py, ++ Dreamverse/server/video_generation.py. + +### Item #5: Typed `dit_config.quant_config` carrier + +**Why:** The `experimental["pipeline_config"]` escape hatch in +Dreamverse should eventually become a typed field. Design TBD. + +**Action:** Heaviest design work. Should consult Oracle. + +**Effort:** Large design + Large implementation. + +**Dependencies:** #4 should land first; this is the "final form" of #4. + +### Item SBS: `SessionStore` / `BlobStore` lifecycle policy + +**Why:** PR 7's in-memory implementations have no eviction, no TTL, no +automatic blob cleanup on state replacement. Documented as per-deployment +policy decision. + +When PR 7.5/7.6 land the live consumer, who owns: + +- bounded session capacity (LRU? TTL? hard max?) +- blob `drop()` chained when state is replaced +- session expiry on websocket disconnect + +**Recommendation:** streaming server's session manager. Worth stating +explicitly in PR 7.5's design. + +**Effort:** Medium design + small implementation. + +### Item D-12-A: Update `GpuPool` ABC docstring — mark experimental + +**Why:** Per D-12 in [decisions-log.md](decisions-log.md), `GpuPool` +should be documented as "API may change post-PR-7.10; experimental / +server-internal" to prevent accidental promotion of streaming-internal +API to framework-level. PR #1257 merged without this caveat. + +**Action:** Edit +[`fastvideo/entrypoints/streaming/gpu_pool.py`](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/gpu_pool.py) +class docstring on `GpuPool` ABC. Add a note: "API may change post-PR-7.10 +when run_async() lands; treat as server-internal for now." + +**Effort:** Trivial. + +**Dependencies:** None. + +### Item D-12-B: Replace `GpuPool.run() -> Any` with `run_async() -> AsyncIterator[VideoEvent]` + +**Why:** Per D-12, this is the canonical evolution post-PR-7.10. Closes +the streaming server's cancellation TODO and converges the streaming + +OpenAI + Dynamo consumers on a single async API. + +**Action:** As part of PR 7.10 cycle: +1. Add `GpuPool.run_async(session_id, request) -> AsyncIterator[VideoEvent]` +2. Worker forwards events through `result_queue` with type discriminator +3. Streaming server replaces `await pool.run(...)` with `async for event in pool.run_async(...)` +4. Sync `run()` becomes a thin compat wrapper that collects events and returns the final +5. Cancellation propagates: client disconnect → `asyncio.CancelledError` → worker stops mid-step + +**Effort:** Medium. Adds ~50-100 LOC + tests. + +**Dependencies:** Item D (PR 7.10 — `generate_async` on `VideoGenerator`). + +### Item D-13-A: Document `streaming/prompt/*` as streaming-scoped + +**Why:** Per D-13 in [decisions-log.md](decisions-log.md), the prompt +enhancer is currently scoped to streaming-server use even though the +abstraction is general. Phrase user-facing docs as "streaming-server +prompt enhancement" to keep future move to `fastvideo.prompt.*` cheap. + +**Action:** When PR 12 (docs migration) is written, the prompt enhancer +section should: +- Be titled "Streaming Server Prompt Enhancement", not "Prompt API" +- Note the 3 fixed operations (`enhance` / `auto_extend` / `rewrite`) are + shaped by LTX-2 streaming session needs +- Note that consumers wanting custom prompt operations can use + `provider.complete()` directly with their own LLMRequest +- Avoid `from fastvideo import LLMProvider` exports until a second + consumer exists + +**Effort:** Trivial (docs only). + +**Dependencies:** PR 12 (docs migration). + +--- + +## Low priority + +### Item D-13-B: Optional `client_factory` parameter for `httpx.AsyncClient` pooling + +**Why:** Today `_openai_compat.py` instantiates `httpx.AsyncClient` per +call (no connection pooling). Reviewer flagged inefficient. Team chose +simplicity for the expected scale (~6-10 enhancer calls per LTX-2 +session). If real-world metrics show connect/TLS overhead is meaningful, +add an optional `client_factory: Callable[[], httpx.AsyncClient] | None` +parameter to providers so they can share a pool. + +**Action:** Only when metrics justify. Add `client_factory=None` parameter +to `CerebrasProvider` / `GroqProvider` constructors and pass through to +`complete_openai_compatible()`. Default to current per-call behavior. + +**Effort:** Small. + +**Dependencies:** None blocking; only act on real perf data. + +### Item D-12-C: Avoid locking `PoolAssignment.gpu_id: int` as public + +**Why:** Today `PoolAssignment` exposes `gpu_id: int`, assuming +one-GPU-per-worker. Future topology-aware pooling may need +`device_ids: list[int]` (one worker = group of GPUs running internal +`MultiprocExecutor`). Don't freeze the int field as public API. + +**Action:** +- Treat `gpu_id` as a current-impl detail; prefer `worker_id` (already + exists, is stable identifier) +- When a worker actually spans multiple GPUs, add + `PoolAssignment.device_ids: list[int]` and let `gpu_id` be `device_ids[0]` + for backward compat +- Or rename to `gpu_id` → `device_id` with deprecation alias + +**Effort:** Small (1 field rename + alias). + +**Dependencies:** Driven by an actual future "one worker = many GPUs" use case. Don't act preemptively. + +### Item #6: Audio attention quantization profile + +**Why:** Today audio attn and FFN are bf16. If an audio-quant profile +is added to `NVFP4Config.fp4_layers`, update +[`test_basic_av_block_propagates_quant_config_to_all_children`](file:///home/william5lin/FastVideo/fastvideo/tests/ops/quantization/test_nvfp4_ltx2_wiring.py). + +**Effort:** Small (one test + one config field). + +### Item #7: Schema parity inventory cleanup + +**Why:** A few internal-only fields are not exposed publicly: + +- `PROMPT_HTTP_TIMEOUT_MS` +- `PROMPT_INITIAL_STAGE_TIMEOUT_MS` +- `PROMPT_TEMPERATURE` +- `PROMPT_MAX_COMPLETION_TOKENS` +- `PROMPT_AUTO_SLEEP_MS` +- `PROMPT_AUTO_TIMEOUT_MS` +- curated-presets file paths + +These flow via env vars on `dreamverse-server` today. If +`fastvideo serve --config` becomes the canonical entrypoint, they need +typed homes. + +**Effort:** Small-Medium. + +### Item #8: Stale `apps/web/test-results/` directory + +**Why:** Cosmetic. `.gitignore` entry hides it from `git status`, but +the dir has stale `.last-run.json` (45 bytes) from a prior Playwright +run. + +**Action:** `rm -rf apps/web/test-results` whenever convenient. + +**Effort:** Trivial. + +### ~~Item #9~~ + ~~#10~~: Commit-message cleanups — ✅ Resolved 2026-05-04 + +Both items resolved during the `will/api_7.8` prep rebase. A targeted +conditional script (`/tmp/opencode/cleanup_subjects_v2.sh` — only amends +when text actually changes) ran across 33 commits, modified 6: + +- **#9 fix**: extended the regex from `\[\d+\.\d+/n\]` to + `\[\d+(\.\d+)?/n\]` so single-digit prefixes match. PR 8's 3 commits + now read `[type] streaming: ...` instead of `[type] [8/n] Improve API: ...`. +- **#10 fix**: added second substitution `streaming: streaming X` → + `streaming: X`. PR 7.8 / 7.9 commits no longer have the duplication. + +The conditional check skipped pre-commit-hook flakiness on no-op amends +(unlike the earlier first attempt). All affected commits verified clean +post-rebase. + +### Item #11: Promote LTX-2 prompt orchestration to public (when 2nd consumer exists) + +**Why:** Per Q-2 in [decisions-log.md](decisions-log.md) and D-13's +"missing alternative", the LTX-2-specific orchestration (locked +segments, segment_prompts JSON shape, rollout id/label, lenient JSON +parsing) currently stays Dreamverse-side per DR-1. If a second +LTX-2-style consumer appears (e.g. another video model with multi-segment +continuation needing the same prompt orchestration), promote this layer +to `fastvideo.entrypoints.streaming.prompt.ltx2_orchestration`. + +**Action:** Wait for a second consumer to materialize. Until then, the +orchestration stays in Dreamverse's `_internal_compat.py` shim (DR-1). + +**Effort:** Medium when triggered. + +**Dependencies:** A second consumer. + +--- + +## Recommended pull order + +If you have unbounded time and want to maximize forward progress: + +1. **D-8 verify** (10 min) — eliminates uncertainty +2. **D-12-A docstring** (trivial) — caveat the GpuPool API publicly +3. **Item #2 AbsMaxFP8** (S) — clears tech debt +4. **Item VPO video_position_offset_sec** (30 min) — unblocks PR 7.10 (since 7.6 has merged, this is now scoped to whatever consumer first reads the field) +5. **DR-1 + DR-2 Dreamverse migration** (M) — **now unblocked since PR #1258 merged**; replaces 1700+ LOC of local fork +6. **Item #4 layer_profile** (M) — closes Dreamverse quant escape hatch +7. **Item #1 build_app routes** (M-L) — closes FE-compat +8. **Item D generate_async** (L) — unlock PR; brings along D-12-B (run_async) + closes Q-5/Q-9/PR-7.5 TODOs +9. **Item #5 typed quant_config carrier** (L+L) — final form +10. **Items #6/#7/#8 + D-12-C/D-13-A/D-13-B + #11** — cleanup polish (#9, #10 resolved 2026-05-04) + +If you have a specific user goal (e.g. "ship `BE_FLAVOR=fastvideo` +flavor end-to-end"), that goal dictates the order — read this list as a +menu, not a prescription. + +--- + +## Verification gates per item + +When implementing any item above, evidence required: + +| Phase | Check | +|---|---| +| Build | `lsp_diagnostics` clean on changed files | +| Test | new + relevant existing tests pass; output captured | +| Manual QA | actually run the affected feature end-to-end (per AGENTS.md MANUAL_QA_MANDATE) | +| Regression | full `fastvideo/tests/api/` + `contract/` + relevant SSIM (if NVFP4 touch) | + +For NVFP4 touches: re-run `test_nvfp4_ltx2_wiring.py` + +`test_typed_quant_flow.py` (CPU) + ideally a flashinfer-enabled path +test (manual, not in CI). + +For Dreamverse-side items (DR-1, DR-2): re-run +`Dreamverse/apps/web/npx playwright test e2e/preset-prompt-generation.spec.ts` +end-to-end against the live BE+FE — this is the contract test that +exercises the prompt enhancer through a real session. diff --git a/.agents/memory/dreamverse-integration/pr-roadmap.md b/.agents/memory/dreamverse-integration/pr-roadmap.md new file mode 100644 index 0000000000..2fe1f69f53 --- /dev/null +++ b/.agents/memory/dreamverse-integration/pr-roadmap.md @@ -0,0 +1,141 @@ +# PR Roadmap + +Status of all 17 PRs in the FastVideo public API refactor + streaming +server upstream + Dynamo backend contract + post-deprecation cleanup. + +For design rationale see [design.md](design.md). For streaming-specific +PRs (7.5-7.10) see [streaming-server.md](streaming-server.md). For NVFP4 +work that runs parallel to this sequence see [quantization.md](quantization.md). + +**Last updated:** 2026-05-05 (strategy reversal — single mega-PR #1288 replaces planned splits 7.10/8/LTX-2/NVFP4/post-fixes/agents_cleanup; see [decisions-log.md D-17](decisions-log.md#d-17)). + +## Status legend + +- ✅ **Landed on `origin/main`** +- 🟢 **Open / in flight** — branch exists, may have open PR +- 🟡 **Planned** — designed, not started +- 🔵 **Future** — deferred to post-PR-13 cleanup + +## Landed PRs (0 → 7.7) + +| # | PR | Status | Merge commit | Scope | +|---|---|---|---|---| +| 0 | #1218 [1/n] | ✅ | merged | Parity inventory + typed inference schema | +| 1 | #1218 [1/n] | ✅ | merged | Strict parser/validation/overrides + API tests | +| 2 | #1220 [2/n] | ✅ | merged | Typed `VideoGenerator` constructors + request path + compat | +| 3 | #1226 [3/n] | ✅ | merged | CLI/YAML-first typed config loading for `generate` and `serve` | +| 4 | #1234 [4/n] | ✅ | merged | Preset registry + presets for all 13 model families; `SamplingParam` moved to `fastvideo/api/`; `configs/sample/` deleted entirely | +| 5 | #1237 [5/n] | ✅ | merged | `ServeConfig.default_request` wired into stateless OpenAI server | +| 5.5 | (`5d1d71fc`) | ✅ | merged | Streaming server package skeleton, typed `StreamingConfig`/`GpuPoolConfig`/`PromptEnhancerConfig`/`PromptSafetyConfig`/`WarmupConfig`, `streaming-serve` CLI stub | +| 6 | #1239 [6/n] | ✅ | merged | LTX2 public preset + asset wiring + `gpu_pool.py` typed-kwarg translation | +| 7 | #1250 [7/n] | ✅ | merged | Typed LTX2 continuation state + streaming session store + blob store | +| **7.5** | **#1251** | ✅ | `95fd29e0` (merged 2026-04-26) | Streaming server skeleton (WebSocket + fMP4 + single generator). 8 commits. Deferred TODOs (per-step progress, mid-segment cancellation) carried forward to PR 7.10. | +| **7.6** | **#1257** | ✅ | `eb0a4152` (merged 2026-05-04) | GPU pool upstream + worker subprocess + two-segment warmup. 7 commits squashed. APPROVED by Eigensystem. See [decisions-log.md D-12](decisions-log.md#d-12) for the architectural review. | +| **7.7** | **#1258** | ✅ | `f673423b` (merged 2026-05-04) | Prompt enhancer with `LLMProvider` abstraction. Built-in providers: cerebras, groq. 3 commits squashed. **Public Literal does NOT include `cerebras_ifm`** — open-threads.md item DR-2 covers the gap. See [decisions-log.md D-13](decisions-log.md#d-13) for the architectural review. | +| **7.8** | **#1284** | ✅ | `eb3a3942` (merged 2026-05-04) | Streaming auxiliaries — `prompt/safety.py` (optional fasttext, lazy import), `prompt/rewrite.py`, `session_logger.py` (thread-safe JSONL), `mock_server.py` (build_mock_app + MockGenerator for FE dev). 730 LOC, 2 commits. See [decisions-log.md D-14](decisions-log.md#d-14). | +| **7.9** | **#1286** | ✅ | `2aaeee2a` (merged 2026-05-05) | Streaming router (multi-replica load balancer + WS proxy + `fastvideo router-serve` CLI). Squashed `cd76cf51 + 1ac1e732 + b0b7f59c + a152cb77` (router-polish second-pass; cherry-pick of `40e265b8` from `will/ltx2_sr_port`). See [decisions-log.md D-15](decisions-log.md#d-15) (structural review) + [D-16](decisions-log.md#d-16) (second-pass polish). | + +## In flight (mega-PR #1288) + +| # | PR | Status | Branch | Scope | +|---|---|---|---|---| +| **mega** | **#1288** | 🟢 OPEN, MERGEABLE | `will/ltx2_sr_port` (head `b36bdbc9`) | **Single consolidated landing of the full `will/ltx2_sr_port` chain.** Was originally planned as 6 stacked PRs (slices 1-3 / 4-6 / 7-15 / 16-21 / 22-23 / 24-34). Now landing as one PR — see [decisions-log.md D-17](decisions-log.md#d-17) for the strategy decision. **Contents** (commit-ordered): (1) streaming `generate_async` + `VideoEvent` + Dynamo backend contract (3 commits, was PR 7.10/#1287 closed); (2) server contract docs + Dreamverse/Dynamo shape tests (3 commits, was PR 8); (3) LTX-2 SR runtime port + i2v conditioning + alignment harness (9 commits); (4) NVFP4 wire-up + per-component compile + typed `transformer_quant` flow (6 commits); (5) LTX-2 post-handoff parity fixes — Gemma `to()`, list-of-generators (2 commits); (6) `.agents/memory/dreamverse-integration/` knowledge base + agents Phase 1 cleanup (11 commits). 34 commits total, 71 files, +13,074/-583 LOC. | + +## Closed PRs in this scope + +| # | PR | Status | Why closed | +|---|---|---|---| +| **7.10** | **#1287** | ❌ CLOSED 2026-05-05 | Superseded by mega-PR #1288 — strategy reversal to land everything in one go. Same 3 commits now form the head of #1288. | + +## Deprecated split bookmarks (D-17) + +`will/api_7.10` / `will/api_8` / `will/ltx2_sr_runtime` / `will/ltx2_nvfp4` / `will/ltx2_post_fixes` / `will/agents_cleanup` were the split-PR bookmarks under the abandoned 6-PR plan. They remain locally as historical references but are no longer maintained. STACK.md (top-level) is similarly deprecated. + +## Planned (post-#1288 merge) + +| # | Status | Branch | Scope | +|---|---|---|---| +| 9 | 🟡 | — | LongCat preset migration + colocation (9 model-specific stage files) | +| 10 | 🟡 | — | Hunyuan15 SR preset migration + colocation + SR field migration POC | +| 11 | 🟡 | — | SSIM/performance test migration off legacy `generate_video(..., **kwargs)` | +| 12 | 🟡 | — | Docs + examples migration (includes streaming server + Dynamo) | +| 13 | 🟡 | — | Deprecation cleanup (includes flat LTX2 kwargs the internal `gpu_pool.py` used to consume) | + +## Future (compat.py death sequence) + +After PR 13 lands deprecation warnings, `fastvideo/api/compat.py` (~370 +lines) is the last translation shim between typed public API and legacy +internals (`FastVideoArgs`, `SamplingParam`). + +| # | Status | Scope | Lines removed | +|---|---|---|---| +| 14 | 🔵 reachable | Strip forward translation: `legacy_from_pretrained_to_config`, `legacy_generate_call_to_request`, `_sampling_param_to_request_raw`, `_LEGACY_REQUEST_ALIASES`, `_LTX2_REFINE_FLAT_KEYS`. Depends on PRs 11/12/7.6 callers being migrated. | ~100 | +| 15 | 🔵 | `FastVideoArgs` becomes a `@dataclass` view over `GeneratorConfig` with `@property` accessors backing legacy field names. ~600-line god-object refactor. Depends on PR 14. | reverse-translation half (~150) trivial | +| 16 | 🔵 | `ForwardBatch` reads `GenerationRequest` by reference; kills `request_to_sampling_param` and the `ForwardBatch(**shallow_asdict(sampling_param), …)` spread. `SamplingParam` demoted or deleted. Depends on PR 15. | rest | +| 17 | 🔵 | Move `normalize_generator_config`, `normalize_generation_request`, `load_generator_config_from_file` to `parser.py`. Delete `compat.py`. | file gone | + +PRs 15-17 touch training, distributed, and worker code in addition to +inference path; realistically 1-2 quarters beyond the current plan. + +## Dependency chain + +``` +PR 13 (deprecation) + ↓ +PRs 11, 12, 7.6 (migrate callers) + ↓ +PR 14 (forward translation gone) ─── ~100 lines out of compat.py + ↓ +PR 15 (FastVideoArgs as view) ─── reverse-translation trivial + ↓ +PR 16 (ForwardBatch reads request) ─── SamplingParam demoted + ↓ +PR 17 (move normalizers, delete file) +``` + +## NVFP4 work (out-of-band, parallel to PR 7.5+) + +NOT in the canonical PR sequence. Lives on `will/ltx2_sr_port` +(currently @ `156103b9`) — a separate stack alongside the public-API +upstreaming. See [quantization.md](quantization.md) for what each commit +locks in. + +| Commit range | Topic | +|---|---| +| `cfccd292..b6ac7630` | LTX-2 i2v + SR runtime port + alignment harness | +| `a4760bae..c6c14c55` | NVFP4 LTX-2 wire-up + per-component compile + parity fixes (May 2 handoff) | +| `a5fcd19c..156103b9` | Post-handoff parity/perf fixes | + +## Key landed artifacts (reference points) + +- Parity inventory: [`docs/design/inference_schema_parity_inventory.yaml`](file:///home/william5lin/FastVideo/docs/design/inference_schema_parity_inventory.yaml) + guard [`fastvideo/tests/api/test_schema_parity_inventory.py`](file:///home/william5lin/FastVideo/fastvideo/tests/api/test_schema_parity_inventory.py) +- Typed schema: [`fastvideo/api/schema.py`](file:///home/william5lin/FastVideo/fastvideo/api/schema.py) +- Compat layer: [`fastvideo/api/compat.py`](file:///home/william5lin/FastVideo/fastvideo/api/compat.py) +- Preset system: [`fastvideo/api/presets.py`](file:///home/william5lin/FastVideo/fastvideo/api/presets.py) + per-family `pipelines/basic//presets.py` +- Streaming package skeleton (PR 5.5): [`fastvideo/entrypoints/streaming/`](file:///home/william5lin/FastVideo/fastvideo/entrypoints/streaming/) +- LTX2 typed continuation state (PR 7): [`fastvideo/pipelines/basic/ltx2/continuation.py`](file:///home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/continuation.py) + +## Known notable decisions carried forward + +- **Public inference boundary stays plain dataclasses + plain dict/YAML/JSON** + — not OmegaConf, not runtime config wrappers. +- **Every public entrypoint normalizes into typed config objects** before + touching legacy `FastVideoArgs` or `SamplingParam`. +- **Legacy `generate_video(..., **kwargs)` stays on direct legacy execution + path until PR 11**'s SSIM/performance migration. Prevents golden + baselines from drifting during compat period. +- **Typed requests use schema defaults**; legacy `generate_video(...)` + continues to inherit model-specific `SamplingParam` defaults during + compat period. +- **Preset registry uses explicit `_register_presets()` pattern** matching + `_register_configs()`; lookup keyed by `model_family`. +- **Stateless OpenAI server clones `ServeConfig.default_request`** and + merges user overrides; preset validation runs before legacy generation. +- **Streaming server added as sibling `fastvideo/entrypoints/streaming/`** + rather than extending `fastvideo/entrypoints/openai/` (PR 5.5). + +## Per-PR commit-level detail + +For per-PR commit lists, test plans, and merge criteria, the archived +source [`source-archive/PR-plan.md`](source-archive/PR-plan.md) (1145 lines) +remains the deepest reference. This file is the navigable summary. diff --git a/.agents/memory/dreamverse-integration/quantization.md b/.agents/memory/dreamverse-integration/quantization.md new file mode 100644 index 0000000000..e68e7e4df5 --- /dev/null +++ b/.agents/memory/dreamverse-integration/quantization.md @@ -0,0 +1,229 @@ +# Quantization — NVFP4, LinearBase Fallback, Layer Profiles + +What landed in the May 2 NVFP4 stack, why it's load-bearing, and what's +still owed (`layer_profile`, typed quant carrier, AbsMaxFP8 cleanup). + +For overall API design see [design.md](design.md). For the open +follow-ups see [open-threads.md](open-threads.md). + +**Last updated:** 2026-05-03. + +## NVFP4 — what it is + +NVIDIA's specific block-scaled FP4 format: + +- e2m1 mantissa +- fp32 alpha +- `layout_128x4` scale layout +- group size 16 + +Distinct from MX-FP4 / OCP-FP4 / generic e3m0. The May 2 rename +(`94c983a2`) disambiguated the naming throughout FastVideo's public +surface. + +## Files (current) + +| File | Role | +|---|---| +| [`fastvideo/layers/quantization/nvfp4_config.py`](file:///home/william5lin/FastVideo/fastvideo/layers/quantization/nvfp4_config.py) | `NVFP4Config`, `NVFP4QuantizeMethod`, `convert_model_to_nvfp4` | +| [`fastvideo/layers/quantization/__init__.py`](file:///home/william5lin/FastVideo/fastvideo/layers/quantization/__init__.py) | `QuantizationMethods` literal includes `"NVFP4"`; `get_quantization_config` resolves it | +| [`fastvideo/layers/linear.py`](file:///home/william5lin/FastVideo/fastvideo/layers/linear.py) | `LinearBase.__init__` falls back to `UnquantizedLinearMethod` when `quant_config.get_quant_method` returns None — **load-bearing** | +| [`fastvideo/models/loader/fsdp_load.py`](file:///home/william5lin/FastVideo/fastvideo/models/loader/fsdp_load.py) | `_maybe_convert_model_to_nvfp4` helper detects via `isinstance(quant_method, NVFP4QuantizeMethod)`; calls `convert_model_to_nvfp4` to materialize buffers | +| [`fastvideo/models/dits/ltx2.py`](file:///home/william5lin/FastVideo/fastvideo/models/dits/ltx2.py) | `nn.Linear` → `ReplicatedLinear` for FP4-eligible subset; `_supports_prequantized_input` + `_linear_project_with_optional_prequant` helpers; quant_config + prefix= plumbing | +| [`fastvideo/api/compat.py`](file:///home/william5lin/FastVideo/fastvideo/api/compat.py) | Typed `engine.quantization.transformer_quant: "NVFP4"` resolves to `NVFP4Config()` instance | +| [`fastvideo/fastvideo_args.py`](file:///home/william5lin/FastVideo/fastvideo/fastvideo_args.py) | `__post_init__._apply_transformer_quant` pins `pipeline_config.dit_config.quant_config = NVFP4Config()` | + +## Buffer naming (post-rename) + +| Old | New | +|---|---| +| `_fp4_weight` / `_fp4_alpha` | `_nvfp4_weight` / `_nvfp4_alpha` | +| `_weight_global_sf` | unchanged | +| `convert_model_to_fp4` | `convert_model_to_nvfp4` | +| `FP4QuantizeMethod` | `NVFP4QuantizeMethod` | +| `QuantizationMethods` literal `"FP4"` | `"NVFP4"` | + +Internal-scope torch op namespace `fastvideo_fp4::*` and +`_get_ltx2_fp4_stage_profile` deliberately left as-is — purely internal +naming that mirrors FastVideo-internal. + +## Layer set asymmetry — by design + +`NVFP4Config.fp4_layers` (default `layer_profile="refine"`) covers: + +- `attn1.{to_q,to_k,to_v,to_out}` — full self-attention +- `attn2.{to_q,to_out}` — cross-attn Q + out only (text context not quantized) +- `audio_to_video_attn.{to_q,to_out}` — AV cross Q + out +- `video_to_audio_attn.{to_k,to_v}` — VA cross K + V +- `ffn.{fc_in,fc_out}` — video FFN +- `adaln_single.linear` — but this is `nn.Linear` (not `LinearBase`), + so it never actually gets FP4'd. List entry has no effect; matches + internal. + +**NOT in the set:** + +- audio self-attention (`audio_attn1.*`) +- audio cross-attention (`audio_attn2.*`) +- audio FFN (`audio.ffn.*`) + +Audio path is cheap enough that quant overhead isn't worth it. Test +[`test_basic_av_block_propagates_quant_config_to_all_children`](file:///home/william5lin/FastVideo/fastvideo/tests/ops/quantization/test_nvfp4_ltx2_wiring.py) +locks this in — if you add audio quantization later, update the test. + +## `LinearBase` fallback — DO NOT REMOVE + +[`fastvideo/layers/linear.py:191-202`](file:///home/william5lin/FastVideo/fastvideo/layers/linear.py#L191-L202): when `quant_config.get_quant_method` returns +`None` (layer not in the quant config's set), we fall back to +`UnquantizedLinearMethod`. + +**Removing this fallback would break every non-tagged +`ReplicatedLinear` constructed with an `NVFP4Config`** — the previous +`assert quant_method is not None` would crash on unmatched layers (e.g. +text-encoder K/V projections, audio attention, etc.). + +This is one of the load-bearing changes from `42b30bf9`. + +## `transformer_quant` precedence rules + +`FastVideoArgs._apply_transformer_quant` only writes +`dit_config.quant_config` when it's currently `None`. **If a caller has +explicitly set** `pipeline_config.dit_config.quant_config = NVFP4Config(...)`, +the explicit setter wins. + +Dreamverse's `video_generation.py` relies on this precedence — it sets +`NVFP4Config()` directly via `experimental["pipeline_config"]` because +typed `transformer_quant: "NVFP4"` doesn't yet expose `layer_profile`. +See "Open follow-ups" below. + +## Attention forward optimization + +[`models/dits/ltx2.py`](file:///home/william5lin/FastVideo/fastvideo/models/dits/ltx2.py) +ports `_supports_prequantized_input` and +`_linear_project_with_optional_prequant`. Attention forward +pre-quantizes input once (`quantize_input`), reuses the +`(x_fp4, x_scale, x_global_sf)` tuple for k/v projections when +`context is x` — bit-matches internal's fused path. + +## `prepare_for_compile` protocol + +[`composed_pipeline_base._maybe_compile_pipeline_module`](file:///home/william5lin/FastVideo/fastvideo/pipelines/composed_pipeline_base.py) +calls `getattr(module, "prepare_for_compile", None)` before invoking +`torch.compile`. Defined as a duck-type protocol — no base class method. + +Currently only **Gemma3** implements it (to materialize HF weights +outside Dynamo's tracer). Add to other models that have lazy external +state if you observe compile-time graph breaks. + +## Per-component compile flags + +`CompileConfig` (in +[`fastvideo/api/schema.py`](file:///home/william5lin/FastVideo/fastvideo/api/schema.py)) +gained per-component knobs in `221cb20a`: + +```python +@dataclass +class CompileConfig: + enabled: bool = False # master DiT switch + backend: str = "inductor" + fullgraph: bool = False + mode: str | None = None + dynamic: bool | None = None + extras: dict = field(default_factory=dict) + + # Per-component overlays, None = inherit master `enabled` + text_encoder_enabled: bool | None = None + vae_enabled: bool | None = None + audio_vae_enabled: bool | None = None + + # Per-component kwargs override master when non-empty + dit_kwargs: dict = field(default_factory=dict) + text_encoder_kwargs: dict = field(default_factory=dict) + vae_kwargs: dict = field(default_factory=dict) + audio_vae_kwargs: dict = field(default_factory=dict) +``` + +**`transformer_refine` is auto-compiled with the master DiT flag.** No +separate `enable_torch_compile_refine` flag — by design, refine inherits +DiT compile state to keep typed surface small. Decoupling would add a +new flag, not repurpose existing ones. + +## Quantization commit chain (`will/ltx2_sr_port`) + +| Commit | Locks in | +|---|---| +| `365a66c7 feat(quantization): upstream LTX-2 FP4Config with lazy flashinfer` | Public colocation of FP4Config (resolves dreamverse_review Q-6 option 1); flashinfer lazy-imported in loader helper, no public hard-dep | +| `a4760bae fix(api): propagate generic refine_*` | `_resolve_refine_args()` copies generic `refine_*` knobs onto `ltx2_refine_*` runtime carriers; `_randn_ltx2_video_latents` reverts to `torch.randn` to bit-match internal under single-generator inference | +| `221cb20a feat(api): typed per-component CompileConfig` | `CompileConfig` per-component knobs; matching `FastVideoArgs` carriers; compat layer round-trip | +| `6da342ba feat(compile): per-component compile + transformer_refine + prepare hook` | `composed_pipeline_base.post_init` compiles `transformer_refine` alongside `transformer`/`transformer_2`; per-component compile loops; `prepare_for_compile` hook on Gemma3 | +| `42b30bf9 feat(ltx2): wire FP4 inference` (largest) | `nn.Linear` → `ReplicatedLinear` for FP4-eligible LTX2 subset; `quant_config` + `prefix=` plumbing; `_maybe_convert_model_to_nvfp4` helper; `LinearBase` fallback to `UnquantizedLinearMethod`; typed `transformer_quant` resolution | +| `94c983a2 refactor(quant): rename FP4 → NVFP4` | Mechanical rename across config, methods, buffers, tests | +| `c6c14c55 test(nvfp4): lock LTX-2 wiring + typed transformer_quant flow` | 6+4 tests in `test_nvfp4_ltx2_wiring.py` + `test_typed_quant_flow.py` | +| `a5fcd19c [fix]: lazy-import flash_attn 2 fallback in attention backend` | post-handoff: lazy import to avoid hard flash_attn 2 dep | +| `d4ee5be2 [fix]: avoid model.to() round-trip in Gemma encoder forward` | post-handoff: parity / perf fix | +| `156103b9 [fix]: unwrap list-of-generator before torch.randn in LTX-2 latent prep` | post-handoff: parity fix for list-of-generators (was bit-matching only single-generator path) | + +## Tests + +| Test | Asserts | +|---|---| +| [`fastvideo/tests/ops/quantization/test_nvfp4_ltx2_wiring.py`](file:///home/william5lin/FastVideo/fastvideo/tests/ops/quantization/test_nvfp4_ltx2_wiring.py) (6 tests) | `LTXSelfAttention.to_q/to_k/to_v/to_out` are `ReplicatedLinear`; `NVFP4Config()` attaches `NVFP4QuantizeMethod` on the quantized subset with correct `layer_prefix`; non-tagged projections (cross-attn K/V, audio attn, audio FFN) fall back to `UnquantizedLinearMethod`; `BasicAVTransformerBlock` propagates `quant_config`+`prefix` correctly to all 4 attention modules + FFN | +| [`fastvideo/tests/api/test_typed_quant_flow.py`](file:///home/william5lin/FastVideo/fastvideo/tests/api/test_typed_quant_flow.py) (4 tests) | typed `engine.quantization.transformer_quant: "NVFP4"` → `NVFP4Config()` instance flow; default leaves `transformer_quant` None; explicit `dit_config.quant_config = ...` wins over typed carrier | + +CPU-only by design; do NOT exercise actual FP4 kernels (no flashinfer in +CI). Real kernel coverage requires a CI run with flashinfer installed. + +## Open follow-ups (quantization-specific) + +### #4: Expose `layer_profile` on typed `engine.quantization` + +Today `transformer_quant: "NVFP4"` always constructs `NVFP4Config()` +with default `layer_profile="refine"`. To support stage-1 profiles (no +`attn2.to_out`, no cross-modal AV) via typed config, add +`transformer_quant_layer_profile: str | None = None` and thread it +through: + +- `fastvideo/api/schema.py` — `QuantizationConfig` field +- `fastvideo/api/compat.py` — typed → flat translation +- `fastvideo/fastvideo_args.py` — `_apply_transformer_quant` consumes it + +Dreamverse currently dodges this by setting `NVFP4Config()` directly via +`experimental["pipeline_config"]`. Exposing `layer_profile` removes the +dodge. See [open-threads.md](open-threads.md) #4. + +### #5: Typed `dit_config.quant_config` carrier (replace `experimental["pipeline_config"]`) + +Long-term: design a typed home for an in-memory `PipelineConfig` +instance with mutated `dit_config`. Today `compat.py` recognizes the +`pipeline_config` key in `experimental` and threads it through to +`FastVideoArgs.from_kwargs`. This is fine for short-term but not pretty. + +Heaviest design work in the open queue. May need Oracle consult. + +### #2: AbsMaxFP8 pre-existing test failure + +`fastvideo/tests/ops/quantization/test_absmax_fp8.py::test_create_weights_rejects_invalid_dtype` +fails on `main` and on `will/ltx2_sr_port` with the same error +(`AssertionError not raised`). Verified via `git stash` that the +failure pre-dates NVFP4 work. + +Either: +- Fix the test (`AbsMaxFP8LinearMethod.create_weights` no longer + asserts on invalid dtype — restore the assert if intentional, or drop + the test). + +Self-contained tech debt; small fix. + +## Don't / Cautions + +- **Don't change `NVFP4Config` buffer names back to `_fp4_*`.** Rename + is intentional to disambiguate from MX-FP4 / OCP-FP4. +- **Don't remove the `LinearBase` `UnquantizedLinearMethod` fallback.** + Load-bearing for non-tagged layers when a `quant_config` is set. +- **Don't repurpose `enable_torch_compile` to mean DiT-only.** It also + drives `transformer_refine` and `transformer_2` compile. +- **Don't bypass the typed surface for new options.** New compile / + quant / refine knobs should land on the dataclass + compat.py + + parity inventory together. The existing test suite locks this in. +- **Don't merge to main without a CI run that covers FP4.** Current CI + doesn't run flashinfer-dependent paths; the wiring tests are CPU-only + by design. diff --git a/.agents/memory/dreamverse-integration/runbook.md b/.agents/memory/dreamverse-integration/runbook.md new file mode 100644 index 0000000000..4dcf134c3b --- /dev/null +++ b/.agents/memory/dreamverse-integration/runbook.md @@ -0,0 +1,385 @@ +# Runbook — How to Do Work in This Scope + +Operational how-to for the dreamverse-integration scope. Read after +[state.md](state.md) and [open-threads.md](open-threads.md). + +For design rationale see [design.md](design.md). For who to credit see +[authors.md](authors.md). For PR status see [pr-roadmap.md](pr-roadmap.md). + +**Last updated:** 2026-05-05 (strategy reversed to single mega-PR #1288 on `will/ltx2_sr_port`; #1287 closed; STACK.md split model deprecated per [decisions-log.md D-17](decisions-log.md#d-17)). + +## Worktree contract + +``` +Repo: /home/william5lin/FastVideo +Branch: will/ltx2_sr_port +``` + +Other agents and the user share this worktree concurrently. If `git status` +shows changes you don't recognize, they belong to **someone else's work** — +don't revert, don't `git stash drop`, don't `git checkout -- `. +Switch to `will/ltx2_sr_port` cleanly with `git checkout will/ltx2_sr_port` +(safe if your own working tree is clean) and proceed. + +If your task requires a different branch (e.g. cherry-pick to +`will/api_7.9` for PR #1286 propagation), return to `will/ltx2_sr_port` +when done — that is the assumed default. + +## Branch topology (single mega-PR model) + +The dreamverse-integration work now ships as one PR (#1288) off +`will/ltx2_sr_port`. The split-PR model documented in earlier revisions +of this runbook (and in top-level `STACK.md`) is **abandoned** — +see [decisions-log.md D-17](decisions-log.md#d-17). + +``` +origin/main + ↓ [public-API refactor: PRs 0..7.9 merged on main, latest #1286 = 2aaeee2a] +will/ltx2_sr_port (**PR #1288 head** — single mega-PR, 34 commits, 71 files, +13,074/-583) +``` + +| Branch | Role | Status | +|---|---|---| +| `will/ltx2_sr_port` | **PR #1288 head**, default working branch | OPEN, MERGEABLE | +| `will/api_7.10` / `will/api_8` / `will/ltx2_sr_runtime` / `will/ltx2_nvfp4` / `will/ltx2_post_fixes` / `will/agents_cleanup` | deprecated split-PR bookmarks | local-only historical references; safe to delete | +| `will/ltx2_sr_port-pre-1286-rebase` | safety backup | local-only; preserves the 4 commits dropped during the post-#1286 rebase | + +**Sanity check:** `git merge-base --is-ancestor origin/main will/ltx2_sr_port` +should exit 0. If it doesn't, the branch is in an unexpected state — read +[state.md](state.md) before continuing. + +## After PR #1288 merges + +When the mega-PR squash-merges into `main`: + +1. `git fetch origin main` to pull the merge commit. +2. The entire `will/ltx2_sr_port` content is now on main; the branch can + be deleted (locally + on origin) once all consumers are notified. +3. Delete deprecated split bookmarks: `git branch -D will/api_7.10 + will/api_8 will/ltx2_sr_runtime will/ltx2_nvfp4 will/ltx2_post_fixes + will/agents_cleanup` (local-only, no remote). +4. Optionally remove top-level `STACK.md` (now a historical artifact). + Keep `CO-AUTHORS.md` — still the canonical roster reference. +5. Decide whether to keep `will/ltx2_sr_port-pre-1286-rebase` (safety + backup of the pre-rebase chain) — recommend deleting once #1288 is + merged and verified on main. +6. Update memory dir to reflect the post-merge state — bump + `Last reconciled` headers, mark Item D resolved in + [open-threads.md](open-threads.md), record the merge commit in + [decisions-log.md](decisions-log.md). + +## Historical: split-PR re-slice protocol (deprecated) + +Prior revisions of this runbook documented a 10-step re-slice protocol +for the abandoned 6-PR split model. That protocol is now obsolete. +The post-#1286 rebase (2026-05-05) was the last execution of it; details +are preserved in [state.md](state.md) "Post-#1286 rebase summary" and +git history at commit `b34d9704`. + +## Verification + +### Lint (pre-commit) + +```bash +pre-commit run --files +``` + +- Binary: `/home/william5lin/miniconda3/envs/fv-main/bin/pre-commit`. + NOT `.venv/bin/pre-commit` — that doesn't exist in this worktree. +- Auto-applies yapf reformatting; re-stage modified files after. +- Hook chain: yapf → ruff → codespell → mypy → spaces-check. +- Memory dir (`.agents/memory/`) is yapf/ruff/mypy excluded — only + "spaces" runs. Memory edits don't need lint, but DO use UTF-8 and + consistent line endings. + +### Tests + +Router tests (PR #1286 scope): +```bash +.venv/bin/python -m pytest fastvideo/tests/entrypoints/streaming/test_router.py -v --no-header +``` + +Stack baseline (May 2 handoff suite — re-run when you change anything in +api/, contract/, or LTX-2 paths): +```bash +.venv/bin/python -m pytest \ + fastvideo/tests/api/ \ + fastvideo/tests/contract/ \ + fastvideo/tests/ops/quantization/test_nvfp4_*.py \ + tests/local_tests/pipelines/test_ltx2_pipeline_smoke.py \ + -q --no-header +``` + +Expected baselines: +- May 2 handoff (`156103b9`): 222 passed, 1 skipped. +- Post-D-16 (`a152cb77` / `09647a30`): +7 router tests pass on top. + +### LSP + +Use `lsp_diagnostics` on changed files BEFORE running build. Pre-existing +warnings to ignore (predate this work): + +- `fastvideo/entrypoints/streaming/router/main.py:37` — `Task` generic. +- `fastvideo/entrypoints/cli/router_serve.py:55` — `_SubParsersAction` generic. + +### gh CLI for PR status + +```bash +# PR #1286 quick status +gh pr view 1286 --json headRefOid,mergeable,statusCheckRollup \ + --jq '{headRefOid, mergeable, checks: [.statusCheckRollup[] | {name, status, conclusion}]}' + +# All commits in a PR + co-author check +gh pr view 1286 --json commits \ + --jq '.commits[] | {oid: .oid[0:8], msg: .messageHeadline, author: .authors[0].login}' +``` + +## Commit workflow + +### Subject convention + +`[type] : ` — keep ≤ 72 chars. + +Types observed in this scope: `feat`, `fix`, `test`, `docs`, `chore`, +`refactor`. Scopes observed: `streaming`, `dreamverse-integration`, +`api`, `quant`, `ltx2`, `nvfp4`, etc. + +Examples: +- `[fix] streaming: router polish — bridge cancel + state machine + deps` +- `[docs] dreamverse-integration: add authors.md + track D-16 router polish` + +### Body convention + +Bullet list, one bullet per file or concern. Why-before-what. Wrap at +~80 chars (yapf doesn't reformat commit messages; readability is on you). + +### Co-author trailers (REQUIRED on every commit) + +The 4 trailers in [authors.md](authors.md) MUST appear on every commit +in this scope. Use `--trailer` flags or write the body to a file with +`-F` — DO NOT use multiple `-m` blocks for the trailers (each `-m` is +its own paragraph and git's trailer parser only reads the LAST paragraph, +yielding 1 trailer parsed instead of 4). + +**Inline `--trailer` form (preferred for short commits):** + +```bash +git commit -m "subject" -m "body..." \ + --trailer "Co-authored-by: Junda (David) Su <90978028+Davids048@users.noreply.github.com>" \ + --trailer "Co-authored-by: Matthew Noto <99706358+RandNMR73@users.noreply.github.com>" \ + --trailer "Co-authored-by: XOR-op <17672363+XOR-op@users.noreply.github.com>" \ + --trailer "Co-authored-by: Zhang Peiyuan <42993249+jzhang38@users.noreply.github.com>" +``` + +**File form (preferred for multi-paragraph bodies):** + +```bash +cat > /tmp/opencode/msg.txt <<'EOF' +[type] scope: subject + +* Bullet one with rationale. +* Bullet two with rationale. + +Co-authored-by: Junda (David) Su <90978028+Davids048@users.noreply.github.com> +Co-authored-by: Matthew Noto <99706358+RandNMR73@users.noreply.github.com> +Co-authored-by: XOR-op <17672363+XOR-op@users.noreply.github.com> +Co-authored-by: Zhang Peiyuan <42993249+jzhang38@users.noreply.github.com> +EOF +git commit -F /tmp/opencode/msg.txt +``` + +The trailers MUST be a single block at the end of the message with no +blank lines between them. + +**Verify trailers parsed:** + +```bash +git log -1 --format='%(trailers:key=Co-authored-by,valueonly)' +``` + +Should print 4 lines (one per author). If only 1 line, you have the +multi-`-m` bug — amend with `-F` to fix (allowed if commit is unpushed +and you authored it in this session per AGENTS.md amend rules). + +### NEVER add to commits + +Per [`AGENTS.md`](../../../AGENTS.md): + +- AI co-authors (Claude, GPT, Codex, Cursor, etc.) — explicitly forbidden +- "Generated with Claude Code" footer — explicitly forbidden +- `--no-verify` to skip pre-commit — explicitly forbidden + +## Push + PR propagation + +### Pushing `will/ltx2_sr_port` (top of stack) + +```bash +git push origin will/ltx2_sr_port # fast-forward, no force needed +``` + +If git wants to force-push, you've rewritten history. STOP and verify: + +```bash +git log origin/will/ltx2_sr_port..will/ltx2_sr_port # local-only commits +git log will/ltx2_sr_port..origin/will/ltx2_sr_port # remote-only commits +``` + +Force-push requires explicit user confirmation per `AGENTS.md`. + +### Propagating fixes to PR #1286 (`will/api_7.9`) + +When a fix is in router code (`fastvideo/entrypoints/streaming/router/`, +`cli/router_serve.py`, `tests/entrypoints/streaming/test_router.py`, +or `pyproject.toml` router-related), it must land on BOTH branches. +Cherry-pick avoids any force-push: + +```bash +# 1. Commit on will/ltx2_sr_port first (working branch) +git add +git commit -F /tmp/opencode/msg.txt # with trailers per above + +# 2. Cherry-pick onto will/api_7.9 (creates a separate SHA, identical diff) +git checkout will/api_7.9 +git cherry-pick +git push origin will/api_7.9 # fast-forward, no force + +# 3. Return to working branch +git checkout will/ltx2_sr_port + +# 4. Verify PR #1286 picked it up +gh pr view 1286 --json headRefOid --jq '.headRefOid' +``` + +Two SHAs for the same diff — they'll dedupe naturally on the next +bulk-rebase via the trailer-injection rebase command in +[authors.md](authors.md). + +### When a fix is memory-dir-only + +`.agents/memory/dreamverse-integration/` lives in the `agents_cleanup` +layer of the stack — it does NOT belong on `will/api_7.9`. Memory updates +stay on `will/ltx2_sr_port` only. + +### When a fix is non-router code in the integration scope + +Land on `will/ltx2_sr_port`. If that fix needs to ship as a separate PR +(e.g. extending PR 7.10 or starting PR 9), open a new branch off the +right base per [pr-roadmap.md](pr-roadmap.md). + +## Memory dir maintenance + +When state changes, update the memory dir BEFORE moving on. Every file +has a "Last updated" header — bump when you edit. + +| Change | File to update | +|---|---| +| Branch tip moves | [state.md](state.md) "Branch tips" + "Last reconciled" | +| PR opens / merges | [pr-roadmap.md](pr-roadmap.md) status table | +| New decision made | [decisions-log.md](decisions-log.md) — add D-N entry, bump header | +| Open thread resolved | [open-threads.md](open-threads.md) — strikethrough + "Resolved" note | +| New open thread | [open-threads.md](open-threads.md) — priority overview + section | +| New collaborator credited | [authors.md](authors.md) roster + trailer block + bulk-rebase | +| Source doc archived | [source-archive/README.md](source-archive/README.md) + [README.md](README.md) sources table | +| Process / runbook detail changes | [runbook.md](runbook.md) (this file) | + +Cross-link siblings via relative paths. Never duplicate content — link. + +## Common pitfalls + +### `pre-commit` not in `.venv/bin` + +`pre-commit` lives at `/home/william5lin/miniconda3/envs/fv-main/bin/pre-commit`. +The `.venv` here is for the FastVideo package itself, not pre-commit. + +### Trailers split across paragraphs + +`git commit -m A -m B -m C` makes A, B, C separate paragraphs. Git's +trailer parser only reads the LAST paragraph — multiple `-m +"Co-authored-by: ..."` produces 1 trailer parsed, not 4. Use `--trailer` +flags or `-F` with the trailers in a single block at the end. + +### Stash 0 on FastVideo IS NOT yours + +`stash@{0}: WIP on main: 71bfc13d HunyuanVideo plugin` predates this work. +**DO NOT POP.** See [state.md](state.md) "Stashes — DO NOT POP". + +### `AbsMaxFP8` test "failure" is pre-existing + +`fastvideo/tests/ops/quantization/test_absmax_fp8.py::test_create_weights_rejects_invalid_dtype` +fails on `main` and on every branch in this scope. NOT introduced by +integration work. See [open-threads.md](open-threads.md) item #2. + +### Untracked nested clones at repo root + +`dynamo/`, `ray/`, `vllm-omni/` are untracked nested git clones at the +FastVideo repo root. Reference repos for cross-repo work. **Do not +`rm -rf`** — they're someone else's working state. + +### Live services on 8009 / 5274 + +`dreamverse-server` runs on 8009 (warmed GPU worker), Next.js dev server +on 5274. Don't start new instances on those ports without checking +[state.md](state.md) "Live services" first. + +### Branch may have been switched by another agent + +Other agents share this worktree. If `git branch --show-current` returns +something other than `will/ltx2_sr_port`, switch back cleanly with +`git checkout will/ltx2_sr_port` — don't disturb their work, don't +discard their uncommitted changes. + +### Force-push policy + +Per `AGENTS.md`: never force-push without explicit user confirmation. +For trailer fixes on already-pushed commits, prefer the bulk-rebase +command in [authors.md](authors.md) — safe to re-run. + +### Two trailerless commits in PR #1286 + +`a152cb77` (on `will/api_7.9`) and `40e265b8` (now-superseded ancestor +on `will/ltx2_sr_port`) lack the 4 co-author trailers. **Accepted gap** +per user decision — see [authors.md](authors.md) "Known gaps". + +## Self-test (verify your context is loaded) + +After reading the memory dir, you should be able to answer: + +1. What branch should I be on? → `will/ltx2_sr_port` +2. What's the active open PR in this scope? → #1286 on `will/api_7.9` +3. Where does PR #1286 land in the stack? → Bottom; ancestor of `will/ltx2_sr_port` +4. Who do I credit on every commit? → 4 authors per [authors.md](authors.md) +5. Where do memory updates land? → `will/ltx2_sr_port` only (NOT api_7.9) +6. What's the next-priority open thread? → See [open-threads.md](open-threads.md) "Recommended pull order" — D-8 verify is current top +7. What pre-existing failure can I ignore? → AbsMaxFP8 test (item #2) +8. What's the bulk-rebase command for adding trailers across the stack? → See [authors.md](authors.md) "How the trailers were applied" + +If you can't answer one of these from the memory dir alone, the dir has +a gap — file it as a new entry in [open-threads.md](open-threads.md) +before continuing. + +## First 60 seconds — copy-paste orientation + +```bash +# 1. Confirm branch +cd /home/william5lin/FastVideo +git branch --show-current # should print: will/ltx2_sr_port +# If not, recover: git checkout will/ltx2_sr_port + +# 2. Confirm worktree clean (untracked nested clones expected) +git status --short + +# 3. Confirm PR #1286 head matches expected api_7.9 tip +gh pr view 1286 --json headRefOid --jq '.headRefOid' +git rev-parse will/api_7.9 # should match PR head + +# 4. Confirm your context vs the memory dir +git log -1 --oneline +cat .agents/memory/dreamverse-integration/state.md | head -30 + +# 5. Confirm live services still running +curl -s http://localhost:8009/readyz | head -c 200 +curl -s http://localhost:5274/ -o /dev/null -w "%{http_code}\n" +``` + +If any of those produce unexpected output, read [state.md](state.md) +before changing anything. diff --git a/.agents/memory/dreamverse-integration/source-archive/PR-plan.md b/.agents/memory/dreamverse-integration/source-archive/PR-plan.md new file mode 100644 index 0000000000..8b4d9a0f81 --- /dev/null +++ b/.agents/memory/dreamverse-integration/source-archive/PR-plan.md @@ -0,0 +1,1145 @@ +# FastVideo API Refactor PR Plan + +## Related Documents +- [apirefactor.md](apirefactor.md) — design spec this plan implements +- [.agents/exploration/streaming-server-upstream-plan.md](.agents/exploration/streaming-server-upstream-plan.md) — plan for upstreaming the internal LTX2 streaming server and Dynamo backend contract (shapes PRs 5.5-7.10) +- `../FastVideo-internal/.agents/exploration/rebase-upstream-fastvideo.md` — rebasing FastVideo-internal onto upstream (in progress; enables PRs 6-8) +- `../FastVideo-internal/ui/ltx2-streaming/` — upstream source for streaming server (server/, gpu_pool.py, prompt_enhancer.py, router/) +- `../dynamo/` — local clone of ai-dynamo/dynamo; backend shape at `components/src/dynamo/sglang/` is the template for the FastVideo native backend consumed in PR 7.10 +- https://github.com/ai-dynamo/dynamo/pull/7544 — draft PR (CLOSED) that promotes FastVideo to a native Dynamo backend; establishes the contract this plan must satisfy + +## Status + +Working plan for implementing the design in [apirefactor.md](apirefactor.md). + +### PR Landing History + +Landed: +- PR 0 + PR 1 as `[1/n]` (#1218) on `main` — parity inventory + typed inference schema + strict parser/validation/overrides + API test suite +- PR 2 as `[2/n]` (#1220) on `main` — typed `VideoGenerator` constructors and request path + compatibility translation +- PR 3 as `[3/n]` (#1226) on `main` — CLI/YAML-first typed config loading for `generate` and `serve` +- PR 4 as `[4/n]` (#1234) on `main` — preset registry + presets for all 13 model families; `SamplingParam` moved to `fastvideo/api/`; `fastvideo/configs/sample/` deleted entirely +- PR 5 as `[5/n]` (#1237) on `main` — `ServeConfig.default_request` wired into the stateless OpenAI server +- PR 5.5 as `[5.5/n]` (`5d1d71fc`) on `will/api_5.5` — streaming server package skeleton, typed `StreamingConfig`/`GpuPoolConfig`/`PromptEnhancerConfig`/`PromptSafetyConfig`/`WarmupConfig`, `streaming-serve` CLI stub +- PR 6 as `[6/n]` (#1239) on `main` — LTX2 public preset + asset wiring + gpu_pool translation +- PR 7 as `[7/n]` (#1250) on `main` — typed LTX2 continuation state + streaming session store + blob store + +In progress: +- PR 7.5 (#1251) on `will/api_7.5` — streaming server skeleton (WebSocket + fMP4 + single generator). Open for review. +- PR 7.6 on `will/api_7.6` — GPU pool upstream. Branch ready, not yet PR'd; rebased on `will/api_7.5`. + +Remaining (PR 7.7 onward): +- PR 7.7: prompt enhancer upstream with `LLMProvider` abstraction +- PR 7.8: streaming auxiliaries (prompt safety, session logger, mock server, rewrite) +- PR 7.9: router upstream +- PR 7.10: Dynamo backend contract — `VideoGenerator.generate_async` + health-check helper; the Dynamo backend package itself lives in the Dynamo repo +- PR 8: internal-UI ↔ public-server contract docs + Dynamo integration reference +- PR 9: LongCat preset migration + colocation +- PR 10: Hunyuan15 SR preset migration + colocation + SR field migration POC +- PR 11: SSIM/performance test migration +- PR 12: docs/examples migration (includes streaming server + Dynamo) +- PR 13: deprecation cleanup (includes flat LTX2 kwargs the internal gpu_pool used to consume) + +PRs 5.5-7.10 are driven by the decision to upstream `FastVideo-internal/ui/ltx2-streaming/server/` into the public repo; see [streaming-server-upstream-plan.md](.agents/exploration/streaming-server-upstream-plan.md). + +### Landed Artifacts + +Reference points for later PRs: + +- parity inventory: [inference_schema_parity_inventory.yaml](/home/william5lin/FastVideo/docs/design/inference_schema_parity_inventory.yaml) + guard [test_schema_parity_inventory.py](/home/william5lin/FastVideo/fastvideo/tests/api/test_schema_parity_inventory.py) +- typed public schema: [schema.py](/home/william5lin/FastVideo/fastvideo/api/schema.py) +- parser / validation / overrides: [parser.py](/home/william5lin/FastVideo/fastvideo/api/parser.py), [errors.py](/home/william5lin/FastVideo/fastvideo/api/errors.py), [overrides.py](/home/william5lin/FastVideo/fastvideo/api/overrides.py) +- compatibility translation + typed result: [compat.py](/home/william5lin/FastVideo/fastvideo/api/compat.py), [results.py](/home/william5lin/FastVideo/fastvideo/api/results.py) +- typed `VideoGenerator`: [video_generator.py](/home/william5lin/FastVideo/fastvideo/entrypoints/video_generator.py) +- CLI typed config loading: [inference_config.py](/home/william5lin/FastVideo/fastvideo/entrypoints/cli/inference_config.py), [generate.py](/home/william5lin/FastVideo/fastvideo/entrypoints/cli/generate.py), [serve.py](/home/william5lin/FastVideo/fastvideo/entrypoints/cli/serve.py), [main.py](/home/william5lin/FastVideo/fastvideo/entrypoints/cli/main.py) +- preset system: [presets.py](/home/william5lin/FastVideo/fastvideo/api/presets.py) plus `fastvideo/pipelines/basic//presets.py` for all 13 families (Wan, LTX2, Hunyuan, Hunyuan15, HYWorld, GameCraft, LingBotWorld, MatrixGame, GEN3C, Cosmos, Cosmos25, SD35, TurboDiffusion, LongCat); `model_family` + `default_preset` on `ConfigInfo` in [registry.py](/home/william5lin/FastVideo/fastvideo/registry.py) +- `SamplingParam` canonical home: [sampling_param.py](/home/william5lin/FastVideo/fastvideo/api/sampling_param.py) — all 12 subclass files removed; defaults flow through `SamplingParam.from_pretrained()` → `_from_preset()` +- API test suite: [fastvideo/tests/api](/home/william5lin/FastVideo/fastvideo/tests/api) (98+ tests) +- streaming package + config types (PR 5.5): `fastvideo/entrypoints/streaming/` +- LTX2 preset + asset wiring + typed pipeline / refine config (PR 6): `fastvideo/pipelines/basic/ltx2/`, `fastvideo/api/schema.py` typed `pipeline.preset_overrides`/`pipeline.components`, `compile.extras`, `gpu_pool.py` translation +- LTX2 typed continuation state (PR 7): [`fastvideo/pipelines/basic/ltx2/continuation.py`](/home/william5lin/FastVideo/fastvideo/pipelines/basic/ltx2/continuation.py) with `LTX2ContinuationState`, `_pack_frame_blobs`/`_unpack_frame_blobs` (bounds-checked), public `ContinuationState` envelope on `GenerationRequest`, `register_continuation_kind` registry validation in [`compat.py`](/home/william5lin/FastVideo/fastvideo/api/compat.py) +- streaming session + blob stores (PR 7): [`fastvideo/entrypoints/streaming/session_store.py`](/home/william5lin/FastVideo/fastvideo/entrypoints/streaming/session_store.py) + +### Notable Decisions Carried Forward From Landed PRs + +- public inference boundary remains plain dataclasses + plain dict/YAML/JSON (not OmegaConf or runtime config wrappers) +- every public entrypoint normalizes into typed config objects before touching legacy `FastVideoArgs` or `SamplingParam` +- legacy `generate_video(..., **kwargs)` stays on its direct legacy execution path until PR 11's SSIM/performance migration — prevents golden baselines from drifting during the compat period +- typed requests use schema defaults while legacy `generate_video(...)` continues to inherit model-specific `SamplingParam` defaults during the compat period +- preset registry uses an explicit `_register_presets()` pattern matching `_register_configs()`; lookup keyed by `model_family` +- stateless OpenAI server clones `ServeConfig.default_request` and merges user overrides; preset validation runs before legacy generation +- streaming server added as sibling `fastvideo/entrypoints/streaming/` rather than extending `fastvideo/entrypoints/openai/` (PR 5.5 added only the package stub + typed config; live server lands in PRs 7.5-7.9) + +## Goals + +- Break the API refactor into reviewable PRs. +- Keep each PR testable and bisectable. +- Add explicit CI coverage for the new inference schema. +- Include the LTX2/Dreamverse upstream work as part of the rollout. +- Avoid one giant mixed refactor that is hard to land or debug. + +## Ground Rules + +- Every PR must leave the repo in a shippable state. +- Every PR must add or update tests with the code change. +- The new schema cannot freeze before a public-field parity inventory is reviewed. +- Compatibility shims stay in place until all downstream entrypoints are migrated. +- Every public inference entrypoint must normalize into typed config objects before touching legacy internals. +- LTX2 upstreaming should be staged so private Dreamverse behavior is not partially depended on before the public FastVideo API can represent it. +- Private Dreamverse-only fields should be translated in a private adapter layer, not silently turned into public FastVideo compatibility promises. +- GPU-heavy validation should remain in Buildkite or nightly jobs, but core API and config semantics must be covered by regular CI. +- Public inference terminology should use `config`, not `document`. +- The canonical public inference boundary should remain plain dataclasses plus plain dict/YAML/JSON, not OmegaConf objects or runtime-specific config wrappers. + +## Known Technical Debt + +Identified during PR 0-5.5 review; deferred to later PRs. + +### Model-specific fields in shared schema + +Most model-specific SamplingParam fields were promoted to base `SamplingParam` in PR 4 (LTX2 multi-modal CFG/STG, HYWorld attention masks, GameCraft camera/action control). These are classified as `preset_owned` in the parity inventory. + +`SamplingConfig` still contains fields used by only one or two model families: +- `height_sr`, `width_sr`, `num_inference_steps_sr` (Hunyuan15 SR) — target PR 10 +- `guidance_scale_2`, `boundary_ratio` (Wan2.2, LingBotWorld) + +`InputConfig` still contains model-specific conditioning fields: +- `mouse_cond`, `keyboard_cond`, `grid_sizes` (MatrixGame) +- `c2ws_plucker_emb` (LingBotWorld) +- `refine_from`, `stage1_video` (LongCat) — target PR 9 + +Target: migrate to preset-owned typed override classes or request extensions. + +### LTX2-specific defaults leaked onto shared `SamplingParam` (CFG-force fixed in PR 6; remaining fields still leak) + +**Fixed in PR 6**: `SamplingParam.ltx2_cfg_scale_video` / +`ltx2_cfg_scale_audio` class defaults were `3.0` / `7.0`, which tripped +`ForwardBatch.__post_init__`'s +`ltx2_text_cfg_enabled = (ltx2_cfg_scale_video != 1.0 or ltx2_cfg_scale_audio != 1.0)` +check → force-enabled `do_classifier_free_guidance` for every model +family whose preset didn't explicitly reset them. Surfaced as the +TurboDiffusion I2V SSIM crash +(`text_encoding.py:81` asserting `isinstance(batch.negative_prompt, str)`). +Defaults are now `1.0` (CFG off); `ltx2_base` preset already sets +`3.0`/`7.0` explicitly so its behavior is unchanged. Regression guard +at `test_presets.py::TestPresetDefaultTypes::test_ltx2_cfg_defaults_are_off`. + +**Still leaking (not fixed)**: `SamplingParam` still carries the other +LTX-2 multi-modal knobs — `ltx2_modality_scale_video`/`_audio`, +`ltx2_rescale_scale`, `ltx2_stg_scale_video`/`_audio`, +`ltx2_stg_blocks_video`/`_audio` — with LTX-2-on class defaults +(`3.0`/`3.0`/`0.7`/`1.0`/`1.0`/`[29]`/`[29]`). These only affect LTX-2 +denoising stages today (no cross-family code path reads them), so +there's no active bug, but they are still "model-specific fields in +shared schema" tech debt. + +**Consequence for existing LTX-2 reference videos**: `ltx2_distilled` +and `ltx2_two_stage` presets don't explicitly set +`ltx2_cfg_scale_video`/`_audio`, so they previously inherited +`3.0`/`7.0` (CFG accidentally on). After the default-change they +inherit `1.0`/`1.0` (CFG off). This matches the design intent for +few-step distilled variants but may shift SSIM output. Re-seed +`ltx2_distilled` + `ltx2_two_stage` references if the existing refs +fail threshold; alternatively, explicitly set the CFG fields on those +presets to preserve old behavior. + +**Remaining cleanup**: subsumed by the "Model-specific fields in +shared schema" entry above — migrate the still-leaking LTX-2 knobs +(`ltx2_modality_scale_*`, `ltx2_rescale_scale`, `ltx2_stg_*`) to a +typed `LTX2SamplingOverride` during the per-model migration sweep. + +### Escape hatch usage + +The compat layer (`compat.py:134`) routes unrecognized legacy kwargs into `generator.pipeline.experimental`, which `generator_config_to_fastvideo_args` dumps back into flat kwargs. This untyped pass-through should shrink as presets absorb model-specific fields; each model migration PR should review and reduce it. + +### Quantization code paths need a careful audit + +Before any public-API freeze, quantization routing needs end-to-end verification — this was not finished in PR 6 and several overlapping surfaces coexist: + +- `QuantizationConfig.text_encoder_quant` / `.transformer_quant` are string fields on `EngineConfig.quantization` (`api/schema.py`). +- `FastVideoArgs.override_text_encoder_quant` is a legacy flat kwarg that compat.py routes to the typed field above. +- Internal's `ui/ltx2-streaming/server/gpu_pool.py:220,231` skips those typed paths entirely and does `pipeline_config.dit_config.quant_config = FP4Config()` — a direct object mutation on the PipelineConfig instance before calling `VideoGenerator.from_pretrained`. +- `fastvideo/layers/quantization/fp4_config.py` is where the actual `FP4Config()` lives; the wiring from the string (`"fp4"`) to that class is not currently covered by any API-layer test. + +Open questions to resolve before freeze: +- Does `transformer_quant="fp4"` construct an `FP4Config()` end-to-end, or is the string path an unused vestige? +- Does `text_encoder_quant` have the same string→class wiring, or different semantics? +- When the realtime runtime (PR 7.6) drops the in-place `dit_config.quant_config = FP4Config()` mutation, which typed path replaces it? +- Should DiT, text-encoder, VAE, and image-encoder quant each be a separate typed field (current `QuantizationConfig` only has DiT + text-encoder)? + +Action: audit `fastvideo/layers/quantization/` ↔ `api/schema.QuantizationConfig` ↔ `FastVideoArgs` ↔ `PipelineConfig.*.quant_config` wiring in one sweep. Add an equivalence test (`"fp4"` string → same runtime behavior as `FP4Config()` instance) before PR 7.6 lands, or document a deliberate decision to keep the object-mutation path. + +### Scattered model-family config layout + +Each family's config is still spread across: +- `fastvideo/configs/pipelines/.py` — PipelineConfig subclasses (DiT, VAE, precision, flow_shift) +- `fastvideo/api/sampling_param.py` — base SamplingParam with promoted model-specific fields +- `fastvideo/pipelines/basic//` — pipeline + presets +- `fastvideo/pipelines/stages/` — model-specific stages mixed with shared stages + +PR 4 deleted `fastvideo/configs/sample/` entirely and moved defaults to `pipelines/basic//presets.py`. Remaining colocation targets: `configs/pipelines/.py` and model-specific stages in `pipelines/stages/`. See "Pipeline Package Structure" below. + +### Minor duplication + +`_serialize_config` in `request_metadata.py` duplicates `config_to_dict` in `parser.py`. Consolidate when convenient. + +## Config Layer Plan + +The repo should end up with fewer inference-facing config abstractions. Layers with distinct jobs: + +1. **Public Inference Config** — `fastvideo.api`: `GeneratorConfig`, `GenerationRequest`, `RunConfig`, `ServeConfig`, `ContinuationState`, preset selection, stage overrides. Stable API for Python, CLI, YAML/JSON, and OpenAI/server request normalization. Strict, typed, validated. + +2. **Legacy Inference Compatibility Config** — transitional internal layer: `FastVideoArgs`, `SamplingParam` (now at `fastvideo/api/sampling_param.py` with preset-based defaults), legacy inference-facing `PipelineConfig` usage. Shrinks as the runtime migrates to use the typed API directly. + +3. **Pipeline Preset / Default Config** — model-owned presets at `fastvideo/pipelines/basic//presets.py`. Engine/architecture config from `configs/pipelines/.py` should be **colocated** with pipeline implementations (`pipelines/basic//pipeline_configs.py`) but not absorbed by presets — those classes carry internal component wiring (DiT, VAE, precision) that is not user-facing. + +4. **Model Architecture / Component Config** — `fastvideo/configs/models/` stays separate (architecture and component loading, not user request normalization). + +5. **Runtime Execution State** — `ForwardBatch` in `pipeline_batch_info.py` is internal execution state, not a public config object. + +6. **Training Config** — stays separate from inference config. At most shares dotted override parsing/merging, YAML/JSON loading helpers, and error-path formatting patterns. + +### Naming Guidance + +- keep public inference schema names namespaced under `fastvideo.api` +- avoid exporting them from top-level `fastvideo/__init__.py` until migration is farther along +- envelope types `RunConfig` / `ServeConfig` get sufficient disambiguation from training config via the namespace +- consider renaming the public engine quantization type to `EngineQuantizationConfig` if a collision arises (deferred) + +### Inference Package Structure + +Current single-file [schema.py](/home/william5lin/FastVideo/fastvideo/api/schema.py) is acceptable but not the final shape. Later cleanup should split by concern (config/model classes, envelope types, parser/loading, compatibility translation). + +## Pipeline Package Structure + +The `fastvideo/pipelines/` package should converge on a layout where each model family directory is self-contained: pipeline implementation, presets, engine/arch config, and model-specific stages all in one place. + +### Current layout + +``` +fastvideo/ +├── configs/ +│ ├── pipelines/ # flat: wan.py, ltx2.py, hunyuan15.py, ... +│ │ # (PipelineConfig subclasses — engine/arch config) +│ └── models/ # hierarchical: dits/, vaes/, encoders/ +│ # (architecture definitions — stays here) +│ # note: configs/sample/ was removed entirely in PR 4 +├── pipelines/ +│ ├── basic/ +│ │ ├── wan/ # pipeline classes + presets.py +│ │ ├── ltx2/ # pipeline classes + presets.py +│ │ ├── hunyuan15/ # pipeline classes + presets.py +│ │ └── ... # all families have presets.py (PR 4) +│ └── stages/ # flat: 14 shared + 19 model-prefixed files +└── api/ # public inference schema + preset registry + + # sampling_param.py (canonical SamplingParam home) +``` + +### Target layout + +``` +fastvideo/ +├── configs/ +│ ├── models/ # stays: architecture definitions (dits/, vaes/, ...) +│ └── pipelines/ +│ └── base.py # stays: PipelineConfig base class +├── pipelines/ +│ ├── basic/ +│ │ ├── wan/ +│ │ │ ├── wan_pipeline.py +│ │ │ ├── ... +│ │ │ ├── presets.py # user-facing presets (done in PR 4) +│ │ │ └── pipeline_configs.py # from configs/pipelines/wan.py +│ │ ├── ltx2/ +│ │ │ ├── ltx2_pipeline.py +│ │ │ ├── presets.py +│ │ │ ├── pipeline_configs.py # from configs/pipelines/ltx2.py +│ │ │ └── stages/ # from pipelines/stages/ltx2_*.py +│ │ ├── longcat/ +│ │ │ ├── longcat_pipeline.py +│ │ │ ├── presets.py +│ │ │ ├── pipeline_configs.py +│ │ │ └── stages/ # from pipelines/stages/longcat_*.py (9 files) +│ │ └── ... +│ └── stages/ # shared-only stages remain here +│ ├── base.py, denoising.py, encoding.py, decoding.py, text_encoding.py, ... +└── api/ # unchanged +``` + +### What moves and when + +| Source | Destination | Status | +|--------|------------|--------| +| `configs/sample/.py` | Absorbed by `presets.py` defaults | **Done** (PR 4) — directory deleted entirely | +| `configs/pipelines/.py` | `pipelines/basic//pipeline_configs.py` | Pending — per-model colocation PR | +| `pipelines/stages/_*.py` | `pipelines/basic//stages/` | Pending — optional, per-model PR | + +### What stays + +- **`configs/pipelines/base.py`** — `PipelineConfig` base class, shared CLI arg generation, JSON serialization. +- **`configs/models/`** — Model architecture definitions (DiT, VAE, encoder). +- **`pipelines/stages/` shared stages** — `denoising.py`, `encoding.py`, `decoding.py`, `text_encoding.py`, `timestep_preparation.py`, etc. +- **`pipelines/stages/` model-specific stages** — moving into family directories is optional and should only happen when the family has enough model-specific stages to justify it (LongCat: yes; Wan: no). + +### Cross-family inheritance + +Some families extend another family's PipelineConfig (e.g., `LingBotWorld` extends `Wan2_2_I2V_A14B_Config`; `TurboDiffusion` reuses `t5_postprocess_text` from Wan). After relocation these become cross-family imports; shared utilities like `t5_postprocess_text` should be extracted to a common location to avoid coupling unrelated families. + +### Migration approach + +Config colocation is not a separate PR. Each per-model colocation PR (PRs 6, 9, 10) includes the colocation step for that family: +1. `presets.py` already exists (done in PR 4) +2. Move `configs/pipelines/.py` → `pipeline_configs.py` in family dir +3. `configs/sample/` already removed entirely (done in PR 4) +4. Update `registry.py` imports +5. Update any cross-family imports + +## CI / Testing Baseline + +- GitHub Actions runs pre-commit only in [.github/workflows/ci-precommit.yml](/home/william5lin/FastVideo/.github/workflows/ci-precommit.yml) +- Aggregate/full-suite orchestration via Buildkite status flows ([ci-aggregate-status.yml](/home/william5lin/FastVideo/.github/workflows/ci-aggregate-status.yml), [ci-trigger-full-suite.yml](/home/william5lin/FastVideo/.github/workflows/ci-trigger-full-suite.yml)) +- Useful test anchors: + - [test_video_generator.py](/home/william5lin/FastVideo/fastvideo/tests/entrypoints/test_video_generator.py) + - [test_openai_api.py](/home/william5lin/FastVideo/fastvideo/tests/entrypoints/test_openai_api.py) / [test_openai_api_integration.py](/home/william5lin/FastVideo/fastvideo/tests/entrypoints/test_openai_api_integration.py) (real-server GPU integration belongs in Buildkite/nightly) + - [test_sp_ltx2.py](/home/william5lin/FastVideo/fastvideo/tests/distributed/test_sp_ltx2.py) + - [test_ltx2_pipeline_smoke.py](/home/william5lin/FastVideo/tests/local_tests/pipelines/test_ltx2_pipeline_smoke.py) + - [test_ltx2_registry.py](/home/william5lin/FastVideo/tests/local_tests/test_ltx2_registry.py) + +## New CI Coverage To Add + +### GitHub Actions + +A workflow such as `.github/workflows/ci-inference-api-schema.yml` should run on every PR: + +```bash +pytest -q \ + fastvideo/tests/api \ + fastvideo/tests/entrypoints/test_video_generator.py \ + fastvideo/tests/entrypoints/test_openai_api.py +``` + +`fastvideo/tests/api/` already covers schema parsing, YAML/JSON loading, dotted overrides, strict unknown-key validation, legacy flat-flag translation, and preset selection / stage override validation. + +### Buildkite Fastcheck + +GPU fastcheck jobs for LTX2 preset smoke, preset-to-pipeline dispatch, and one old-vs-new compatibility equivalence check: + +```bash +pytest -q fastvideo/tests/distributed/test_sp_ltx2.py +pytest -q tests/local_tests/pipelines/test_ltx2_pipeline_smoke.py +pytest -q tests/local_tests/test_ltx2_registry.py +``` + +### Buildkite Full Suite + +- multi-stage preset smoke on LongCat and Hunyuan15 +- server default-request merge behavior +- backward compatibility path for legacy CLI and Python kwargs +- real-server integration via [test_openai_api_integration.py](/home/william5lin/FastVideo/fastvideo/tests/entrypoints/test_openai_api_integration.py) + +### Nightly + +- LTX2 continuation/state roundtrip +- Hunyuan15 SR preset smoke +- LongCat distill/refine preset smoke + +## PR Sequence + +### PRs 0-7 (landed) + +See "PR Landing History", "Landed Artifacts", and "Notable Decisions Carried Forward" above. Scope, tests, and merge criteria for the landed PRs are reflected in the linked files; the test suites at `fastvideo/tests/api/` + `fastvideo/tests/entrypoints/` cover the merge criteria. The detailed per-PR sections for PR 6 and PR 7 below are kept as historical context. + +## PR 6: LTX2 Public Preset and Asset Wiring + +### Scope + +Upstream the public LTX2 two-stage preset shape from Dreamverse, but only for repo-visible/public FastVideo surfaces. Also colocate LTX2 config alongside its pipeline implementation. + +Note: `ltx2_base` and `ltx2_distilled` presets already exist (`fastvideo/pipelines/basic/ltx2/presets.py`) and the old `configs/sample/ltx2.py` is gone along with the rest of `configs/sample/` (PR 4). This PR adds the two-stage preset and colocates PipelineConfig. + +### Main Changes + +- add `ltx2_two_stage` preset (two-stage refine) +- add LTX2 stage override types +- map repo-visible LTX2 init-time knobs into: preset selection, component config, preset overrides +- **typed replacements for internal `gpu_pool.py` flat kwargs** (load_kwargs at [gpu_pool.py:233-260](/home/william5lin/FastVideo-internal/ui/ltx2-streaming/server/gpu_pool.py)): + - `ltx2_refine_enabled`, `ltx2_refine_upsampler_path`, `ltx2_refine_lora_path`, `ltx2_refine_add_noise` → `generator.pipeline.preset_overrides.refine.*` (init-time stage config) + - `ltx2_refine_num_inference_steps`, `ltx2_refine_guidance_scale` → `request.stage_overrides.refine.*` (per-request) + - `ltx2_vae_tiling` → typed field on `PipelineSelection` or similar + - `torch_compile_kwargs` (`backend`, `fullgraph`, `mode`, `dynamic`) → first-class fields on `CompileConfig`, with `extras: dict[str, Any]` for uncommon kwargs + - `FP4Config()` integration → typed quantization field path +- do not promise public compatibility for private Dreamverse-only aliases; those belong in the private adapter layer +- **config colocation**: move `configs/pipelines/ltx2.py` → `pipelines/basic/ltx2/pipeline_configs.py`; update `registry.py` imports +- optionally move `pipelines/stages/ltx2_*.py` (4 files) into `pipelines/basic/ltx2/stages/` + +### Why the gpu_pool.py typed-replacement scope matters + +PR 7.6 upstreams `gpu_pool.py` into the public repo. Without this PR 6 expansion, the public server perpetuates the flat-kwarg surface the refactor is eliminating. Every flat kwarg used by `gpu_pool.py` must have a typed home in `GeneratorConfig` / preset overrides / request stage overrides before PR 7.6 can land cleanly. + +Same scoping rule applies to Dynamo. Draft PR ai-dynamo/dynamo#7544 had to reason about FastVideo-internal flat kwarg names to construct `VideoGenerator`; after this PR, Dynamo's `FastVideoArgGroup` can build a typed `GeneratorConfig` directly from its CLI with no awareness of legacy LTX2 names. Hard gate for PR 7.10. + +### Commits + +1. `feat(ltx2): add public ltx2 pipeline presets` +2. `feat(ltx2): add typed refine stage overrides for public ltx2 surfaces` +3. `feat(api): promote common torch.compile kwargs and ltx2 vae tiling to typed fields` +4. `refactor(ltx2): colocate pipeline config and stages with implementation` +5. `test(ltx2): cover preset config normalization, gpu_pool-style kwarg translation, compatibility` + +### Required Tests + +- new `fastvideo/tests/api/test_ltx2_presets.py` +- expand [test_ltx2_registry.py](/home/william5lin/FastVideo/tests/local_tests/test_ltx2_registry.py) +- expand [test_ltx2_pipeline_smoke.py](/home/william5lin/FastVideo/tests/local_tests/pipelines/test_ltx2_pipeline_smoke.py) + +### Merge Criteria + +- public/repo-visible LTX2 setup can be represented by public config +- no new public compatibility promise is made for private-only Dreamverse field aliases +- LTX2 preset smoke passes on GPU CI +- LTX2 config no longer split across `configs/` and `pipelines/` + +## PR 7: LTX2 Continuation State (Public Payload + Server Session) + +### Scope + +Upstream the continuation contract as a **hybrid** public API that supports both opaque client-round-trip payloads AND server-held session state. Both surfaces share one serialization format. + +Decision rationale: [streaming-server-upstream-plan.md § Design Decision 1](.agents/exploration/streaming-server-upstream-plan.md). + +### Main Changes + +- add typed `LTX2ContinuationState` internal dataclass with: + - trailing conditioning frames (or tensor blob ID) + - audio latents (or tensor blob ID) + - segment index / rollout position + - audio sample rate, `video_position_offset_sec`, other metadata +- map request/response state into public `ContinuationState` with `kind="ltx2.v1"` and `payload` serialized from the typed state +- stop requiring app-level raw latent/audio condition fields in the public API +- keep `extensions` only for any remaining experimental fields +- add `SessionStore` interface in `fastvideo/entrypoints/streaming/session_store.py`: + - `snapshot(session_id) -> ContinuationState` + - `hydrate(state: ContinuationState) -> session_id` + - default in-memory implementation; pluggable for redis/etc. later +- specify payload serialization: tensor fields use a blob store indirection when large (bandwidth optimization for the opaque form) + +### Commits + +1. `feat(ltx2): add typed ltx2 continuation state and public payload schema` +2. `feat(streaming): add SessionStore with snapshot and hydrate` +3. `refactor(ltx2): replace raw continuation kwargs with state roundtrip` +4. `test(ltx2): add continuation roundtrip, session snapshot, and compatibility coverage` + +### Required Tests + +- new `fastvideo/tests/api/test_ltx2_state.py` +- new `fastvideo/tests/entrypoints/streaming/test_session_store.py` +- integration tests: generate returns state when requested; next request accepts returned state; invalid state/preset combinations error cleanly; server-held session auto-chains between segments; snapshot + hydrate round-trip across session boundaries +- GPU smoke on Buildkite for state roundtrip + +### Merge Criteria + +- continuation state is a first-class public concept +- both opaque payload and server-held session flows work end to end +- server request translation is able to carry typed state without reverting to ad hoc kwargs +- `gpu_pool.py` style per-GPU implicit chaining is expressible via SessionStore +- `ContinuationState.payload` is JSON-serializable (or uses an opaque blob-ID indirection for large tensors) so it can round-trip through a Dynamo-style RPC for future disaggregated prefill/decode — aggregated Dynamo in PR 7.10 ignores continuation, but the contract must not drift + +## PR 7.5: Streaming Server Skeleton + +Status: open as #1251 on `will/api_7.5`. + +### Scope + +Upstream the minimum viable WebSocket streaming server from `FastVideo-internal/ui/ltx2-streaming/server/main.py`. Single generator (no GPU pool yet), typed `GenerationRequest` as JSON messages, fMP4 output. Prompt enhancer and pool come in later PRs. + +### Main Changes + +- `fastvideo/entrypoints/streaming/server.py`: FastAPI + WebSocket entry +- `fastvideo/entrypoints/streaming/session.py`: session lifecycle, state machine +- `fastvideo/entrypoints/streaming/protocol.py`: JSON WebSocket message schemas (`session_init_v2`, `segment_prompt_source`, `ltx2_segment_start`, `step_complete`, `media_init`, `media_segment_complete`, etc.) +- `fastvideo/entrypoints/streaming/stream.py`: fMP4 encoding via ffmpeg +- `fastvideo/entrypoints/streaming/session_init_image.py`: i2v init image +- Replace the `NotImplementedError` stub from PR 5.5 with the live server +- Wire into `fastvideo streaming-serve` CLI from PR 5.5 +- `docs/design/server_contracts/streaming.md`: WebSocket protocol contract + +### Commits (as shipped) + +1. `feat(streaming): protocol schemas + session state machine` +2. `feat(streaming): fMP4 encoder + session init-image persistence` +3. `feat(streaming): single-generator WebSocket server entry` +4. `test(streaming): server lifecycle + protocol + fMP4 coverage` +5. `docs(streaming): server contract spec` +6. `fix(streaming): restore missing-streaming-block guard + retire stub-era test` +7. `simplify(streaming): review follow-ups (idle timeout via asyncio.wait_for, _send_error helper, _cleanup_session, Protocol-typed generator, cleanup-on-disconnect)` +8. `fix(streaming): enforce idle timeout on receive_json + flag generator-cancellation gap (TODO → PR 7.10)` + +### Required Tests + +- `fastvideo/tests/entrypoints/streaming/test_protocol.py` +- `fastvideo/tests/entrypoints/streaming/test_session.py` +- `fastvideo/tests/entrypoints/streaming/test_session_init_image.py` +- `fastvideo/tests/entrypoints/streaming/test_stream_encoder.py` (fMP4 encode) +- `fastvideo/tests/entrypoints/streaming/test_server.py` (in-process WebSocket lifecycle via `starlette.testclient`) + +### Merge Criteria + +- Single-user WebSocket session end-to-end: connect, init, submit prompts, receive fMP4 chunks, clean shutdown ✓ +- All JSON messages validated against typed protocol schemas ✓ + +### Deferred to later PRs + +- Per-step progress events (only a terminal `step_complete` is emitted today; per-step events need `generate_async` from PR 7.10). +- Mid-segment cancellation on client disconnect (TODO marker in `server.py` near `pool.run`; needs PR 7.10). + +## PR 7.6: GPU Pool Upstream + +Status: branch `will/api_7.6` rebased on `will/api_7.5`, not yet PR'd. + +### Scope + +Upstream `FastVideo-internal/ui/ltx2-streaming/server/gpu_pool.py` with a typed configuration boundary. One subprocess per GPU, one `VideoGenerator` per subprocess, job queue, session-to-GPU binding. + +### Main Changes (as shipped on `will/api_7.6`) + +- `fastvideo/entrypoints/streaming/gpu_pool.py`: `GpuPool` (ABC) + `InProcessGpuPool` + `SubprocessGpuPool` + `PoolAssignment` / `PoolHealth` / `PoolAcquireTimeout` +- `fastvideo/entrypoints/streaming/worker.py`: per-GPU worker entry (`worker_main`) and two-segment warmup helper +- subprocess startup uses typed `GeneratorConfig`, not flat kwargs +- session-to-GPU binding with timeout + queue for contention +- two-segment startup warmup per worker (segment 1 fresh + segment 2 with returned `ContinuationState` so both compile branches are primed) +- `SessionStore` (from PR 7) wired into the pool for per-GPU continuation cache +- `server.py` rerouted to `pool.acquire` / `pool.run` / `pool.release`; `build_app` accepts either a generator (wrapped in `InProcessGpuPool`) or a pre-built `pool=` + +### Commits (as shipped) + +1. `feat [7.6/n]: GPU pool manager with typed worker boundary` +2. `refactor [7.6/n]: route streaming server through GpuPool` +3. `test [7.6/n]: GPU pool coverage (in-process + subprocess)` +4. `fix(streaming): restore missing asyncio import in server` (rebase fixup) +5. `feat(streaming): extract worker.py and add two-segment warmup` + +### Required Tests + +- `fastvideo/tests/entrypoints/streaming/test_gpu_pool.py` (in-process + subprocess via thread-backed factory) ✓ +- `fastvideo/tests/entrypoints/streaming/test_worker.py` (two-segment warmup dispatch + result-shape extractor) ✓ +- GPU smoke on Buildkite for real multi-GPU pool — deferred (separate infra ask) + +### Merge Criteria + +- Single-user multi-segment WebSocket session via the pool path ✓ (covered by `test_server.py`'s `_MockGenerator` on `InProcessGpuPool`) +- No flat kwargs in the pool/worker construction path ✓ (worker_main takes `GeneratorConfig`) +- Session handoff across GPUs (snapshot + hydrate elsewhere) — `SessionStore` wired but no explicit handoff test yet +- Multi-user, multi-GPU WebSocket server end-to-end on real GPUs — deferred (Buildkite GPU smoke) + +### Deferred to later PRs (with rationale) + +- **Audio re-encode (`LTX2AudioEncoder`, `AudioProcessor`)** — internal `_re_encode_audio` runs *inside* the per-step streaming loop (`_stream_av_fmp4_events` / `do_step_ltx2`) to convert waveform → latents for continuation conditioning. The public LTX2 pipeline already populates `LTX2ContinuationState.audio_latents` via `ltx2_audio_decoding.py`, so the whole-segment `pool.run()` path doesn't need a re-encode shim. Re-encode integration is therefore a **per-step streaming concern that belongs with PR 7.10**'s `generate_async`. +- **Deprecate `VideoGenerator.from_pretrained(**flat_kwargs)`** — worker uses typed config, but no public deprecation warning yet. Belongs with PR 13 cleanup. +- **Multi-GPU Buildkite smoke** — separate infra ask; not blocking the upstream PR. + +## PR 7.7: Prompt Enhancer Upstream + +### Scope + +Upstream `FastVideo-internal/ui/ltx2-streaming/server/prompt_enhancer.py` behind an `LLMProvider` abstraction. Ship built-in providers for cerebras and groq; leave the door open for users to add their own. + +Decision rationale: [streaming-server-upstream-plan.md § Design Decision 3](.agents/exploration/streaming-server-upstream-plan.md). + +### Main Changes + +- `fastvideo/entrypoints/streaming/prompt/enhancer.py`: provider-agnostic prompt operations (enhance, auto-extend, rewrite) +- `fastvideo/entrypoints/streaming/prompt/providers/base.py`: `LLMProvider` protocol + `LLMRequest` / `LLMResponse` dataclasses +- `fastvideo/entrypoints/streaming/prompt/providers/cerebras.py`, `groq.py`: built-in implementations +- hot-reloadable system prompts via management endpoint +- fallback retry across providers in priority order +- wire `PromptEnhancerConfig` from PR 5.5 into server startup + +### Commits + +1. `feat(streaming): add LLMProvider protocol and cerebras providers` +2. `feat(streaming): add groq provider` +3. `feat(streaming): add provider-agnostic prompt enhancer orchestration` +4. `feat(streaming): add hot-reloadable system prompt management endpoint` +5. `test(streaming): cover enhancer operations and provider fallback` + +### Required Tests + +- `fastvideo/tests/entrypoints/streaming/prompt/test_providers.py` +- `fastvideo/tests/entrypoints/streaming/prompt/test_enhancer.py` +- mocked provider tests for fallback behavior + +### Merge Criteria + +- Enhancer works end-to-end with the WebSocket server from PR 7.5 +- Third-party users can register their own `LLMProvider` +- Hot-reload of system prompts survives config changes + +## PR 7.8: Streaming Auxiliaries + +### Scope + +Upstream the small auxiliary modules: prompt safety, rewrite payload builder, session logger, mock server. + +### Main Changes + +- `fastvideo/entrypoints/streaming/prompt/safety.py`: optional fasttext classifier; shipped as optional extra `pip install fastvideo[prompt-safety]` +- `fastvideo/entrypoints/streaming/prompt/rewrite.py`: rewrite payload builder (from internal `rewrite_prompt_payload.py`) +- `fastvideo/entrypoints/streaming/session_logger.py`: session JSONL logs +- `fastvideo/entrypoints/streaming/mock_server.py`: mock backend for dev/tests +- `pyproject.toml` optional-dependency entry for `prompt-safety` + +### Commits + +1. `feat(streaming): add optional fasttext prompt safety` +2. `feat(streaming): add rewrite payload builder and session logger` +3. `feat(streaming): add mock server for frontend development` +4. `test(streaming): cover safety, rewrite, mock server` + +### Required Tests + +- `fastvideo/tests/entrypoints/streaming/test_safety.py` (with and without fasttext installed) +- `fastvideo/tests/entrypoints/streaming/test_rewrite.py` +- `fastvideo/tests/entrypoints/streaming/test_mock_server.py` + +### Merge Criteria + +- Optional dependency gating works: safety silently disables when fasttext is not installed +- Mock server can replace the real server for frontend dev + +## PR 7.9: Router Upstream + +### Scope + +Upstream `FastVideo-internal/ui/ltx2-streaming/router/main.py` — a multi-replica load balancer with health checks and WebSocket proxying. + +**Open decision**: in-repo subpackage vs. separate package. Default assumption: in-repo at `fastvideo/entrypoints/streaming/router/`. If review concludes router is too orthogonal to inference, split into `fastvideo-router/` or `fastvideo/contrib/router/`. + +### Main Changes + +- `fastvideo/entrypoints/streaming/router/main.py`: router entry +- `fastvideo/entrypoints/streaming/router/registry.py`: replica registry (from internal `ReplicaRegistry` class) +- health check loop, failure threshold, primary/secondary semantics +- `fastvideo router-serve --config router.yaml` CLI subcommand +- typed `RouterConfig` in `fastvideo/api/schema.py` + +### Commits + +1. `feat(router): add typed RouterConfig and replica registry` +2. `feat(router): add health check loop and failure handling` +3. `feat(router): add websocket proxy and http passthrough` +4. `feat(cli): add router-serve subcommand` +5. `test(router): cover registry, health, and proxy behavior` + +### Required Tests + +- `fastvideo/tests/entrypoints/streaming/router/test_registry.py` +- `fastvideo/tests/entrypoints/streaming/router/test_main.py` +- integration test with two mock backends + +### Merge Criteria + +- Multi-backend deployment works end-to-end +- Health checks flip replicas in and out cleanly +- WebSocket sessions routed to healthy primary, fall back on failure + +## PR 7.10: Dynamo Backend Contract + +### Scope + +Make FastVideo consumable as a native Dynamo backend (same tier as vllm, sglang, trtllm). **FastVideo does not host any Dynamo code** — the backend package (args.py, main.py, backend.py, register.py, health_check.py, adapter) lives entirely in the Dynamo repo at `components/src/dynamo/fastvideo/`, modeled on draft PR ai-dynamo/dynamo#7544. + +This PR lands only the FastVideo-side **contract**: the public Python API that Dynamo's backend package imports. Zero new dependencies, zero `contrib/dynamo/`, zero Dynamo-specific CLI inside FastVideo. + +Decision rationale: [streaming-server-upstream-plan.md § Design Decision 4](.agents/exploration/streaming-server-upstream-plan.md). + +### Main Changes + +- add `VideoGenerator.generate_async(request: GenerationRequest) -> AsyncGenerator[VideoEvent, None]`: + - `VideoProgressEvent(step, total_steps, stage)` + - `VideoPartialEvent(frames_ndarray, index)` (optional; emitted in the streaming path only) + - `VideoFinalEvent(video_bytes_or_tensor, metadata, continuation_state: ContinuationState | None)` +- refactor `VideoGenerator.generate_video(request=...)` to run through `asyncio.run(generate_async(...))` internally, collecting events and returning the final result; preserve the public sync signature +- add `VideoGenerator.default_health_check_request() -> GenerationRequest` (256x256, 8 frames, 1 step) so a Dynamo-side health payload can be derived purely from the public API +- add typed `VideoEvent` hierarchy and `VideoResult` exports under `fastvideo.api` +- stabilize public re-exports: `from fastvideo import VideoGenerator`; `from fastvideo.api import GenerationRequest, SamplingConfig, ContinuationState, VideoResult, VideoEvent, VideoProgressEvent, VideoPartialEvent, VideoFinalEvent` +- PR 7.5's streaming server is rewired to consume `generate_async` directly (was a TODO in PR 7.5) +- audio re-encode integration (`LTX2AudioEncoder`, `AudioProcessor`) for per-step audio continuity inside the streaming fMP4 pipeline (deferred from PR 7.6 — the whole-segment `pool.run()` path doesn't need it; the per-step path does) +- mid-segment cancellation: client disconnect propagates an `asyncio.CancelledError` through `generate_async` so the GPU work stops instead of running to completion (the gap PR 7.5/7.6 flagged with TODO markers around `pool.run`) +- docs PR (PR 8) carries a reference mapping sketch the Dynamo repo's backend package can use as a template — but no code in FastVideo knows about Dynamo + +### Why the async API matters for more than Dynamo + +The same `generate_async` surface that Dynamo consumes also powers: + +- **Streaming server fMP4 pipeline** (PR 7.5) — decoder pulls `VideoPartialEvent` frames directly, no intermediate disk spill +- **OpenAI stateless server** (PR 5) — can opt into progress events for future Server-Sent-Events extension without a second code path +- **Future disaggregation in Dynamo** — prefill/decode split can carry `ContinuationState` across workers using the same event shape + +Building `generate_async` once prevents three near-duplicate progress loops from growing in the three adapters. + +### Commits + +1. `feat(api): add VideoEvent hierarchy and VideoResult public exports` +2. `feat(entrypoints): add VideoGenerator.generate_async event stream` +3. `refactor(entrypoints): reroute generate_video through generate_async internally` +4. `feat(entrypoints): add default_health_check_request helper` +5. `test(entrypoints): cover generate_async event stream and sync wrapper parity` +6. `test(entrypoints): contract test that mock dynamo-style handler wraps public api` + +### Required Tests + +- `fastvideo/tests/entrypoints/test_generate_async.py`: + - event ordering (Progress* → Final) + - sync `generate_video` returns the same result as collecting events from `generate_async` + - cancellation mid-generation cleans up GPU state +- contract test that imports only the public surface (`from fastvideo import VideoGenerator`, `from fastvideo.api import ...`) and wraps it in a mock Dynamo-style handler signature (`async def generate(req: dict, ctx) -> AsyncGenerator[dict, None]`), verifying the wrap is possible without any FastVideo-internal imports +- health-check helper returns a valid `GenerationRequest` that passes `parse_config` + +### Merge Criteria + +- `generate_async` is the canonical execution API; `generate_video` remains for backward-compat but is a thin sync wrapper +- FastVideo's public surface alone is sufficient to construct a Dynamo backend — no flat LTX2 legacy kwargs, no FastVideo-internal imports required +- migration docs (PR 8) include the Dynamo integration skeleton so ai-dynamo/dynamo#7544 or its successor can be reopened and landed with a straightforward handler/adapter written in the Dynamo repo +- streaming server (PR 7.5) consumes `generate_async` directly, no wrapper duplication +- no Dynamo-related file, dep, or import path lives in FastVideo + +## PR 8: Internal-UI ↔ Public-Server Contract + Dynamo Integration Reference + +### Scope + +Document and test the contract between the public FastVideo server stack (OpenAI HTTP, streaming WebSocket) and both of its major external consumers: + +1. The private Dreamverse / internal-UI server stack that previously lived in `FastVideo-internal/ui/ltx2-streaming/`. +2. The Dynamo backend package at `ai-dynamo/dynamo/components/src/dynamo/fastvideo/`. + +This PR does not ship runtime code beyond tests and docs — it locks down the surface so drift between FastVideo, the internal UI, and Dynamo can be caught at review time. + +### Main Changes + +- add WebSocket protocol reference doc (message schemas, state machine, error codes) for the streaming server from PR 7.5-7.9 +- add OpenAI HTTP contract reference for the stateless server from PR 5 +- add Dynamo integration reference: + - end-to-end example showing how `components/src/dynamo/fastvideo/` should be laid out (args.py, main.py, backend.py, register.py, health_check.py) using the public FastVideo API from PR 7.10 + - contract tests that mimic Dynamo's `serve_endpoint(handler.generate, ...)` wrapping and verify FastVideo's `VideoGenerator` works inside it +- migration examples for Dreamverse-style inputs normalized through the typed public API without private-only compat kwargs +- keep translation from private-only fields in the private adapter rather than broadening the public FastVideo compatibility surface + +### Commits + +1. `docs(server): add websocket streaming protocol reference` +2. `docs(server): add openai stateless contract reference` +3. `docs(dynamo): add integration reference for native backend package` +4. `test(contract): add dreamverse-style and dynamo-style contract fixtures` + +### Required Tests + +- public-side tests only +- verify Dreamverse-style inputs can be normalized without private-only APIs +- mock Dynamo handler wraps `VideoGenerator.generate_async` without pulling internal modules — regression guard for PR 7.10 + +### Merge Criteria + +- clear migration path exists for private server consumers +- clear reference path exists for Dynamo integrators (the next iteration of ai-dynamo/dynamo#7544 can reopen against this doc set) +- no new ad hoc public kwargs are added + +## PR 9: LongCat Preset Migration + +> May be combined with PR 10 if preset infrastructure from PR 4 is mature. + +### Scope + +Move LongCat's two-stage user flow behind a named preset and typed refine override surface. Colocate LongCat config — this family has the strongest case for colocation given its 9 model-specific stage files scattered in the shared `pipelines/stages/` directory. + +Note: LongCat presets (`longcat_t2v`, `longcat_i2v`, `longcat_vc`) already exist and are wired via `default_preset` in registry (PR 4). LongCat never had SamplingParam subclasses. This PR adds the stage override types and colocates PipelineConfig + stages. + +### Main Changes + +- add `longcat_distill_refine` multi-stage preset +- add `LongCatRefineStageOverride` +- map current `refine_from`, `stage1_video`, `t_thresh`, `spatial_refine_only`, `num_cond_frames` +- update examples to use the preset path +- **config colocation**: move `configs/pipelines/longcat.py` → `pipelines/basic/longcat/pipeline_configs.py`; update `registry.py` imports +- **stage colocation**: move `pipelines/stages/longcat_*.py` (9 files) → `pipelines/basic/longcat/stages/`; update imports from pipeline classes + +### Commits + +1. `feat(longcat): add distill refine preset and override types` +2. `refactor(longcat): colocate pipeline config and stages with implementation` +3. `refactor(longcat): migrate examples to typed preset based api` +4. `test(longcat): add preset and compatibility coverage` + +### Required Tests + +- API/unit tests for LongCat preset parsing +- smoke coverage for preset dispatch +- if feasible, SSIM/nightly preset regression for LongCat refine path + +### Merge Criteria + +- LongCat public flow no longer requires hand-wired two-generator orchestration in examples +- LongCat config and model-specific stages colocated under `pipelines/basic/longcat/` + +## PR 10: Hunyuan15 SR Preset Migration + +> May be combined with PR 9 if preset infrastructure from PR 4 is mature. + +### Scope + +Represent Hunyuan15 SR as first-class presets rather than pipeline-class knowledge in examples. Colocate Hunyuan15 config alongside its pipeline implementation. This PR also serves as the proof-of-concept for migrating model-specific fields out of the shared schema (`height_sr`, `width_sr`, `num_inference_steps_sr` → SR stage overrides). + +Note: Hunyuan15 presets (`hunyuan15_t2v_480p`, `hunyuan15_i2v_480p_distilled`, `hunyuan15_t2v_720p`, `hunyuan15_i2v_720p_distilled`, `hunyuan15_sr_1080p`) already exist and the old `configs/sample/hunyuan15.py` is gone along with the rest of `configs/sample/` (PR 4). This PR adds the SR stage override types and colocates PipelineConfig. + +### Main Changes + +- add `HunyuanSRStageOverride` typed override class +- add small stage override types where needed +- update examples and request defaults +- **config colocation**: move `configs/pipelines/hunyuan15.py` → `pipelines/basic/hunyuan15/pipeline_configs.py`; update `registry.py` imports +- **SR field migration POC**: declare `height_sr`, `width_sr`, `num_inference_steps_sr` as SR-stage-owned overrides in the preset rather than shared `SamplingConfig` fields + +### Commits + +1. `feat(hunyuan15): add sr presets with typed stage overrides` +2. `refactor(hunyuan15): colocate pipeline config with implementation` +3. `refactor(hunyuan15): route examples through preset selection` +4. `test(hunyuan15): add sr preset config and smoke coverage` + +### Required Tests + +- API parsing tests +- entrypoint tests for preset defaults +- GPU smoke or nightly SR preset checks + +### Merge Criteria + +- Hunyuan15 SR is discoverable and stable through named presets +- Hunyuan15 config colocated under `pipelines/basic/hunyuan15/` +- SR-specific fields validated through preset stage overrides + +## PR 11: SSIM and Performance Test Migration + +### Scope + +Move golden-quality inference tests onto the typed/public API only after preset defaults and request-vs-pipeline override semantics have stabilized. + +This PR should migrate regression suites that currently depend on legacy generation helpers such as `generate_video(..., **kwargs)` and test-only parameter bags. + +### Main Changes + +- migrate SSIM tests to the typed API or typed config path +- migrate performance tests to the typed API or typed config path +- make any remaining request-vs-pipeline compatibility mappings explicit before the migration +- keep output-quality baselines unchanged while swapping the invocation path + +### Commits + +1. `refactor(ssim): migrate golden inference tests to typed api` +2. `refactor(perf): migrate performance tests to typed api` +3. `test(regression): add old-vs-new invocation parity coverage where needed` + +### Required Tests + +- existing SSIM/nightly suites +- existing performance suites +- at least one parity check that runs the same canonical request through both the legacy and typed paths before the legacy path is removed + +### Merge Criteria + +- SSIM/performance tests no longer depend on legacy public inference helpers +- migrated tests do not need ad hoc compatibility exceptions beyond the typed schema/preset surface +- quality baselines remain stable after the invocation-path switch + +## PR 12: Docs and Example Migration + +> May be combined with PR 13 if scope is small. + +### Scope + +Move docs and examples onto the new API so the canonical surface is actually visible to users. + +### Main Changes + +- update inference docs +- add YAML config examples +- update basic examples to `GeneratorConfig` + `GenerationRequest` +- add migration guide from flat kwargs and flags + +### Commits + +1. `docs(api): add typed inference schema and yaml examples` +2. `docs(migration): map legacy kwargs and flags to new config` +3. `refactor(examples): migrate basic inference examples` + +### Required Tests + +- doc example smoke tests if feasible +- at minimum, keep example snippets synchronized with tested APIs + +### Merge Criteria + +- docs no longer present legacy kwargs as the preferred surface + +## PR 13: Deprecation Warnings and Final Cleanup + +> May be combined with PR 12 if scope is small. + +### Scope + +Make the old surface clearly transitional without removing it immediately. + +### Main Changes + +- add deprecation warnings for: + - direct public `FastVideoArgs` + - direct public `SamplingParam` + - `generate_video(..., **kwargs)` legacy paths + - `VideoGenerator.from_pretrained(**flat_kwargs)` (deferred from PR 7.6 — the typed `config=GeneratorConfig` path is already preferred) + - legacy flat CLI flags where appropriate +- remove duplicated now-dead translation paths if any + +### Commits + +1. `chore(deprecation): warn on legacy inference api entrypoints` +2. `test(deprecation): cover warning paths and compat guarantees` + +### Required Tests + +- warning assertion tests +- ensure compatibility still works while warnings are emitted + +### Merge Criteria + +- users have a clear migration runway +- public docs point to the new surface + +## Post-PR 13: Retire `fastvideo/api/compat.py` + +After PR 13 puts deprecation warnings on the flat-kwarg public surface, the compat layer at `fastvideo/api/compat.py` (~370 lines) is the last remaining translation shim between the typed public API and the legacy internal types (`FastVideoArgs`, `SamplingParam`). It bridges five distinct jobs: + +| Function / block | Job | Removable when | +|---|---|---| +| `legacy_from_pretrained_to_config` | forward: flat `from_pretrained(..., **kwargs)` → `GeneratorConfig` | all callers pass `config=GeneratorConfig` | +| `legacy_generate_call_to_request`, `_sampling_param_to_request_raw`, `_LEGACY_REQUEST_ALIASES` | forward: `generate_video(prompt, **kwargs)` → `GenerationRequest` | all callers pass `request=GenerationRequest` | +| `generator_config_to_fastvideo_args`, `_compile_config_to_torch_kwargs` | reverse: typed `GeneratorConfig` → legacy `FastVideoArgs` | runtime consumes `GeneratorConfig` directly | +| `request_to_sampling_param`, `explicit_request_updates` | reverse: typed `GenerationRequest` → legacy `SamplingParam`; supports the `ForwardBatch(**shallow_asdict(sampling_param), …)` spread in `entrypoints/video_generator.py` | `ForwardBatch`/stages read from `GenerationRequest` directly | +| `normalize_generator_config`, `normalize_generation_request`, `load_generator_config_from_file` | input normalization (dict / YAML / JSON → typed) | never — these move to `parser.py`, not deleted | + +Can't be done in a single PR; each job has a different unlock condition. Kill order: + +### PR 14: Strip forward translation + +Prerequisite: flat-kwarg callers already migrated via PRs 11 (SSIM/performance tests), 12 (docs/examples), and 7.6 (realtime runtime upstream — `fastvideo/entrypoints/realtime/local_runtime.py:GPUSlot` currently calls `VideoGenerator.from_pretrained(**load_kwargs)` with the flat LTX-2 kwarg surface PR 6 has now typed). + +- `VideoGenerator.from_pretrained` accepts `(model_path, config: GeneratorConfig | None = None)`; raises if called with extra `**kwargs`. +- `generate_video` accepts `(request: GenerationRequest, …)`; no legacy flat-kwarg path. +- Delete `legacy_from_pretrained_to_config`, `legacy_generate_call_to_request`, `_sampling_param_to_request_raw`, `_LEGACY_REQUEST_ALIASES`, `_LTX2_REFINE_FLAT_KEYS`, `_apply_request_field`. +- Verify with `grep -rn 'from_pretrained.*,\s*\*\*' fastvideo/ examples/ tests/` — expect zero hits outside the implementation itself. + +Net: ~100 lines gone from compat.py; the file still exists for the reverse half. + +### PR 15: `FastVideoArgs` becomes a view over `GeneratorConfig` + +Today `FastVideoArgs` is a ~600-line god-object threaded through every stage, model loader, distributed setup, and worker. `compat.py:generator_config_to_fastvideo_args` exists solely to produce it from a typed config. + +The minimum-disruption path: turn `FastVideoArgs` into a `@dataclass` that holds a `GeneratorConfig` and exposes the legacy field names as `@property` accessors backed by the nested typed fields. No more two-way conversion — one object, one source of truth. + +- `generator_config_to_fastvideo_args` becomes identity / trivial wrapper; inlined at call sites where obvious. +- `FastVideoArgs.from_kwargs` (which silently filters unknown kwargs — see the text-encoder compile case in this session) either disappears or becomes equivalent to passing the GeneratorConfig through. +- All existing `fastvideo_args.dit_cpu_offload` etc. call sites keep working via the property accessors. + +Alternative: sweep `grep -rn 'fastvideo_args\.' fastvideo/` (200+ hits) and rewrite every usage to read from `GeneratorConfig` directly. Cleaner end state, 3-5 PRs of grunt work; defer to opportunistic clean-as-you-go after PR 15. + +Net: reverse-translation half of compat.py (~150 lines) becomes trivial or inlined. + +### PR 16: `ForwardBatch` reads `GenerationRequest` by reference + +Kills `request_to_sampling_param` and the `ForwardBatch(**shallow_asdict(sampling_param), …)` spread currently at `entrypoints/video_generator.py:576`. + +- `ForwardBatch` gains `request: GenerationRequest` field. +- Stages that read `batch.num_inference_steps`, `batch.guidance_scale`, etc. rewrite to `batch.request.sampling.num_inference_steps` / `.guidance_scale`. Mostly mechanical; easily scripted. +- `explicit_request_updates` (used by the OpenAI server for operator-default merge) moves to `parser.py` — it's genuinely useful logic, just mis-filed in compat. +- `SamplingParam` either deleted or demoted to an external-facing convenience dataclass with no internal consumers. + +Depends on PR 15 (or at least on having a typed config reachable from every stage that currently reaches `fastvideo_args`). + +### PR 17: Dissolve `compat.py` + +At this point the file has only the parsing helpers: + +- `normalize_generator_config`, `normalize_generation_request` → move to `fastvideo/api/parser.py` next to `parse_config`. +- `load_generator_config_from_file` → move to `parser.py`. + +Delete `fastvideo/api/compat.py`. + +### Dependency chain + +``` +PR 13 (deprecation) + ↓ +PRs 11, 12, 7.6 (migrate callers) + ↓ +PR 14 (forward translation gone) ───── ~100 lines out of compat.py + ↓ +PR 15 (FastVideoArgs as view) ───── reverse-translation trivial + ↓ +PR 16 (ForwardBatch reads request) ───── SamplingParam demoted + ↓ +PR 17 (move normalizers, delete file) +``` + +PR 14 is reachable within the currently-planned sequence. PRs 15-17 touch training, distributed, and worker code in addition to the inference path; realistically 1-2 quarters of work beyond the current plan. + +## Checkpoint: Post-PR 5.5 Review + +Before starting PR 6, review: + +- Whether PR 6 expansion (typed replacements for the flat LTX2 kwargs used by internal `gpu_pool.py`) is in reach +- Which model-specific fields remain in the shared `SamplingConfig`/`InputConfig` +- Whether the escape hatch pass-through in the compat layer has shrunk +- Whether config colocation (moving `configs/pipelines/.py` into `pipelines/basic//`) can begin with PR 6, or needs a separate prep PR +- Whether PRs 9 and 10 can be combined +- Whether PRs 12 and 13 can be combined +- Whether model-specific stages in `pipelines/stages/` should move into family directories (especially LongCat with 9 model-specific stage files) +- Router: in-repo subpackage vs. separate package decision (defer to PR 7.9) +- Overall timeline and priority for the remaining PR tail + +## Commit Hygiene Rules + +Within each PR: + +- keep structural moves and behavioral changes in separate commits +- keep test additions in separate commits where practical +- do not mix LTX2 private-upstream logic with unrelated CLI refactors +- every compatibility mapping change must have an equivalence test in the same PR + +## Recommended Test Matrix By Layer + +### Schema / Parser Layer + +- public-field parity assertions +- YAML load +- JSON load +- dict load +- serialization roundtrip +- dotted override merge +- strict unknown-key rejection +- type error path reporting + +### Python API Layer + +- `from_config` +- `from_file` +- typed `generate` +- legacy kwargs translation +- batch prompt file behavior + +### CLI Layer + +- `generate --config` +- `serve --config` +- dotted nested overrides +- flat legacy flag compatibility +- precedence tests + +### Preset Layer + +- model/preset resolution +- preset version validation +- stage name validation +- stage override type validation + +### Server Layer + +- `ServeConfig` load +- default request merge +- per-request overrides +- stage override validation +- continuation state request/response path +- real-server health/generation integration in GPU/nightly CI + +### GPU / Pipeline Layer + +- LTX2 preset smoke +- LTX2 continuation roundtrip +- LongCat preset smoke +- Hunyuan15 SR preset smoke +- old-vs-new config equivalence for one or two canonical requests +- after preset/default stabilization, migrate SSIM and performance regression suites off legacy `generate_video(...)` + +## Risk Management Notes + +### Highest Risk Areas + +- legacy kwargs translation subtly changing behavior +- server request translation bypassing validation +- LTX2 continuation semantics drifting from Dreamverse expectations +- preset defaults accidentally changing output quality + +### Mitigations + +- require normalized-config equivalence tests for legacy mapping +- gate server translation through typed parser only +- add LTX2 continuation roundtrip tests before private-server migration +- add smoke and nightly regression coverage for preset defaults + +## Recommended Landing Order Summary + +1. PR 0: schema parity inventory — **done** +2. PR 1: shared schema — **done** +3. PR 2: VideoGenerator typed path + compat — **done** +4. PR 3: CLI/YAML refactor — **done** +5. PR 4: preset registry + preset migration for all families — **done** +6. PR 5: stateless OpenAI server `default_request` merge (narrow) — **done** +7. PR 5.5: streaming server subpackage split (skeleton only, no behavior change) — **done** +8. PR 6: LTX2 public preset + config colocation + typed replacements for every flat LTX2 kwarg used by internal `gpu_pool.py` and consumed by the Dynamo backend +9. PR 7: LTX2 continuation state (hybrid: opaque payload + server session), JSON-serializable payloads +10. PR 7.5: streaming server skeleton (WebSocket + fMP4 + single generator) +11. PR 7.6: GPU pool upstream +12. PR 7.7: prompt enhancer upstream with `LLMProvider` abstraction +13. PR 7.8: streaming auxiliaries (prompt safety, session logger, mock server, rewrite) +14. PR 7.9: router upstream +15. PR 7.10: Dynamo backend **contract** — FastVideo adds `VideoGenerator.generate_async` + health-check helper; the Dynamo backend package itself lives entirely in the Dynamo repo +16. PR 8: internal-UI ↔ public-server contract docs + Dynamo integration reference +17. PR 9: LongCat preset migration + colocation +18. PR 10: Hunyuan15 SR preset migration + colocation + SR field migration POC +19. PR 11: SSIM/performance test migration +20. PR 12: docs/examples (includes streaming server + Dynamo) +21. PR 13: deprecation cleanup (includes flat LTX2 kwargs the internal gpu_pool used to consume) + +This order keeps the API foundation first, lands server normalization before any private-server or Dynamo migration claim, builds one async execution substrate (PR 7.10) that serves both the streaming server and the Dynamo backend, and keeps broad multi-model cleanup only after the shared abstractions have settled. + +## Post-PR 13 Cleanup Goal + +The successful end state is: + +- one public inference config surface under `fastvideo.api` +- one internal preset/default layer near each pipeline +- one internal execution-state layer + +### Target directory structure per model family + +Each family directory under `fastvideo/pipelines/basic//` should be self-contained: + +``` +fastvideo/pipelines/basic// +├── _pipeline.py # pipeline implementation(s) +├── presets.py # user-facing presets (defaults + stage topology) +├── pipeline_configs.py # engine/arch config (from configs/pipelines/) +└── stages/ # model-specific stages (optional, if >2 files) +``` + +### What should be gone + +- `configs/pipelines/.py` — moved to `pipelines/basic//` +- `configs/sample/` — directory removed entirely (**done** in PR 4); defaults absorbed by `presets.py` +- model-prefixed files in `pipelines/stages/` — moved to family `stages/` dirs + +### What remains shared + +- `configs/pipelines/base.py` — `PipelineConfig` base class +- `configs/models/` — architecture definitions (dits/, vaes/, encoders/) +- `pipelines/stages/` — shared stages only (denoising.py, encoding.py, etc.) + +The refactor is not complete if the repo permanently keeps two equal, first-class public inference config systems, or if understanding a single model family requires visiting 4+ scattered directories. diff --git a/.agents/memory/dreamverse-integration/source-archive/README.md b/.agents/memory/dreamverse-integration/source-archive/README.md new file mode 100644 index 0000000000..6cc5a52f65 --- /dev/null +++ b/.agents/memory/dreamverse-integration/source-archive/README.md @@ -0,0 +1,44 @@ +# Source Archive + +These are the original unsynthesized design and integration docs that +predate the consolidation in +[`../`](../). They are **NOT** the source of truth — the synthesized +sibling files in the parent directory are. + +Archived 2026-05-03. All previously untracked. + +## Contents + +| File | Original location | Date | Synthesized into | +|---|---|---|---| +| `apirefactor.md` | `FastVideo/` (repo root) | 2026-04-21 | [`../design.md`](../design.md) | +| `PR-plan.md` (was `PR plan.md` at repo root) | `FastVideo/` (repo root) | 2026-04-25 | [`../pr-roadmap.md`](../pr-roadmap.md) | +| `dreamverse_review.md` | `FastVideo/` (repo root) | 2026-04-26 | [`../decisions-log.md`](../decisions-log.md) + [`../state.md`](../state.md) | +| `handoff-nvfp4-launch-demo.md` | `.agents/exploration/` | 2026-05-02 | [`../state.md`](../state.md) + [`../quantization.md`](../quantization.md) + [`../open-threads.md`](../open-threads.md) | +| `streaming-server-upstream-plan.md` | `.agents/exploration/` | 2026-04-17 | [`../streaming-server.md`](../streaming-server.md) + [`../decisions-log.md`](../decisions-log.md) | +| `dreamverse_integration.md` | `.agents/exploration/` | 2026-04-23 | [`../cross-repo-surfaces.md`](../cross-repo-surfaces.md) | +| `video-generator-config-api-design.md` | `.agents/exploration/` | 2026-04-02 | [`../design.md`](../design.md) (early-draft material) | + +## Why archived (not deleted) + +- Future agents may want the **full unsynthesized rationale** for a + decision the synthesis abbreviated. +- The originals remain useful as a **time machine** for understanding + how the design evolved. +- These docs were never committed to git, so leaving them on disk costs + nothing. + +## When to read the archive vs. the synthesis + +- **Read the synthesis (`../*.md`)** for: current state, decision + status, action items, design rationale at the conceptual level. +- **Read the archive (here)** for: deep historical context, exact wording + of design decisions, full PR plan with all sub-PR commit details, + the original Q-1..Q-9 / D-1..D-11 prose. + +## Maintenance rule + +Do NOT edit files in this archive. They are point-in-time snapshots. +If new design material appears that supersedes an entry here, update the +synthesis (the parent dir) and append a note to that synthesis file — +do not mutate this archive. diff --git a/.agents/memory/dreamverse-integration/source-archive/apirefactor.md b/.agents/memory/dreamverse-integration/source-archive/apirefactor.md new file mode 100644 index 0000000000..482c406d1a --- /dev/null +++ b/.agents/memory/dreamverse-integration/source-archive/apirefactor.md @@ -0,0 +1,838 @@ +# FastVideo API Refactor Design + +## Related Documents +- [PR plan.md](PR%20plan.md) — PR-by-PR implementation plan for this design +- [.agents/exploration/streaming-server-upstream-plan.md](.agents/exploration/streaming-server-upstream-plan.md) — streaming-server upstream + Dynamo backend contract (shapes PRs 5.5-7.10) +- `../FastVideo-internal/.agents/exploration/rebase-upstream-fastvideo.md` — rebasing FastVideo-internal onto upstream (enables PRs 6-8) +- `../FastVideo-internal/ui/ltx2-streaming/` — source for the streaming server being upstreamed (PRs 7.5-7.9) +- `../dynamo/` — local clone of ai-dynamo/dynamo; `components/src/dynamo/sglang/` is the template for FastVideo's native backend landed in PR 7.10 +- https://github.com/ai-dynamo/dynamo/pull/7544 — closed draft PR that establishes the Dynamo backend shape this design must satisfy + +## Status + +Design spec for the public inference API refactor. PRs 0-5.5 are landed; see [PR plan.md](PR%20plan.md) for rollout status and the PR 6+ roadmap. The typed schema, strict parser, preset system, typed VideoGenerator, typed CLI, and stateless OpenAI server default-request merge are all implemented. Streaming package skeleton + typed streaming config types are in place; live streaming server + Dynamo contract are the next milestones. + +## Executive Summary + +FastVideo should move to a single typed nested inference schema that is shared across: + +- Python API +- CLI +- YAML/JSON config files +- OpenAI/server request translation + +The core split is: + +- `GeneratorConfig`: generator-instance lifetime settings +- `GenerationRequest`: per-call inputs, sampling, outputs, and continuation +- `InferencePreset`: model-owned named multi-stage defaults + +The canonical user experience should be: + +1. Choose a model. +2. Choose a pipeline preset. +3. Override a few typed fields. +4. Generate. + +FastVideo should not make a raw free-form string dict the primary API. Dicts and YAML/JSON should be supported as serialization/interchange layers, but they must be parsed immediately into typed config objects with strict unknown-key validation. + +The repo should also shift model-specific preset/default definitions closer to their pipeline implementations, while keeping the shared public schema and parsers centralized. + +## Why This Refactor Is Needed + +Today the public inference boundary is too flat and too forgiving. + +- `VideoGenerator.from_pretrained(..., **kwargs)` mixes: + - engine/runtime settings + - pipeline init settings + - component overrides +- `VideoGenerator.generate_video(..., **kwargs)` mixes: + - prompt and inputs + - sampling parameters + - output settings + - model-specific workflow knobs +- unknown or drifting keys can be silently filtered or merely logged instead of failing fast +- model-specific multi-stage behavior is exposed through ad hoc top-level flags instead of a stable preset/stage abstraction + +This is already painful in LTX2/Dreamverse, and it will get worse as more multi-stage pipelines are upstreamed. + +## Design Goals + +- Keep the Python API typed and editor-friendly. +- Make YAML/JSON a first-class serialization of the same schema. +- Support CLI overrides cleanly without flattening the schema into hundreds of canonical flags. +- Separate init-time config from request-time config. +- Provide a stable public abstraction for multi-stage pipelines. +- Support LTX2 two-stage and continuation behavior cleanly. +- Keep the simple case simple. +- Co-locate model-owned defaults and stage topology with the relevant pipeline. +- Protect current public/server behavior with an explicit schema parity audit before freezing the new surface. +- Preserve backward compatibility long enough to migrate examples, internal users, and servers safely. + +## Non-Goals + +- Do not make Ray a structural dependency or copy its package layout. +- Do not make a raw free-form dict the primary Python API. +- Do not force all models into one universal `RefineConfig`. +- Do not expose stage indices as the primary user interface. +- Do not move every shared config class into per-model directories. + +## External Inspiration + +### Ray + +Borrow only the ergonomic idea that user-facing config can be expressed as a string-keyed dict or YAML/JSON config. Do not copy Ray's structure into FastVideo. + +### SGL Multimodal Gen + +Useful ideas: split instance config from request config; allow dict input at the boundary; parse dicts immediately into typed request objects; merge request overrides onto model defaults; validate request params against pipeline/task type. Do not copy: request objects depending on server/engine config; broad weakly typed request bags as the canonical API. + +### vLLM-Omni + +Useful ideas: model-owned pipeline presets; explicit stage topology; per-stage default sampling params; clean separation between stage topology, engine defaults, and runtime overrides. Do not copy: positional `sampling_params_list` as the primary public API; serving-engine-oriented stage index semantics in the main Python interface. + +## Core Decision + +FastVideo should have: + +1. A shared typed public schema. +2. Model-owned named pipeline presets. +3. Semantic stage overrides by stage name. +4. Optional advanced explicit plans for power users. +5. YAML-first config loading with dotted CLI overrides. + +The public API should be stable at the schema level, while model-specific behavior should be contained in preset definitions and model-specific typed override classes. + +## Schema Parity Requirement + +Before the new schema is declared canonical, FastVideo should build a parity inventory across all current public inference surfaces (Python `VideoGenerator` kwargs, CLI flags, YAML/JSON config inputs, OpenAI/server request models, model-specific sampling/runtime fields). Each field must be marked: kept as-is, renamed, moved to a nested path, preset-owned, private-only adapter field, or intentionally dropped. No field should disappear implicitly. + +For any public field that remains supported, there should be either a normalized-config equivalence test, or an explicit parser/translation test. Fields that exist only in private Dreamverse integration code should be handled by a private adapter layer, not quietly converted into public FastVideo compatibility guarantees. + +Landed artifact: [inference_schema_parity_inventory.yaml](docs/design/inference_schema_parity_inventory.yaml) + guard [test_schema_parity_inventory.py](fastvideo/tests/api/test_schema_parity_inventory.py). + +## Canonical Public Schema + +The typed schema is implemented in [fastvideo/api/schema.py](fastvideo/api/schema.py). Envelope types: + +- `RunConfig` — offline: `generator` (GeneratorConfig) + `request` (GenerationRequest) +- `ServeConfig` — serving: `generator` + `server` (ServerConfig) + `default_request` (GenerationRequest) + optional `streaming` (StreamingConfig) + +Key nested types (summary; full fields in `schema.py`): + +- `GeneratorConfig` → `model_path`, `revision`, `trust_remote_code`, `engine` (EngineConfig: parallelism/offload/compile/quantization/flags), `pipeline` (PipelineSelection: workload_type, preset, preset_version, components, preset_overrides, experimental) +- `GenerationRequest` → `prompt`, `negative_prompt`, `inputs` (InputConfig), `sampling` (SamplingConfig), `runtime` (RequestRuntimeConfig), `output` (OutputConfig), `stage_overrides`, `state` (ContinuationState), `plan` (GenerationPlan), `extensions` +- `ContinuationState` → opaque `{kind: str, payload: dict[str, Any]}` +- `GenerationPlan` → `{stages: list[PlannedStage], final_stage: str | None}`; advanced/escape-hatch only + +### Important Semantics + +- Dataclasses are canonical for Python users. +- Dict and YAML/JSON are parsed into these dataclasses immediately. +- Unknown keys must raise validation errors. +- Typed `GenerationRequest` defaults come from the public schema, not from model-specific `SamplingParam.from_pretrained(...)` defaults. +- Legacy `generate_video(...)` continues to inherit model-specific sampling defaults until the SSIM/performance migration lands (PR 11). +- The only open-ended escape hatches are: + - `generator.pipeline.experimental` + - `request.extensions` + +That keeps the public contract strict without blocking experimental work. + +### Request Mutation Tracking + +When a `GenerationRequest` is parsed from a raw dict (YAML, JSON, or Python mapping), FastVideo records which fields the user explicitly provided versus which received schema defaults. This matters because `request_to_sampling_param()` must distinguish user-provided values (which should override model defaults) from schema defaults (which should NOT override model defaults). + +The tracking contract: + +- At parse time, the original raw dict and a baseline snapshot of the parsed object are stored on the request. +- Dataclass field mutations after parsing (e.g., `request.sampling.seed = 7`) are captured via lightweight `__setattr__` dirty-path recording. +- Dict-typed field mutations (e.g., `del request.stage_overrides["refine"]`) are detected at access time by diffing the current dict against the baseline snapshot. +- Setting a field to the schema default value IS captured as explicit, so it will override model defaults. +- The raw dict is reconciled lazily when `normalize_generation_request()` is called, not on every individual mutation. + +### Schema Purity and Model-Specific Fields + +The shared schema currently contains fields that are specific to one or two model families. These remain for backward compatibility during the initial migration (PRs 0-3) but should migrate to preset-owned typed override classes as the preset system lands (PRs 4-10). + +**SamplingConfig fields to migrate:** + +- `height_sr`, `width_sr`, `num_inference_steps_sr`: Hunyuan15 SR only. Target: `HunyuanSRStageOverride` in PR 10. +- `guidance_scale_2`, `boundary_ratio`: Wan2.2 and LingBotWorld only. Target: preset-owned overrides in the relevant model migration PR. + +**InputConfig fields to migrate:** + +- `mouse_cond`, `keyboard_cond`, `grid_sizes`: MatrixGame action control only. Target: `request.extensions` or a typed MatrixGame input config. +- `c2ws_plucker_emb`: LingBotWorld camera control only. Target: `request.extensions` or a typed LingBotWorld input config. +- `refine_from`, `stage1_video`: LongCat refinement only. Target: `LongCatRefineStageOverride` inputs or keep in `InputConfig` if they remain a public contract. + +**Universal fields that stay in the shared schema:** + +- `guidance_rescale`: used by multiple denoising stages across models, default 0.0. Universally applicable. +- `true_cfg_scale`: OpenAI adapter surface. Keep for protocol compatibility. + +### Escape Hatch Sunset + +`generator.pipeline.experimental` and `request.extensions` are intentional escape hatches for experimental and private work. They bypass strict validation by design. + +Rules for escape hatch usage: + +- New fields should not be added to `experimental` or `extensions` without a plan to either promote them to typed fields or remove them within two PR cycles. +- Each model migration PR (PRs 6-10) should review and shrink escape hatch usage for that model family. +- The compatibility layer currently routes unrecognized legacy kwargs into `experimental`. This pass-through should shrink as presets absorb model-specific fields. + +## Public Python API + +### New Canonical API + +```python +from fastvideo import VideoGenerator +from fastvideo.api import ( + GeneratorConfig, GenerationRequest, + EngineConfig, OutputConfig, + PipelineSelection, SamplingConfig, +) + +generator = VideoGenerator.from_pretrained( + config=GeneratorConfig( + model_path="/models/ltx2", + engine=EngineConfig(num_gpus=1), + pipeline=PipelineSelection( + workload_type="t2v", + preset="ltx2_two_stage", + ), + ) +) + +result = generator.generate( + GenerationRequest( + prompt="a fox running through snow", + sampling=SamplingConfig( + num_frames=121, height=1024, width=1536, + num_inference_steps=8, seed=42, + ), + output=OutputConfig(save_video=True, return_state=True), + ) +) +``` + +### Accepted Construction Forms + +Canonical: + +```python +VideoGenerator.from_pretrained(config=GeneratorConfig(...)) +VideoGenerator.from_config(GeneratorConfig(...)) +VideoGenerator.from_file("run.yaml") +``` + +Stable convenience constructor: + +```python +VideoGenerator.from_pretrained("model-id") +VideoGenerator.from_pretrained("model-id", num_gpus=2, use_fsdp_inference=False, ...) +``` + +Legacy compatibility: + +```python +VideoGenerator.from_pretrained(model_path, **legacy_kwargs) +``` + +All constructor forms normalize through the same typed path. Stable convenience kwargs remain supported with no deprecation warning. Advanced model/pipeline-specific kwargs are accepted during migration but only as compatibility inputs that normalize into `GeneratorConfig`. The thing being deprecated over time is the unbounded legacy kwarg surface, not the `from_pretrained(...)` entrypoint itself. + +### Generation Entry Point + +Canonical: `generator.generate(request: GenerationRequest) -> GenerationResult`. + +Compatibility alias: `generator.generate_video(prompt=..., **legacy_kwargs)` — converts legacy calls into a `GenerationRequest` and emits a deprecation warning. + +During the compat period, `generate(request=...)` uses schema defaults while `generate_video(...)` preserves legacy model-default behavior. These paths intentionally differ until preset-owned defaults replace the remaining `SamplingParam` default logic (migrated in PR 11). + +### Boundary Normalization Rule + +Every public inference entrypoint normalizes into typed config objects before touching legacy internals. That includes Python constructors, generation calls, CLI `generate`, CLI `serve`, and OpenAI/server request translation. Legacy internals (`FastVideoArgs`, `SamplingParam`) may remain temporarily, but only behind a typed normalization boundary. + +## Pipeline Presets + +### Definition + +An `InferencePreset` is a named model-owned preset that defines: + +- workload selection +- stage topology +- per-stage defaults +- stage names +- allowed stage override types +- init-time feature requirements + +The preset is not user-authored by default. It is supplied by the model integration. + +### Why Presets Are The Right Abstraction + +Users usually do not want to assemble a stage graph by hand. They want to say: + +- use LongCat distill + refine +- use Hunyuan 1080p SR +- use LTX2 two-stage continuation mode + +Presets provide a stable public noun for that behavior. + +### Preset Naming Rules + +- Use semantic names, not stage indices. +- Keep names stable across releases. +- If semantics change incompatibly, change `preset_version` or create a new preset name. + +Examples: `ltx2_base`, `ltx2_two_stage`, `longcat_distill_refine`, `hunyuan15_sr_720p`, `hunyuan15_sr_1080p`. + +### Preset-Owned Stage Names + +Stage names are public and stable within a preset. + +- LTX2: `base`, `refine` +- LongCat: `distill`, `refine` +- Hunyuan15: `base`, `sr_720p`, `sr_1080p` + +Public overrides should reference these stage names, never stage indices. + +## Stage Overrides + +The main user override surface for multi-stage pipelines is: + +```python +request.stage_overrides["refine"] = ... +``` + +Each model family should expose typed override classes for its stage names. Examples for the model families that land in PRs 6/9/10: + +```python +@dataclass +class LTX2RefineStageOverride: + enabled: bool | None = None + num_inference_steps: int | None = None + guidance_scale: float | None = None + add_noise: bool | None = None + image_crf: int | None = None + video_position_offset_sec: float | None = None + +@dataclass +class LongCatRefineStageOverride: + t_thresh: float | None = None + spatial_refine_only: bool | None = None + num_cond_frames: int | None = None + +@dataclass +class HunyuanSRStageOverride: + num_inference_steps: int | None = None + guidance_scale: float | None = None +``` + +### Strictness Rules + +- Stage names must exist in the selected preset. +- Override fields must be valid for that stage type. +- Unknown stage names and unknown fields must error. + +## Advanced Explicit Plans + +Presets should be the default API. `GenerationPlan` exists only for advanced composition or experimentation: + +- building a custom workflow that is not yet standardized as a preset +- debugging or benchmarking stage combinations +- prototyping a future preset + +Do not require `GenerationPlan` for normal users. + +## Continuation State + +Continuation must be a first-class part of the API. + +### Public Contract + +- `GenerationResult.state` may return a `ContinuationState`. +- `GenerationRequest.state` may accept a previously returned state. +- Most users should treat `state` as opaque and round-trip it back into the next request. + +### Why This Matters + +Dreamverse/LTX2 currently leaks continuation internals into app-level request fields like video conditions, audio clean latent, audio denoise mask, and segment offsets. Those should not remain top-level app-owned public API. + +### State Design + +Public surface: + +```python +@dataclass +class ContinuationState: + kind: str + payload: dict[str, Any] +``` + +Internally, FastVideo should also define typed model-specific state subclasses, e.g. `LTX2ContinuationState` (PR 7) and `LongCatIntermediateState` if ever needed. Minimal stable surface: return state, pass state back in, validate that the state is compatible with the active preset. + +Payload serialization: fields must be JSON-serializable or use an opaque blob-ID indirection for large tensors. This supports both the stateless OpenAI client round-trip AND future Dynamo prefill/decode disaggregation where prefill yields a state that decode hydrates across workers. + +## YAML / JSON Design + +YAML and JSON should be exact serializations of the typed schema, not a second unrelated config system. YAML is the primary documented format. JSON is accepted with the same schema. + +### Run Config Example + +```yaml +generator: + model_path: /models/ltx2 + engine: + num_gpus: 1 + parallelism: {tp_size: -1, sp_size: -1} + offload: {dit: false, text_encoder: false, vae: false, pin_cpu_memory: true} + pipeline: + workload_type: t2v + preset: ltx2_two_stage + components: + config_root: /models/ltx2-config + upsampler_weights: /models/ltx2-refine + lora_path: /models/ltx2-refine-lora + preset_overrides: + refine: {enabled: true, add_noise: true} + +request: + prompt: "a fox running through snow" + sampling: + num_frames: 121 + height: 1024 + width: 1536 + num_inference_steps: 8 + seed: 42 + output: {save_video: true, return_state: true} + stage_overrides: + refine: {num_inference_steps: 2, guidance_scale: 1.0} +``` + +### Serve Config Example + +```yaml +generator: + model_path: /models/ltx2 + engine: {num_gpus: 1} + pipeline: {workload_type: t2v, preset: ltx2_two_stage} + +server: {host: 0.0.0.0, port: 8000, output_dir: outputs/} + +default_request: + sampling: {num_frames: 121, height: 1024, width: 1536, num_inference_steps: 8} + output: {save_video: false, return_frames: false} +``` + +### Validation Rules + +- top-level schema must match `RunConfig` or `ServeConfig` +- unknown keys must fail +- dotted CLI overrides are applied to the nested config before typed parsing +- parse errors must include the exact nested path that failed + +## CLI Design + +Inference CLI reuses the best parts of the current training authoring flow (YAML-first authoring, dotted nested overrides, typed parsing after merge) but stays stricter than training at the public boundary because it is a user-facing API surface for Python, CLI, YAML/JSON, and serving. + +### Canonical CLI Forms + +```bash +fastvideo generate --config run.yaml +fastvideo generate --config run.yaml --request.sampling.seed 42 +fastvideo generate --config run.yaml --generator.engine.num_gpus 2 + +fastvideo serve --config serve.yaml +fastvideo serve --config serve.yaml --server.port 8090 +``` + +The CLI is config-only. Beyond `--config`, CLI input uses dotted override paths into the nested schema rather than maintaining a second flat flag surface. + +Implementation: YAML/JSON is loaded into a nested dict, dotted CLI overrides are applied to the nested dict, then the result is parsed into typed config objects. Flat CLI flags are rejected so the nested schema stays canonical. + +## OpenAI / Server Mapping + +`fastvideo serve` loads `ServeConfig`. Incoming HTTP requests are translated into `GenerationRequest` by: + +1. cloning `default_request` +2. applying API request fields onto that request +3. validating against the selected preset + +This is similar in spirit to the SGL pattern of merging user overrides onto model defaults. + +Rules: + +- HTTP request translation must not bypass typed validation. +- multi-stage defaults should come from the preset and `default_request`, not from ad hoc server-local logic. +- stateful continuation requests should accept and return typed `ContinuationState` payloads. + +Landed in PR 5 for the stateless OpenAI server at `fastvideo/entrypoints/openai/`. The streaming/session server (PRs 7.5-7.9) uses the same preset/default_request merge through `ServeConfig.streaming`. + +## Streaming Server + Dynamo Backend + +The typed public API is consumed by three server-class integrations. They must share one execution substrate so we don't grow three near-duplicate progress loops. + +### The three consumers + +| Consumer | Transport | Request shape | State | +|---|---|---|---| +| Stateless OpenAI (`fastvideo/entrypoints/openai/`) | HTTP POST | `GenerationRequest` merged onto `ServeConfig.default_request` | Stateless; continuation via opaque payload if needed | +| Streaming WebSocket (`fastvideo/entrypoints/streaming/`) | WebSocket JSON + binary fMP4 | `GenerationRequest` per segment, session-scoped | Server-held session (per-GPU continuation cache); snapshot on demand | +| Dynamo native backend (`ai-dynamo/dynamo/components/src/dynamo/fastvideo/`) | Dynamo RPC endpoint | `NvCreateVideoRequest` ↔ adapter ↔ `GenerationRequest` | Aggregated today; disaggregated prefill/decode later via `ContinuationState` | + +### Shared execution substrate: `VideoGenerator.generate_async` + +The OpenAI server, streaming server, and Dynamo backend all want the same thing: a typed async API that yields progress events and a typed final result. FastVideo exposes exactly one canonical entry point: + +```python +async def generate_async( + self, + request: GenerationRequest, +) -> AsyncGenerator[VideoEvent, None]: ... +``` + +Events: + +```python +@dataclass +class VideoProgressEvent: + step: int + total_steps: int + stage: str # "denoise" | "refine" | "decode" | ... + +@dataclass +class VideoPartialEvent: + frames: np.ndarray # shape: (num_frames, H, W, 3) + index: int # monotonic chunk index + +@dataclass +class VideoFinalEvent: + video_bytes: bytes | None # mp4-encoded if requested + tensor: torch.Tensor | None # raw if requested + metadata: dict[str, Any] + continuation_state: ContinuationState | None + +VideoEvent = VideoProgressEvent | VideoPartialEvent | VideoFinalEvent +``` + +The sync `generate_video(request=...) -> VideoResult` becomes a thin `asyncio.run` wrapper over `generate_async` that collects events and returns the final. + +### Streaming server mapping + +`fastvideo/entrypoints/streaming/` owns per-session state: + +- `SessionStore.hydrate(state: ContinuationState) -> session_id` +- `SessionStore.snapshot(session_id) -> ContinuationState` +- Per-GPU implicit continuation cache (today's internal behavior) is wrapped as a `SessionStore` implementation. + +Per-segment, the session writes a `GenerationRequest`, pipes the event stream to the WebSocket (progress → JSON messages, partial → fMP4 frames), and persists the final's `ContinuationState` into the session. + +### Dynamo backend mapping + +Dynamo's backend pattern (from `components/src/dynamo/sglang/`) is a pure Python import. FastVideo does not host a `fastvideo/entrypoints/dynamo/` subpackage; the integration lives in the Dynamo repo. FastVideo exposes a stable contract: + +| Surface | Exposed as | +|---|---| +| Construction | `VideoGenerator.from_pretrained(model_path, **typed_kwargs)` | +| Execution (async) | `VideoGenerator.generate_async(request) -> AsyncGenerator[VideoEvent, None]` | +| Execution (sync) | `VideoGenerator.generate_video(request=...) -> VideoResult` | +| Typed request | `fastvideo.api.GenerationRequest`, `SamplingConfig`, `InputConfig` | +| Typed result | `fastvideo.api.VideoResult`, `VideoEvent`, `ContinuationState` | +| Health-check input | `VideoGenerator.default_health_check_request() -> GenerationRequest` | +| Config dump | `config_to_dict(cfg)` (already exists) | + +Request/response mapping the Dynamo adapter must perform: + +``` +NvCreateVideoRequest -> fastvideo.api.GenerationRequest + prompt -> sampling.prompt + size="WxH" -> sampling.width, sampling.height + seconds -> seconds * nvext.fps -> sampling.num_frames + input_reference -> input.image_path | input.video_path + nvext.fps -> sampling.fps + nvext.num_frames -> sampling.num_frames (overrides seconds*fps) + nvext.num_inference_steps -> sampling.num_inference_steps + nvext.guidance_scale -> sampling.guidance_scale + nvext.seed -> sampling.seed + nvext.negative_prompt -> sampling.negative_prompt + response_format -> (handled at the adapter's output stage) + +VideoFinalEvent -> NvVideosResponse + video_bytes -> data[0].b64_json (if response_format=b64_json) + uploaded URL -> data[0].url (if response_format=url) + metadata.inference_time_s -> inference_time_s + continuation_state -> (reserved for future disaggregation) +``` + +All fields already exist (or will exist after PR 6's typed-kwarg expansion) on FastVideo's typed schema. **The adapter lives entirely in the Dynamo repo** at `components/src/dynamo/fastvideo/` — FastVideo does not host any Dynamo subpackage, dep, or CLI. The only FastVideo obligation is the stable public Python API listed above. + +### Constraints this places on other sections + +- **Continuation State** (see earlier section): `ContinuationState.payload` must be JSON-serializable or use an opaque blob-ID indirection for large tensors. This supports both the stateless OpenAI client round-trip *and* future Dynamo prefill/decode disaggregation, where prefill yields a state that decode hydrates across workers. +- **Typed GeneratorConfig** (see Public Python API): every flat legacy LTX2 kwarg currently used by the internal `gpu_pool.py` must have a typed home reachable from `GeneratorConfig`. Dynamo's `FastVideoArgGroup` builds the config from its CLI and must not have to know any legacy LTX2 name. +- **Public exports**: `from fastvideo import VideoGenerator`; `from fastvideo.api import GenerationRequest, SamplingConfig, ContinuationState, VideoResult, VideoEvent, VideoProgressEvent, VideoPartialEvent, VideoFinalEvent`. + +## Repo Layout + +### Shared Public API + +`fastvideo/api/` contains the shared public API package. Current files: + +- `schema.py` — `RunConfig`, `ServeConfig`, `ServerConfig`, `GeneratorConfig`, and all nested typed config dataclasses +- `sampling_param.py` — `SamplingParam` + `CacheParams` (canonical home since PR 4; former `configs/sample/base.py` location removed) +- `presets.py` — `InferencePreset`, `PresetStageSpec`, registry APIs +- `results.py` — `GenerationResult` / `VideoResult` +- `parser.py` — `from_dict`, `to_dict`, `load_yaml`, `load_json`, validation +- `overrides.py` — dotted override application +- `compat.py` — legacy Python kwargs translation +- `errors.py` — path-aware validation errors + +May split further by concern in a future cleanup. + +### Pipeline-Local Model-Owned Config + +Model-owned presets and override types live next to the model pipeline: + +```text +fastvideo/pipelines/basic/ltx2/ + ltx2_pipeline.py, presets.py, stage_overrides.py, continuation.py + +fastvideo/pipelines/basic/longcat/ + longcat_pipeline.py, presets.py, stage_overrides.py + +fastvideo/pipelines/basic/hunyuan15/ + hunyuan15_pipeline.py, hunyuan15_sr_pipeline.py, hunyuan15_2sr_pipeline.py, + presets.py, stage_overrides.py +``` + +PR 4 landed `presets.py` for all 13 model families. Remaining colocation targets are `pipeline_configs.py` (moving `configs/pipelines/.py`) and model-specific stages (moving `pipelines/stages/_*.py`); see [PR plan.md](PR%20plan.md) "Pipeline Package Structure". + +### Registry + +Central registry (`fastvideo/registry.py`) registers preset providers rather than owning all model-specific defaults directly. It answers: + +- which pipeline class corresponds to a model path +- which presets are available for that model family +- which override/state classes are valid for a selected preset + +## Relationship To Current Internal Classes + +This refactor does not require deleting current internals immediately. + +- `FastVideoArgs` is an internal compatibility/input adapter, no longer the primary public inference type. +- `SamplingParam` now lives in `fastvideo/api/sampling_param.py` and gets model-specific defaults from presets via `_from_preset()`. All 12 `SamplingParam` subclasses have been removed and the former `fastvideo/configs/sample/` directory has been deleted entirely (PR 4). It remains an internal adapter between the preset system and the runtime. +- current `PipelineConfig` classes can remain temporarily as internal component config carriers +- the new public schema is the stable boundary above them + +`VideoGenerator` accepts the new schema and translates down into current execution internals. Legacy `generate_video(..., **kwargs)` stays on the direct execution path during the compat period until SSIM/performance tests migrate in PR 11. + +## Model-Specific Design + +### LTX2 / Dreamverse + +LTX2 needs both: + +- init-time two-stage feature wiring +- request-time continuation/refine behavior + +Expressed as: + +- preset: `ltx2_two_stage` +- init-time fields: refine assets, optional config root, stage enablement +- request-time fields: stage override for refine behavior, optional returned continuation state + +#### LTX2 Preset Example + +```yaml +generator: + pipeline: + preset: ltx2_two_stage + components: + config_root: /models/ltx2-config + upsampler_weights: /models/ltx2-refine + lora_path: /models/ltx2-refine-lora + preset_overrides: + refine: {enabled: true, add_noise: true} +``` + +#### LTX2 Request Example + +```yaml +request: + prompt: "continue the previous sequence" + state: ${previous_result.state} + stage_overrides: + refine: + num_inference_steps: 2 + guidance_scale: 1.0 + image_crf: 18 + output: + return_state: true +``` + +#### LTX2 Explicit Decisions + +- `config_model_path` becomes `generator.pipeline.components.config_root` +- `ltx2_refine_*` stops being a pile of top-level kwargs +- continuation internals move into `ContinuationState` +- app-level code should pass `state`, not raw latent/audio condition payloads + +### LongCat + +LongCat should expose a named preset like `longcat_distill_refine` with stage topology `distill` and `refine`. + +User-facing override knobs remain model-specific (`t_thresh`, `spatial_refine_only`, `num_cond_frames`) but live under: + +```yaml +request: + stage_overrides: + refine: + t_thresh: 0.5 + spatial_refine_only: false + num_cond_frames: 8 +``` + +### Hunyuan 1.5 SR + +Hunyuan already behaves like an integrated multi-stage pipeline. Expose it via presets: `hunyuan15_sr_720p`, `hunyuan15_sr_1080p`. Users should not need to know the exact internal pipeline class split between base and SR stages. Per-stage override surface should stay small and mostly sampling-focused. + +Hunyuan15 presets (`hunyuan15_t2v_480p`, `hunyuan15_i2v_480p_distilled`, `hunyuan15_t2v_720p`, `hunyuan15_i2v_720p_distilled`, `hunyuan15_sr_1080p`) are implemented (PR 4). The `Hunyuan15_*_SamplingParam` subclasses have been removed; defaults (including precomputed sigmas) come from preset `defaults` dicts. Remaining work: adding typed `HunyuanSRStageOverride` classes and colocating PipelineConfig (PR 10). + +## Exact Compatibility Mapping + +Intended translation layer for common current fields. + +| Legacy Field | New Path | +| --- | --- | +| `model_path` | `generator.model_path` | +| `revision` | `generator.revision` | +| `trust_remote_code` | `generator.trust_remote_code` | +| `workload_type` | `generator.pipeline.workload_type` | +| `num_gpus` | `generator.engine.num_gpus` | +| `tp_size` | `generator.engine.parallelism.tp_size` | +| `sp_size` | `generator.engine.parallelism.sp_size` | +| `dit_cpu_offload` | `generator.engine.offload.dit` | +| `dit_layerwise_offload` | `generator.engine.offload.dit_layerwise` | +| `text_encoder_cpu_offload` | `generator.engine.offload.text_encoder` | +| `image_encoder_cpu_offload` | `generator.engine.offload.image_encoder` | +| `vae_cpu_offload` | `generator.engine.offload.vae` | +| `pin_cpu_memory` | `generator.engine.offload.pin_cpu_memory` | +| `enable_torch_compile` | `generator.engine.compile.enabled` | +| `torch_compile_kwargs` | split across `generator.engine.compile.backend`, `.fullgraph`, `.mode`, `.dynamic`; uncommon keys land in `.extras` | +| `enable_torch_compile_text_encoder` | `generator.engine.compile.text_encoder_enabled` | +| `enable_stage_verification` | `generator.engine.enable_stage_verification` | +| `prompt_txt` | `request.inputs.prompt_path` | +| `prompt` | `request.prompt` | +| `negative_prompt` | `request.negative_prompt` | +| `image_path` | `request.inputs.image_path` | +| `video_path` | `request.inputs.video_path` | +| `output_path` | `request.output.output_path` | +| `output_video_name` | `request.output.output_video_name` | +| `save_video` | `request.output.save_video` | +| `return_frames` | `request.output.return_frames` | +| `num_videos_per_prompt` | `request.sampling.num_videos_per_prompt` | +| `seed` | `request.sampling.seed` | +| `num_frames` | `request.sampling.num_frames` | +| `height` | `request.sampling.height` | +| `width` | `request.sampling.width` | +| `fps` | `request.sampling.fps` | +| `num_inference_steps` | `request.sampling.num_inference_steps` | +| `guidance_scale` | `request.sampling.guidance_scale` | +| `guidance_scale_2` | `request.sampling.guidance_scale_2` | +| `guidance_rescale` | `request.sampling.guidance_rescale` | +| `true_cfg_scale` | `request.sampling.true_cfg_scale` | +| `boundary_ratio` | `request.sampling.boundary_ratio` | +| `sigmas` | `request.sampling.sigmas` | +| `enable_teacache` | `request.runtime.enable_teacache` | +| `return_trajectory_latents` | `request.runtime.return_trajectory_latents` | +| `return_trajectory_decoded` | `request.runtime.return_trajectory_decoded` | + +### Private Dreamverse Adapter Mapping + +The mappings below are useful for private Dreamverse migration, but they should not be treated as a public FastVideo backward-compatibility promise unless and until those fields actually exist in the public repo surfaces. + +| Private Adapter Field | New Path | +| --- | --- | +| `config_model_path` | `generator.pipeline.components.config_root` | +| `ltx2_refine_enabled` | `generator.pipeline.preset_overrides.refine.enabled` | +| `ltx2_refine_upsampler_path` | `generator.pipeline.components.upsampler_weights` | +| `ltx2_refine_lora_path` | `generator.pipeline.components.lora_path` | +| `ltx2_refine_num_inference_steps` | `request.stage_overrides.refine.num_inference_steps` | +| `ltx2_refine_guidance_scale` | `request.stage_overrides.refine.guidance_scale` | +| `ltx2_refine_add_noise` | `generator.pipeline.preset_overrides.refine.add_noise` | +| `ltx2_image_crf` | `request.stage_overrides.refine.image_crf` | +| `return_continuation_state` | `request.output.return_state` | + +### LongCat Legacy Mapping + +| Legacy Field | New Path | +| --- | --- | +| `refine_from` | `request.inputs.refine_from` | +| `stage1_video` | `request.inputs.stage1_video` | +| `t_thresh` | `request.stage_overrides.refine.t_thresh` | +| `spatial_refine_only` | `request.stage_overrides.refine.spatial_refine_only` | +| `num_cond_frames` | `request.stage_overrides.refine.num_cond_frames` | + +## Validation and Error Handling + +### Strict by Default + +All structured inputs should be strict by default: unknown keys error, wrong types error, invalid stage names error, incompatible state/preset combinations error. + +### Exceptions + +The only intentionally open-ended fields are `generator.pipeline.experimental` and `request.extensions`. These must be clearly documented as unstable and unsupported for long-term API compatibility. + +### Error Quality + +Validation errors should include the full nested path, expected type or valid choices, and preset/stage context when relevant: + +```text +Invalid field: request.stage_overrides.refine.num_inference_steps +Expected int, got "two" +Preset: ltx2_two_stage +Stage: refine +``` + +## Implementation Plan + +### Phases 0-5: Landed + +- Phase 0 — Schema Parity Inventory: inventory complete; field classifications live in `docs/design/inference_schema_parity_inventory.yaml`; parity test guard in `fastvideo/tests/api/test_schema_parity_inventory.py`. +- Phase 1 — Shared Schema: `fastvideo/api/` with typed dataclasses, parser, validation, dotted overrides, `RunConfig`/`ServeConfig`. +- Phase 2 — VideoGenerator Compat: `from_config`, `from_file`, `generate(request=...)`, legacy `from_pretrained(..., **kwargs)` and `generate_video(..., **kwargs)` as compat shims routed through typed normalization. +- Phase 3 — CLI Refactor: `fastvideo generate` and `fastvideo serve` parse nested YAML/JSON with training-style dotted overrides; flat flag expansion removed as the canonical path. +- Phase 4 — Preset System: shared registry + pipeline-local `presets.py` for all 13 families; all 12 `SamplingParam` subclasses removed; `SamplingParam` moved to `fastvideo/api/sampling_param.py`. +- Phase 5 — Server Request Translation: `fastvideo serve` loads `ServeConfig`; stateless OpenAI endpoint clones `default_request` and merges validated user overrides. + +### Remaining Phases + +- **Phase 6 — LTX2 Public Upstream Path** (PR 6): upstream `ltx2_two_stage` preset; upstream continuation-state contract; upstream only repo-visible/public LTX2 surfaces into FastVideo. +- **Phase 7 — Dreamverse Adapter Migration** (PR 7 + private repo work): translate private Dreamverse-only request/config fields in a private adapter; replace raw app-owned continuation kwargs with `state` in the private server; do not expand the public FastVideo compatibility promise just to match private adapter fields. +- **Phase 7.5-7.10 — Streaming Server and Dynamo Contract** (PRs 7.5-7.10): upstream the streaming server (skeleton, GPU pool, prompt enhancer, auxiliaries, router) consuming `generate_async`; land the Dynamo backend contract (`VideoGenerator.generate_async`, health-check helper) with the Dynamo backend package itself living in the Dynamo repo. +- **Phase 8 — Model Migration and Docs** (PRs 9-10, 12): colocate `configs/pipelines/.py` with pipeline implementations; add typed stage override classes for multi-stage models; update basic examples to the new API; document YAML-first inference config and migration guidance. +- **Phase 8.5 — Golden-Test Migration** (PR 11): keep SSIM/performance regression tests on legacy Python generation while preset defaults are still settling; one dedicated migration pass after the preset system and model-default behavior are stable; complete this migration before removing legacy Python inference entrypoints or kwargs. +- **Phase 9 — Deprecation and Cleanup** (PR 13): deprecate direct public use of `FastVideoArgs`; deprecate direct public use of `SamplingParam`; gradually reduce public documentation for flat flags; eventually remove legacy kwargs after downstream migration is complete. + +## Final Recommendation + +The public FastVideo inference API is being rebuilt around: + +- typed nested configs +- model-owned named presets +- semantic stage overrides +- first-class continuation state +- YAML-first CLI with dotted overrides + +The primary abstraction is `InferencePreset`, not raw kwargs and not a fully manual stage graph. + +The repo is moving model-specific defaults closer to each pipeline, while keeping the public schema and parsing logic centralized. + +Regression and quality tests follow the rollout. Unit/entrypoint tests migrated to the typed API early, but SSIM/performance suites only move once the typed path can express all current knobs without compatibility exceptions and produces stable defaults through presets (PR 11). + +End state: + +- stable Python typing +- clean YAML/JSON support +- a much better CLI story +- a sane path for Dreamverse/LTX2 +- a unified abstraction for LongCat, Hunyuan, and future multi-stage models diff --git a/.agents/memory/dreamverse-integration/source-archive/dreamverse_integration.md b/.agents/memory/dreamverse-integration/source-archive/dreamverse_integration.md new file mode 100644 index 0000000000..1e137e277e --- /dev/null +++ b/.agents/memory/dreamverse-integration/source-archive/dreamverse_integration.md @@ -0,0 +1,285 @@ +# Dreamverse ↔ FastVideo Integration + +## Status + +Working integration record. Captures how Dreamverse consumes the +FastVideo public API today, what's already shared, what's still ad +hoc, and what migrations land alongside each PR in the API refactor +sequence. + +Pinned versions (last reconciled this session): + +| Repo | Branch | Commit | Note | +|---|---|---|---| +| FastVideo (public) | `origin/main` | `70ee5d23` | PR 6 merged | +| FastVideo (public) | `will/api_7` | `3de5f833` | PR 7 in flight (typed continuation state) | +| FastVideo-internal | `will/rebase-nbv` | `1adc513e` | pre-PR-1 on the API refactor; has live realtime runtime | +| Dreamverse | `master` | `dc500330` | uses local + remote FastVideo runtimes via `server/runtime/` | + +## Related Documents + +- [PR plan.md](../../PR%20plan.md) — PR-by-PR sequence for the API refactor +- [apirefactor.md](../../apirefactor.md) — design spec +- [streaming-server-upstream-plan.md](streaming-server-upstream-plan.md) — upstream plan for `ui/ltx2-streaming/server/` +- `../../../Dreamverse/server/video_generation.py` — Dreamverse's worker + local `ContinuationState` +- `../../../Dreamverse/server/runtime/{factory,backend,gpu_pool,interfaces}.py` — runtime abstraction +- `../../../FastVideo-internal/fastvideo/entrypoints/realtime/{api_server,local_runtime}.py` — internal's realtime runtime (PR 7.5/7.6 upstream source) + +## Surface Area + +Dreamverse depends on FastVideo across three surfaces. Listed in order +of how stable each is. + +### 1. Pipeline construction (stable) + +`Dreamverse/server/video_generation.py:VideoGenerationWorker` calls +`VideoGenerator.from_pretrained(...)` with flat LTX-2 kwargs today. +After PR 6 the typed `GeneratorConfig` path exists; Dreamverse can +migrate at its own pace. + +| Dreamverse usage | FastVideo public surface (post-PR 6) | +|---|---| +| `VideoGenerator.from_pretrained(model_path, ltx2_refine_enabled=…, …)` | `VideoGenerator.from_pretrained(config=GeneratorConfig(...))` | +| Flat `torch_compile_kwargs={…}` dict | `engine.compile.{backend,fullgraph,mode,dynamic,extras}` | +| `ltx2_vae_tiling=True` | `pipeline.vae_tiling=True` | +| `ltx2_refine_*` family | `pipeline.preset_overrides.refine.*` + `pipeline.components.upsampler_weights` | +| `enable_torch_compile_text_encoder` | `engine.compile.text_encoder_enabled` | + +The legacy flat-kwarg path stays supported via `compat.py`; migration +is opt-in. PR 13's deprecation warnings are the eventual nudge. + +### 2. Realtime runtime (in flight: PRs 7.5–7.6) + +`Dreamverse/server/runtime/factory.py` selects a runtime backend at +process start: + +```python +def create_runtime_pool() -> RuntimePool: + if os.getenv("FASTVIDEO_REALTIME_BASE_URL"): + return FastVideoRealtimePool(base_url=..., ws_url=..., default_model_id=...) + return GPUPool(get_available_gpus()) # in-process, wraps fastvideo.entrypoints.realtime.local_runtime +``` + +Both backends speak the same `RuntimePool` / `RuntimeSlot` Protocol +(`server/runtime/interfaces.py`): + +- `acquire(client_id, websocket=None) -> (gpu_id, RuntimeSlot)` +- `release(client_id)` +- `RuntimeSlot.{join_user, user_step, leave_user, register_stream_queue, …}` + +Today both impls reach into FastVideo-internal's +`fastvideo.entrypoints.realtime.local_runtime` (which exposes +`RealtimeRuntimeConfig`, `GPUPool`, `GPUSlot`). The remote backend +talks HTTP+WS to a separately-deployed runtime of the same shape. + +**Contract that PR 7.5/7.6 must preserve:** + +- `RealtimeRuntimeConfig` accepts `model_registry`, `default_model_id`, + `default_height/width/num_frames/fps/num_inference_steps/guidance_scale/seed/negative_prompt`, + `default_ltx2_image_crf`, `startup_warmup_{enabled,prompt,timeout_seconds}`. +- `GPUPool(gpu_ids: list[int], config: RealtimeRuntimeConfig)` constructor. +- `pool.initialize() / shutdown() / acquire() / release() / get_status()`. +- HTTP endpoints on the remote variant: `GET /healthz`, `GET /readyz`, + `GET /status`, `WS /ws`. (These already match what + `Dreamverse/server/routes/health.py` consumes.) + +When PR 7.6 lands the upstream of `fastvideo/entrypoints/realtime/`, +Dreamverse should not need any code change unless we rename the import +path. **Open: do we rename `realtime/` → `streaming/` to match the +public package introduced in PR 5.5?** A deprecation alias module +keeps both working during transition. + +### 3. Continuation state (PR 7) + +`Dreamverse/server/video_generation.py:89 ContinuationState` is +Dreamverse's hand-rolled per-session state holder. PR 7 introduces +the typed equivalent at `fastvideo/pipelines/basic/ltx2/continuation.py`. + +#### Field mapping + +| Dreamverse | PR 7 `LTX2ContinuationState` | Notes | +|---|---|---| +| `video_images: list[PIL.Image]` | `video_frames: list[np.ndarray]` (uint8 H×W×3) | numpy is leaner; Dreamverse already round-trips PIL→numpy→PIL just to add noise | +| `audio_latents: torch.Tensor` `[B, C, T, mel]` | `audio_latents: torch.Tensor` (safetensors-serialized; bf16-safe) | unchanged shape; safetensors preserves dtype incl. `bfloat16` | +| `LTX2_VIDEO_CONDITIONING_FRAME_IDX` (env) | `video_conditioning_frame_idx: int` | env constant → per-state field | +| `LTX2_VIDEO_CONDITIONING_STRENGTH` (env) | `video_conditioning_strength: float` | env constant → per-state field | +| `AUDIO_CONDITIONING_NUM_FRAMES` (env) | `audio_conditioning_num_frames: int` | env constant → per-state field | +| `AUDIO_CONDITIONING_STRENGTH` (env) | `audio_conditioning_strength: float` | env constant → per-state field | +| `audio_lps` (passed into `apply_audio`) | `audio_sample_rate: int \| None` | analogous; rename worth confirming with audio team | +| Computed `prefix_sec` per segment | `video_position_offset_sec: float` | **see open question below** | +| `segment_idx` (param to apply_*) | `segment_index: int` | per-state field | +| `VIDEO_CONTEXT_NOISE`, `AUDIO_CONTEXT_NOISE`, `ENABLE_AUDIO_COND` | not on state | runtime policy / regularization knobs, not portable session data | +| `apply_video / apply_audio / save_video / save_audio_latents / clear` | not on PR-7 state class | state is a pure data carrier; runtime owns lifecycle policy | + +PR-7 is a strict superset of Dreamverse's data model **plus** lifts +several env globals into per-session typed fields. + +#### Lifecycle mapping + +| Dreamverse pattern | `SessionStore` API | +|---|---| +| `self.continuation = ContinuationState()` per session | `state = session_store.snapshot(sid) or LTX2ContinuationState()` | +| `apply_video(req_kwargs, segment_idx)` + `apply_audio(req_kwargs, segment_idx, audio_lps)` | `state = session_store.snapshot(sid)`; runtime builds request from `state.video_frames` / `state.audio_latents` etc. | +| `save_video(frames)` + `save_audio_latents(latents)` | runtime constructs new `LTX2ContinuationState`, then `session_store.store(sid, new_state.to_continuation_state())` | +| `clear()` at end of session | `session_store.drop(sid)` | + +`SessionStore` and `BlobStore` ABCs ship with thread-safe in-memory +defaults (`InMemorySessionStore`, `InMemoryBlobStore`). Dreamverse can +adopt them as-is for the local runtime; remote runtimes can plug in +redis-backed implementations later. + +#### Wire format (HTTP/WS round-trip) + +Dreamverse's `FastVideoRealtimePool` already speaks the realtime +runtime's HTTP+WS protocol. When PR 7.5/7.6 land state emission on +the server side, the on-the-wire payload is the public envelope: + +```json +{ + "kind": "ltx2.v1", + "payload": { + "schema_version": 1, + "segment_index": 3, + "video_conditioning_frame_idx": 9, + "video_conditioning_strength": 0.75, + "audio_sample_rate": 24000, + "audio_conditioning_num_frames": 5, + "audio_conditioning_strength": 0.5, + "video_position_offset_sec": 0.2, + "video": {"frames_b64": ["..."]}, + "audio": {"safetensors_b64": "..."}, + "metadata": {} + } +} +``` + +JSON-serializable end-to-end; safetensors blob preserves audio dtype +(incl. bf16). For payloads above the inline threshold a `BlobStore` +indirection replaces the b64-encoded body with `{"blob_id": "..."}`; +the blob itself stays inside the runtime that produced it. + +## Migration Plan + +Per PR landed, Dreamverse adoption is opt-in. + +### After PR 7 merges + +Single-file change in Dreamverse, ~50-line PR: + +1. Replace `server/video_generation.py:89 ContinuationState` import + with `from fastvideo.pipelines.basic.ltx2.continuation import LTX2ContinuationState`. +2. Move `apply_video`, `apply_audio`, `save_video`, `save_audio_latents`, + `clear` off the state class onto `VideoGenerationWorker` (these are + runtime policy that uses the state, not part of the state itself). +3. Update `apply_audio` to read knobs from `state.audio_conditioning_num_frames` + and `state.audio_conditioning_strength` instead of the env globals + `AUDIO_CONDITIONING_NUM_FRAMES` / `AUDIO_CONDITIONING_STRENGTH`. The + env globals can stay as defaults that populate the state when a new + session starts. +4. Same treatment for video knobs: `state.video_conditioning_frame_idx`, + `state.video_conditioning_strength`. +5. Frame storage swaps `list[PIL.Image]` for `list[np.ndarray]` — + simpler `save_video` (no PIL conversion) and simpler `clear` (no + `.close()` loop). + +### After PR 7.5 lands streaming server skeleton + +Dreamverse's runtime/factory.py either: + +- Continues to construct `GPUPool` from `RealtimeRuntimeConfig` (the + current path), now backed by the upstreamed `fastvideo/entrypoints/realtime/`. +- Or migrates to the upstream's `ServeConfig.streaming` shape and + invokes `fastvideo serve --config realtime.yaml` as the launch path. + +Either way, `Dreamverse/server/runtime/interfaces.py` `RuntimePool` / +`RuntimeSlot` Protocol can stay in place — it was modeled after the +realtime runtime's surface. No interface change needed. + +### After PR 7.6 lands the GPU pool upstream + +- The `local_runtime.py` import in + `Dreamverse/server/runtime/gpu_pool.py:24` becomes a public import + with the same symbols (`RealtimeRuntimeConfig`, `GPUPool`, + `get_available_gpus`). +- Per-GPU continuation state inside the worker (`ltx2_continuation_images`, + `ltx2_continuation_audio_latents`) gets replaced by a `SessionStore` + reference. Dreamverse doesn't see this change — it's runtime-internal. +- `request.state` / `result.state` round-trip starts working end-to-end + on the local runtime. Dreamverse's worker can begin reading + `result.state` and feeding `request.state` between segments. + +### After PR 7.10 lands the Dynamo backend contract + +- `VideoGenerator.generate_async(...) -> AsyncGenerator[VideoEvent, None]` + is the canonical API. +- Dreamverse's per-segment `user_step` flow can migrate from the legacy + sync `generate_video(..., **kwargs)` path to consuming the typed + event stream. Optional; the sync wrapper stays. + +## Open Questions + +### `video_position_offset_sec` semantics + +Dreamverse computes `prefix_sec = float(audio_extra) / 24.0` per +segment in `apply_audio`. Not persisted on `ContinuationState`. + +PR-7 has `video_position_offset_sec` as a **state field**. Two valid +interpretations: + +(a) **Persistent across segments** — accumulating time offset for +long sessions; useful for time-coherent audio chaining. +(b) **Per-segment hint that rides on the carrier** — runtime +overwrites every time; field is harmless redundancy. + +Field's docstring leans toward (b). Decide before PR 7.6 starts +emitting/consuming it. If we land on (a), document the accumulation +rule explicitly. + +### `BlobStore` / `SessionStore` lifecycle ownership + +PR 7's in-memory implementations have no eviction, no TTL, no +automatic blob cleanup on state replacement. Documented as a +per-deployment policy decision. + +When PR 7.5/7.6 land the live consumer, who owns: + +- bounded session capacity (LRU? TTL? hard max?) +- blob `drop()` chained when a state is replaced +- session expiry on websocket disconnect + +Probably the streaming server's session manager, but worth stating +explicitly in PR 7.5's design. + +### `realtime/` vs `streaming/` package naming + +Currently: + +- Public PR 5.5 introduced `fastvideo/entrypoints/streaming/` (skeleton + typed config). +- Internal has `fastvideo/entrypoints/realtime/` (live runtime). +- Dreamverse imports from `fastvideo.entrypoints.realtime` (per the internal name). + +PR 7.5 either picks one or ships a deprecation alias module. +Recommendation in `streaming-server-upstream-plan.md`: keep +`streaming/` (it's the post-PR-5.5 public name), provide +`realtime/__init__.py` as a re-export with a `DeprecationWarning` for +one release cycle so internal/Dreamverse can land import updates. + +## Test Coverage on the FastVideo Side + +PR 7 ships: + +- `fastvideo/tests/api/test_ltx2_continuation.py` — typed + state round-trip (inline + blob), bf16 preservation, JSON + serializability, kind/version validation, schema_version guard. +- `fastvideo/tests/entrypoints/streaming/test_session_store.py` — + store/snapshot/hydrate/drop behavior on `InMemorySessionStore`; + put/get/drop on `InMemoryBlobStore`; thread-safety of both. + +PR 7.5+ should add a contract test that exercises the round-trip via +the same wire format Dreamverse's `FastVideoRealtimePool` consumes. + +## Changelog + +| Date | Change | +|------|--------| +| 2026-04-23 | Initial draft. Captures PR 6 / PR 7 mapping; open questions on `video_position_offset_sec`, lifecycle ownership, and `realtime/` vs `streaming/` naming. | diff --git a/.agents/memory/dreamverse-integration/source-archive/dreamverse_review.md b/.agents/memory/dreamverse-integration/source-archive/dreamverse_review.md new file mode 100644 index 0000000000..976cff0361 --- /dev/null +++ b/.agents/memory/dreamverse-integration/source-archive/dreamverse_review.md @@ -0,0 +1,390 @@ +# Dreamverse Integration Review Log + +This document tracks design decisions, open questions, and integration-time +choices made while landing the public-side stacked PRs (7.7 → 8) and switching +Dreamverse from `FastVideo-internal` to public `FastVideo`. The user will +review this carefully — entries are deliberately verbose about *why*. + +## Goal + +Replace Dreamverse's dependency on `FastVideo-internal` with the public +`FastVideo` package, using the upstreamed streaming server stack +(`fastvideo.entrypoints.streaming.*`) where Dreamverse currently has local +copies or imports private modules. + +## Surfaces Dreamverse currently uses from FastVideo-internal + +(from `/home/william5lin/Dreamverse/server/`, scanned 2026-04-26): + +| Dreamverse import | Internal path | Public replacement | +|---|---|---| +| `fastvideo.entrypoints.realtime.local_runtime.RealtimeRuntimeConfig` | `FastVideo-internal/fastvideo/entrypoints/realtime/local_runtime.py` | (none) — Dreamverse rewires through `streaming.gpu_pool.SubprocessGpuPool` | +| `fastvideo.entrypoints.realtime.local_runtime.GPUPool` | same as above | `fastvideo.entrypoints.streaming.gpu_pool.SubprocessGpuPool` (PR 7.6) | +| `fastvideo.configs.pipelines.base.PipelineConfig` | already in public | unchanged | +| `fastvideo.entrypoints.video_generator.VideoGenerator` | already in public | unchanged | +| `fastvideo.layers.quantization.fp4_config.FP4Config` | already in public | unchanged | +| `fastvideo.utils.maybe_download_model` | already in public | unchanged | +| `fastvideo.models.audio.ltx2_audio_processing.AudioProcessor` | already in public | unchanged | +| `fastvideo.models.loader.component_loader.ComponentLoader` | already in public | unchanged | +| `fastvideo.models.dits.ltx2.*` | already in public | unchanged | +| local copy: `Dreamverse/server/prompt_enhancer.py` (1933 lines) | mirrors `FastVideo-internal/.../prompt_enhancer.py` | `fastvideo.entrypoints.streaming.prompt.*` (PR 7.7) | +| local copy: `Dreamverse/server/prompt_safety.py` | mirrors `FastVideo-internal/.../prompt_safety.py` | `fastvideo.entrypoints.streaming.prompt.safety` (PR 7.8) | +| local copy: `Dreamverse/server/session_logger.py` | mirrors `FastVideo-internal/.../session_logger.py` | `fastvideo.entrypoints.streaming.session_logger` (PR 7.8) | +| local copy: `Dreamverse/server/rewrite_prompt_payload.py` | mirrors `FastVideo-internal/.../rewrite_prompt_payload.py` | `fastvideo.entrypoints.streaming.prompt.rewrite` (PR 7.8) | +| local copy: `Dreamverse/server/mock_server.py` (1200 lines) | mirrors `FastVideo-internal/.../mock_server.py` | `fastvideo.entrypoints.streaming.mock_server` (PR 7.8) | +| local copy: `Dreamverse/server/session_init_image.py` | mirrors `FastVideo-internal/.../session_init_image.py` | `fastvideo.entrypoints.streaming.session_init_image` (PR 7.5 — already public) | + +## Design decisions made (auto-resolved) + +### D-1: Realtime runtime → streaming GpuPool migration shape + +**Context.** Dreamverse's `server/runtime/gpu_pool.py` thin-wraps +`fastvideo.entrypoints.realtime.local_runtime.GPUPool`, which takes a +`RealtimeRuntimeConfig(model_registry=…, default_model_id=…, default_height=…, +default_width=…, default_num_frames=…, default_num_inference_steps=…, +startup_warmup_*…)`. The public `streaming.gpu_pool.SubprocessGpuPool` takes a +typed `GeneratorConfig` + `GpuPoolConfig` + `WarmupConfig`. + +The shapes differ in two important ways: + +1. The internal version had a multi-model registry (`model_id → model_config` + dict). The public version is single-model (one `GeneratorConfig`). +2. The internal version flattened a few sampling defaults (height/width/frames/ + steps) into the runtime config. The public version expects them as part of + the per-request `SamplingConfig`. + +**Decision.** Dreamverse will: +1. Drop the multi-model registry on the integration branch (it is not used in + production today — Dreamverse boots one model per replica). +2. Construct a `GeneratorConfig` for the chosen model from `MODEL_REGISTRY[id]` + and pass it to `SubprocessGpuPool`. +3. Move the `default_height` / `default_width` / `default_num_frames` / + `default_num_inference_steps` defaults into a server-side + `default_request: GenerationRequest` template the session controller fills + from per-request input. + +**Why.** Multi-model is feasible to add back later (one pool per model id, +acquire by `(session_id, model_id)`), but not on the migration branch — that +would couple the upstream switch to a feature redesign. Punting keeps the +upstream switch a pure mechanical refactor. + +**Risk.** If a Dreamverse code path silently relied on the registry to swap +models per-session, the migration branch will surface that as a missing-model +error. The integration tests must exercise at least one segment per supported +model id before merging the Dreamverse branch. + +### D-2: PR 7.7 prompt enhancer API surface narrower than the internal one + +**Context.** The upstreamed `PromptEnhancer.enhance/auto_extend/rewrite` returns +`LLMResponse(content, provider, model, latency_ms, fallback_used)`. The internal +`enhance_prompt` / `generate_auto_prompt` / `rewrite_prompt_sequence` returns +`EnhanceResult(prompt, fallback_used, error, provider, model, latency_ms)` / +`RewriteResult(prompts, …, rollout_id, rollout_label, raw_response_text)`. + +**Decision.** The Dreamverse integration branch will adapt at the call site: +- `enhancer.enhance_prompt(...)` → `enhancer.enhance(prompt)` + a thin shim + that maps the structured response into the existing `EnhanceResult` shape + for the session-controller code path. Move the shim to + `Dreamverse/server/prompting/_internal_compat.py`. +- The locked-segment / next-segment-index plumbing the internal version + built into the user payload becomes Dreamverse-side template logic in + the shim. +- The JSON-shaped responses the internal prompts assume (`{"next_prompt": + "..."}` / `{"segment_prompts": [...]}`) become Dreamverse-side + parsing in the shim, since the public `LLMResponse` is intentionally raw. + +**Why.** The public surface stays minimal and provider-agnostic; the +LTX-2-specific orchestration (locked segments, rollout id/label, JSON +schemas) is an internal-UI concern, not something every public consumer +should wear. Dreamverse keeps its existing call shape; the public stays +clean. + +**Open question for review:** Should we promote some of this into +`fastvideo.entrypoints.streaming.prompt.ltx2_orchestration` (or similar) +once a second consumer appears? Logging here so we have the option. + +### D-3: Multi-stage provider race (Dreamverse) vs sequential fallback (public) + +**Context.** The internal enhancer runs all providers in a stage in parallel +and returns the first to succeed (`_run_provider_race`). The public +enhancer runs providers strictly sequentially with retryable-error fallback. + +**Decision.** Public stays sequential for PR 7.7. The race-based fallback is +a Dreamverse-specific tail-latency optimization that depends on parallel API +budgets; promoting it would force every public consumer to have multiple +provider keys configured. Dreamverse can keep `_run_provider_race` as an +internal optimization on its side. + +**Risk.** First-segment latency on Dreamverse may regress slightly when +Cerebras is having a bad minute (sequential fallback waits the full +20s timeout before trying Groq). If this is a real production concern, +add a public knob like `concurrency: int = 1` on `PromptEnhancer` that +gates a race path — but only after measuring. + +### D-4: Skipping PR 7.9 router for the integration branch + +**Context.** The internal stack ships a `router/main.py` that load-balances +across replicas with health checks. Dreamverse's deployment uses a single +replica per region (per `gpu_pool.py:_parse_requested_gpu_limit`). + +**Decision.** Land PR 7.9 on the public side (so the surface is upstreamed) +but skip wiring it into the Dreamverse integration branch. Dreamverse's +`server/main.py` does not import from `router/`. + +### D-5: Audio re-encode (PR 7.10) needed for streaming, deferred + +**Context.** The internal streaming server's per-step path runs an audio +re-encode (`_re_encode_audio` inside `_stream_av_fmp4_events` / +`do_step_ltx2`) so each fMP4 segment ships with continuation-conditioning +audio. The whole-segment `pool.run()` path the public streaming server +currently uses doesn't need this. The PR plan defers re-encode integration +to PR 7.10 (`generate_async` / per-step streaming). + +**Decision.** Land PR 7.10's `generate_async` on the public side. The +Dreamverse integration branch initially keeps using `pool.run()` (whole +segment, no re-encode); a follow-up branch swaps it to +`generate_async` + audio re-encode once that path is exercised end-to-end. + +### D-6: `realtime/local_runtime.py` is *not* upstreamed + +**Context.** It is the FastVideo-internal precursor to `streaming.gpu_pool`. +Upstreaming both would create two GPU pool implementations in the public +repo. + +**Decision.** Don't upstream `realtime/local_runtime.py`. Dreamverse switches +to `streaming.gpu_pool.SubprocessGpuPool` on the integration branch. The +internal module can be deleted from FastVideo-internal at a follow-up. + +## Open questions for user review + +Each section below is a place the auto-decision could plausibly be wrong. +Please flip / annotate these in review. + +### Q-1 Multi-model GPU pool (D-1) + +Does any current Dreamverse production flow load multiple model ids +concurrently? If yes, we need to either (a) keep `realtime/local_runtime` +alive on the internal side until the public side gains a multi-model pool, +or (b) build the multi-model abstraction upstream as part of PR 7.6 follow-up +work. + +### Q-2 Promoting LTX-2 prompt orchestration (D-2) + +The locked-segments / next-segment-index / JSON-response orchestration is +LTX-2-specific. If Cosmos / Wan / Hunyuan ever grow a similar continuation +flow, we'll regret keeping the orchestration on the consumer side. Worth +promoting now? + +### Q-3 Race-based provider fallback (D-3) + +The sequential fallback in the public enhancer adds up to `timeout_ms` of +extra latency per failing provider before the next is tried. For Dreamverse +that's 20s. Should we land the race path now behind a `concurrency: int = 1` +knob, or wait until we have data? + +### Q-4 Router upstream skip on Dreamverse branch (D-4) + +We're upstreaming PR 7.9 (router) but not consuming it in the Dreamverse +integration branch. Is that right? Dreamverse currently has no router +component, so the answer is probably yes — but flagging. + +### Q-5 generate_async cutover for the streaming path (D-5) + +The plan leaves Dreamverse using `pool.run` (whole segment) initially. +Audio re-encode for cross-segment continuity is deferred to a follow-up. +Is that acceptable for the first switch, or does Dreamverse audio quality +regress relative to the internal path until 7.10 is wired in? + +## PR-by-PR execution log + +### PR 7.6 — already opened (#1257) + +`will/api_7.6` rebased onto `origin/main`, with subprocess-pool robustness +review fixes pushed (boot_ok event, dead-worker detection, parallel shutdown, +reader-exit pending-job cleanup). 17/17 gpu_pool tests + 89/89 streaming +tests green at head. + +### PR 7.7 — already opened (#1258) + +`will/api_7.7` rebased onto the new 7.6 + LLM provider review fixes applied +locally (per-instance `retryable`, 4xx-non-retryable, json-decode wrap, +shared `_openai_compat.complete_openai_compatible`, `dataclasses.replace` +for the fallback marker). 29/29 prompt tests + 120/120 streaming tests green. +**Pending push** — the user opted to push this branch themselves. + +### PR 7.8 — rebased onto new 7.7 + +`will/api_7.8` two commits replayed cleanly on the new 7.7. Adds +`fastvideo/entrypoints/streaming/{prompt/safety,prompt/rewrite,session_logger, +mock_server}.py` plus `test_auxiliaries.py`. 141/141 streaming tests green. + +Notable gap vs internal version: the public `PromptSafetyFilter` ships one +classifier slot (`unsafe` label, single threshold) whereas the internal +version chained an NSFW filter and a hate-speech filter with marker-based +label matching. Multi-classifier composition is left to Dreamverse — +operators chain two filters explicitly. See **D-7** below. + +### PR 7.9 — rebased onto new 7.8 + +`will/api_7.9` three commits replayed cleanly. Adds streaming router +(`router/{config,registry,main}.py`), `fastvideo router-serve` CLI +subcommand, and `test_router.py`. 151/151 streaming tests green. + +Caveat: router/main.py uses the deprecated FastAPI `app.on_event("shutdown")` +hook — emits a DeprecationWarning. Migration to lifespan handlers is a +pre-merge cleanup item but not a blocker. + +### PR 7.10 — rebased onto new 7.9 + +`will/api_7.10` three commits replayed with two trivial conflicts (line +wrap in `server.py`, redundant test in `test_cli_translation.py`). Adds +`VideoEvent` hierarchy, `VideoGenerator.generate_async`, +`default_health_check_request`, plus `test_generate_async.py` (273-line +contract test). 184/184 streaming + contract tests green. + +### PR 8 — rebased onto new 7.10 + +`will/api_8` four commits → three (the 4th was a duplicate +`streaming.md` doc that 7.5 already shipped, dropped during rebase). +Adds `docs/design/server_contracts/{dynamo,index,openai}.md`, +`mkdocs.yml` entries, and `fastvideo/tests/contract/test_{dreamverse, +dynamo}_shape.py`. 206/206 streaming + contract tests green. + +### Dreamverse `will/integrate-public-fastvideo` + +Branch created from Dreamverse `master`. Single change: `pyproject.toml` +swaps `fastvideo = { path = "../FastVideo-internal", editable = true }` +to point at `../FastVideo`. Comment added linking back to this review +doc. + +**Verified:** every TRACKED `from fastvideo.*` import in Dreamverse +(`server/video_generation.py` only) resolves against the public +package — except `fastvideo.layers.quantization.fp4_config.FP4Config` +(see **D-7** / Q-6 below). + +**Untracked WIP** in `Dreamverse/server/{config,prompting,runtime,session}/` +imports `fastvideo.entrypoints.realtime.local_runtime` (D-6); this +branch does not migrate that WIP. The user's existing untracked work +stays untouched and will need a separate follow-up to consume +`streaming.gpu_pool.SubprocessGpuPool`. + +## Test ladder (built-up to e2e per user request) + +Each rung verifies the integration switch at one layer. Run from the +narrowest to the broadest before running the full e2e against real +GPU + model weights. + +| # | Layer | Command | Status against the switched stack | +|---|---|---|---| +| 1 | Public FastVideo unit + contract tests | `pytest fastvideo/tests/api/ fastvideo/tests/entrypoints/streaming/ fastvideo/tests/contract/` | 358/358 passing on `will/api_8` | +| 2 | Public FastVideo FP4 lazy-import | `pytest fastvideo/tests/ops/quantization/test_fp4_config.py` | 3/3 passing | +| 3 | Dreamverse Python tests | `cd Dreamverse && uv run pytest server/tests/ -k "not stress and not benchmark and not health_endpoint"` | 73/73 passing against public FastVideo | +| 4 | Dreamverse FE unit/integration (vitest) | `cd Dreamverse/apps/web && npm test` | 54/86 passing — 32 failures are pre-existing copy-mismatches in `reducer.test.ts` etc., not caused by the switch | +| 5 | Backend HTTP smoke (Playwright) | `cd Dreamverse/apps/web && PLAYWRIGHT_SKIP_WEBSERVER=1 PLAYWRIGHT_BASE_URL=http://127.0.0.1:8009 npx playwright test e2e/backend-health.spec.ts` | 4/4 passing (5th correctly skipped because devtools-only route is off) | +| 6 | Frontend shell smoke (Playwright) | `npx playwright test e2e/frontend-shell.spec.ts` | Pending — requires Next.js dev server to be reachable; was stuck during this run, needs a clean restart | +| 7 | Full e2e preset generation | `npx playwright test e2e/preset-prompt-generation.spec.ts` | **8/8 passing** end-to-end after restart with `CUDA_VISIBLE_DEVICES=4 ENABLE_TORCH_COMPILE=0 FASTVIDEO_GPU_COUNT=1 FASTVIDEO_ENABLE_DEVTOOLS=1`. BE warmup + GPU 4 idle slot let `/readyz` flip green; the spec verifies preset → WS → backend handshake → "Generating video…" state. | + +### How to reproduce e2e tier 7 from cold + +``` +# 1. BE — picks an idle GPU and skips torch.compile (avoids the +# aarch64 cross-compiler bug in the conda env's triton stack). +cd ~/Dreamverse +set -a; source ~/.env; set +a +CUDA_VISIBLE_DEVICES=4 ENABLE_TORCH_COMPILE=0 \ + FASTVIDEO_ENABLE_DEVTOOLS=1 FASTVIDEO_GPU_COUNT=1 \ + uv run dreamverse-server & + +# 2. Wait for /readyz (~2 min for warmup x2 segments) +until curl -fsS http://127.0.0.1:8009/readyz >/dev/null; do sleep 5; done + +# 3. FE +cd ~/Dreamverse/apps/web +BACKEND_URL=http://127.0.0.1:8009 NEXT_PUBLIC_INCLUDE_DEVTOOLS=1 \ + npm run dev:devtools & + +# 4. Playwright +cd ~/Dreamverse/apps/web +PLAYWRIGHT_SKIP_WEBSERVER=1 \ + PLAYWRIGHT_BASE_URL=http://127.0.0.1:5274 \ + BACKEND_URL=http://127.0.0.1:8009 \ + npx playwright test --project=chromium --reporter=list +``` + +### Surfaced during the e2e debug pass (logged here for follow-up) + +* **`SamplingParam has no field ltx2_image_crf`** — Dreamverse's + `server/video_generation.py:406` passes `ltx2_image_crf=0.0` to a + `SamplingParam(...)` constructor. The internal SamplingParam (in + `fastvideo/configs/sample/base.py`) declared this field; the public + `fastvideo.api.sampling_param.SamplingParam` does not. Currently + the BE logs an `ERROR` and silently drops the kwarg; warmup still + succeeds because the field is non-load-bearing for FP4-disabled + inference. Either re-add the field to the public schema or update + Dreamverse to stop passing it. **D-8.** + +* **`aarch64-conda-linux-gnu-cc` triton compile failure** — the conda + env we boot from injects an ARM cross-compiler ahead of `gcc` on + `$PATH`, so `torch._inductor`'s triton launcher fails compilation. + Setting `ENABLE_TORCH_COMPILE=0` bypasses it. Long-term fix: clean + the conda env's compiler shadowing or add a `CC=gcc` override in + Dreamverse's worker bootstrap. **D-9.** + +* **GPU pool starts but warmup OOMs on a shared GPU** — when + `CUDA_VISIBLE_DEVICES` lands on a GPU another tenant is using + (107 GiB-pegged training run on GPU 0 in this case), LTX-2 warmup + fails with OOM. Picking an idle GPU (4-7 here) is a manual step. + A pre-warm probe that checks free memory before booting the pool + would prevent this. **D-10.** + +* **ffmpeg fragment write `Broken pipe`** — when the WS client closes + before the backend finishes streaming the first segment, ffmpeg + hits `[Errno 32] Broken pipe`. Currently Dreamverse's + `gpu_pool.handle_command` re-raises this as a session error, + which then propagates to "User step failed". Cosmetic for now — + swallowing pipe-broken on intentional disconnect would clean up + the logs. **D-11.** + +## Additional integration gaps surfaced during the switch + +### D-7: `FP4Config` is private-only + +**Context.** `Dreamverse/server/video_generation.py:271` imports +`fastvideo.layers.quantization.fp4_config.FP4Config` and assigns it to +`pipeline_config.dit_config.quant_config`. The 411-line module lives only +in `FastVideo-internal/fastvideo/layers/quantization/fp4_config.py` and +hard-imports `flashinfer` at module top — it never made the public +upstream pass. Public has `base_config.py` and `absmax_fp8.py` only. + +**Decision (provisional).** Don't upstream `fp4_config.py` in this +session. Reasons: +1. It introduces a new external dependency (`flashinfer`) the public + package has avoided so far. +2. The class hard-codes LTX-2 layer paths + (`ltx2.blocks.{i}.attn1.to_q` etc.) — this is "LTX-2-specific FP4", + not generic FP4. Belongs colocated with `pipelines/basic/ltx2/` if + it goes anywhere. +3. The FP4 pre-quantize/forward op surface is the kind of thing where + a careful review pass matters more than a bulk copy. + +**What this means for the integration branch.** Dreamverse will boot +fine; only the FP4-quantized path inside `video_generation.py:283` +will fail (lazy import). For workflows that don't enable FP4 +quantization, the integration is complete. + +### Q-6 (review): how to land FP4Config publicly? + +Two reasonable next steps: +1. **Colocate.** Move FP4 code to `fastvideo/pipelines/basic/ltx2/quantization.py` + with `flashinfer` as an optional extra: `pip install fastvideo[fp4]`. + Refactor `FP4QuantizeMethod` to take its layer-prefix list from a + pipeline-config field instead of hardcoding ltx2 paths so the + approach generalizes. +2. **Keep private.** Treat FP4 as a Dreamverse-side concern — Dreamverse + imports `fp4_config` from the internal repo via a thin shim. Public + FastVideo stays focused on generic surfaces. This means the + "FastVideo-internal removable" goal is partially undone. + +Recommendation: option 1 once the API refactor settles — wait until +the LTX-2 colocation step (PR 9 / 10 territory) and land FP4 there. + diff --git a/.agents/memory/dreamverse-integration/source-archive/handoff-nvfp4-launch-demo.md b/.agents/memory/dreamverse-integration/source-archive/handoff-nvfp4-launch-demo.md new file mode 100644 index 0000000000..c928bef1a2 --- /dev/null +++ b/.agents/memory/dreamverse-integration/source-archive/handoff-nvfp4-launch-demo.md @@ -0,0 +1,518 @@ +# Handoff: LTX-2 NVFP4 wire-up + Dreamverse launch-demo skill + +This document hands off in-flight work to the next coding agent. It covers +two related streams that landed across two repos: + +1. **FastVideo** (`will/ltx2_sr_port`): wire NVFP4 (NVIDIA's block-scaled + FP4) inference + per-component torch.compile + supporting parity fixes + so the public package matches `FastVideo-internal` for the LTX-2 + distilled streaming path used by Dreamverse. +2. **Dreamverse** (`will/integrate-public-fastvideo`): switch the GPU + worker to the typed `GeneratorConfig` API, rename `FP4Config` → + `NVFP4Config`, add a `launch-demo` skill + canonical + `serve_configs/streaming_demo.yaml` for `fastvideo serve --config`. + +Stack remains green: 222/222 FastVideo unit/contract/api tests pass; 8/8 +Playwright e2e tests pass against the live `dreamverse-server` + Next.js +stack. + +--- + +## Repo + branch state + +| Repo | Path | Branch | Tip | +| --- | --- | --- | --- | +| FastVideo | `/home/william5lin/FastVideo` | `will/ltx2_sr_port` | `c6c14c55` | +| Dreamverse | `/home/william5lin/Dreamverse` | `will/integrate-public-fastvideo` | `3d7fd89` | +| Reference (read-only) | `/home/william5lin/FastVideo-internal` | (their) `main` | source of truth for parity | + +> **Working branch on FastVideo is `will/ltx2_sr_port`, not the default checkout.** +> The shell may report `will/uv-pip-install-everywhere` because that was +> the earlier checkout. Run `git checkout will/ltx2_sr_port` before +> picking up FastVideo work. + +### Live processes (do not duplicate) + +``` +:8009 dreamverse-server pid 2453227 (warmed, /readyz returns 200) +:5274 next-server (dev) pid 2399103 (devtools build) +``` + +### Stashes + +* FastVideo: `stash@{0}: WIP on main: …HunyuanVideo plugin…` — pre-existing, + unrelated to this work, do not pop. +* Dreamverse: `stash@{0}: wip: server modular refactor (split + config/prompting/runtime/session)` — 3867 lines of orphan modular split + off this branch. Do not pop on this branch; recover on a separate + feature branch if anyone wants to resurrect it. + +--- + +## What landed (FastVideo: `cfccd292..c6c14c55`) + +Six commits on top of the i2v / continuation latent port: + +``` +c6c14c55 test(nvfp4): lock LTX-2 wiring + typed transformer_quant flow +94c983a2 refactor(quant): rename FP4 → NVFP4 to disambiguate from other FP4 variants +42b30bf9 feat(ltx2): wire FP4 inference through fastvideo.layers.quantization +6da342ba feat(compile): per-component compile + transformer_refine + prepare hook +221cb20a feat(api): typed per-component CompileConfig + FastVideoArgs carriers +a4760bae fix(api): propagate generic refine_* args + match internal randn +``` + +Each commit message has the rationale. Highlights below. + +### `a4760bae` — three small parity fixes + +* `FastVideoArgs.__post_init__` now calls `_resolve_refine_args()` which + copies the public-facing generic `refine_*` knobs onto their + `ltx2_refine_*` runtime carriers. Was missing → callers that set + `refine_lora_path=...` saw "applied to 0 layers" warnings as the value + was silently dropped. +* `_randn_ltx2_video_latents` patch path reverted from `randn_tensor` → + `torch.randn` to bit-match internal under single-generator inference. + Identical for a single `torch.Generator` but diverges for + `list[Generator]` (per-sample seeds). +* Classified 19 `refine_*` / `ltx2_refine_*` / i2v / `ltx2_audio_*` / + `ltx2_conditioning_latent_*` / `ltx2_video_conditions` fields in the + schema-parity inventory yaml. + +### `221cb20a` — typed CompileConfig + FastVideoArgs carriers + +`CompileConfig` (in `fastvideo/api/schema.py`) gained per-component knobs: + +```python +@dataclass +class CompileConfig: + enabled: bool = False # master DiT switch + backend / fullgraph / mode / dynamic / extras # master kwargs + + # Per-component overlays, None = inherit master `enabled` + text_encoder_enabled: bool | None = None + vae_enabled: bool | None = None + audio_vae_enabled: bool | None = None + + # Per-component kwargs override master when non-empty + dit_kwargs: dict = ... + text_encoder_kwargs: dict = ... + vae_kwargs: dict = ... + audio_vae_kwargs: dict = ... +``` + +Matching carrier fields on `FastVideoArgs`: +`enable_torch_compile_text_encoder/vae/audio_vae` and +`torch_compile_kwargs_dit/text_encoder/vae/audio_vae`. Compat layer +round-trips them through `legacy_from_pretrained_to_config` and +`generator_config_to_fastvideo_args`. **No behavior change yet** — these +are surface ports only; consumed in the next commit. + +### `6da342ba` — refine + per-component compile + prepare_for_compile + +`composed_pipeline_base.post_init` now: + +* compiles `transformer_refine` alongside `transformer` and + `transformer_2` whenever the DiT compile flag is on (closes the LTX-2 + stage-2 silent-eager bug); +* dispatches per-component compile loops (text encoder, VAE, audio VAE) + with per-component kwargs falling back to master when empty; +* calls `module.prepare_for_compile()` on each compiled submodule + before invoking `torch.compile` (hook protocol — model-specific). + Implemented on `Gemma3` to materialize HF weights outside Dynamo's + tracer. + +### `42b30bf9` — NVFP4 LTX-2 inference wire-up *(largest)* + +End-to-end: + +1. `models/dits/ltx2.py` — swap `nn.Linear` → `ReplicatedLinear` for the + FP4-eligible subset (`LTXSelfAttention`, `LTXDistributedSelfAttention`, + `FeedForward`/`GELUApprox`); plumb `quant_config` and `prefix=` from + `BasicAVTransformerBlock` → `_init_transformer_blocks` → `LTXModel` + → `LTX2Transformer3DModel`. Other linears + (`TimestepEmbedding`, `PixArtAlphaTextProjection`, `patchify_proj`, + `proj_out`, `AdaLayerNormSingle.linear`) stay `nn.Linear` — + matches internal exactly. +2. Port `_supports_prequantized_input` and + `_linear_project_with_optional_prequant` helpers. Attention forward + pre-quantizes input once (`quantize_input`), reuses the + `(x_fp4, x_scale, x_global_sf)` tuple for k/v projections when + `context is x` — bit-matches internal's fused path. +3. `models/loader/fsdp_load.py` — new `_maybe_convert_model_to_nvfp4` + helper detects via `isinstance(quant_method, NVFP4QuantizeMethod)` + (no flag); calls `convert_model_to_nvfp4` to materialize + `_nvfp4_weight*` / `_nvfp4_alpha` / `_weight_global_sf` buffers. + `flashinfer` import is lazy (inside the helper), so the loader is a + no-op on hosts without flashinfer. +4. `layers/quantization/__init__.py` — registered `"NVFP4"` in + `QuantizationMethods` literal + `get_quantization_config`. +5. `api/compat.py` + `fastvideo_args.py` — typed + `engine.quantization.transformer_quant: "NVFP4"` resolves to a + concrete `NVFP4Config()` instance, carried on `FastVideoArgs.transformer_quant`, + pinned onto `pipeline_config.dit_config.quant_config` in + `__post_init__._apply_transformer_quant`. **The explicit setter + (legacy mutation pattern) wins** if `dit_config.quant_config` is + already non-None. +6. `layers/linear.py` — `LinearBase.__init__` now falls back to + `UnquantizedLinearMethod` when `quant_config.get_quant_method` returns + `None`. `NVFP4Config` only tags a curated subset of LTX-2 layers, and + the previous `assert quant_method is not None` would crash any + non-tagged layer that received a quant_config. + +### `94c983a2` — FP4 → NVFP4 rename + +NVIDIA's specific block-scaled fp4 format (e2m1 mantissa, fp32 alpha, +`layout_128x4` scale layout, group size 16) — distinct from MX-FP4 / +OCP-FP4 / generic e3m0. Mechanical rename, no behavior change: + +* `fp4_config.py` → `nvfp4_config.py` +* `FP4Config` → `NVFP4Config`; `get_name()` returns `"nvfp4"` +* `FP4QuantizeMethod` → `NVFP4QuantizeMethod` +* `convert_model_to_fp4` → `convert_model_to_nvfp4` +* `QuantizationMethods` literal: `"FP4"` → `"NVFP4"` +* registered buffer names: `_fp4_weight`/`_fp4_alpha` → + `_nvfp4_weight`/`_nvfp4_alpha` +* loader helper renamed +* test file rename + symbol updates + +Internal-scope torch op namespace `fastvideo_fp4::*` and +`_get_ltx2_fp4_stage_profile` deliberately left as-is — purely +internal naming that mirrors FastVideo-internal. + +### `c6c14c55` — contract + numerical lock-in tests + +* `fastvideo/tests/ops/quantization/test_nvfp4_ltx2_wiring.py` (6 tests): + asserts that `LTXSelfAttention.to_q/to_k/to_v/to_out` are + `ReplicatedLinear`; `NVFP4Config()` attaches `NVFP4QuantizeMethod` + on the quantized subset with the correct `layer_prefix`; non-tagged + projections (cross-attn K/V, audio attn, audio FFN) fall back to + `UnquantizedLinearMethod`; `BasicAVTransformerBlock` propagates + `quant_config` and `prefix` correctly to all 4 attention modules + + FFN at once. +* `fastvideo/tests/api/test_typed_quant_flow.py` (4 tests): asserts + typed `engine.quantization.transformer_quant: "NVFP4"` → + `NVFP4Config()` instance flow; default leaves `transformer_quant` + None; explicit `dit_config.quant_config = …` wins over typed carrier. + +--- + +## What landed (Dreamverse: `248060b..3d7fd89`) + +Three commits on top of the e2e tier: + +``` +3d7fd89 feat(skill): launch-demo orchestrator + fastvideo serve YAML +d80c2a8 refactor(server): drive FP4 + per-component compile via typed GeneratorConfig +4cc6b30 chore: gitignore Playwright + Next.js build artifacts under apps/web +``` + +### `d80c2a8` — server/video_generation.py refactor + +Three coordinated changes in the GPU worker: + +* Replace legacy `load_kwargs` dict + `VideoGenerator.from_pretrained(model_root, **kwargs)` + call with the typed `GeneratorConfig` (`EngineConfig` / + `OffloadConfig` / `CompileConfig` / `PipelineSelection` / + `ComponentConfig`). Refine knobs move from `ltx2_refine_*` flat + kwargs into `preset_overrides["refine"]`. **The in-memory + `pipeline_config` pin** (`dit_config.quant_config = NVFP4Config()`) + keeps using the legacy `experimental["pipeline_config"]` carrier + because typed `transformer_quant: "NVFP4"` doesn't yet support + setting `layer_profile`. +* Rename FP4 → NVFP4. +* Re-enable `"mode": "max-autotune-no-cudagraphs"` (was commented out). + Closes the last known divergence vs FastVideo-internal in the + worker-level path trace. + +### `4cc6b30` — gitignore Playwright/Next.js artifacts + +Added `apps/web/{node_modules,.next,test-results,playwright-report}` to +`.gitignore`. Mirror of the existing `prod-ui/` ignore set. + +### `3d7fd89` — launch-demo skill + +``` +.agents/skills/launch-demo/ +├── SKILL.md +└── scripts/ + ├── launch_demo.sh # orchestrator: BE + FE + health probes + Ctrl-C trap + ├── launch_backend_dreamverse.sh # uv run dreamverse-server (default) + ├── launch_backend_fastvideo.sh # uv run fastvideo serve --config (typed path) + └── launch_frontend.sh # next dev (devtools/dev/single5s) +serve_configs/ +└── streaming_demo.yaml # canonical ServeConfig matching internal/ui +``` + +YAML has every field annotated with the internal source line it mirrors: +LTX-2 distilled, NVFP4, 121 frames @ 1088×1920 24fps, 5 inference steps, +2-step refine gs=1.0 add_noise=true, max-autotune-no-cudagraphs compile, +121-frame default request, 300s session timeout, 6 segment cap, av_fmp4 +streaming, cinematic-drone warmup prompt, 2400s warmup timeout, 9 +conditioning frames + 0 end-offset, prompt enhancer on with cerebras / +gpt-oss-120b / 20s timeout. + +**Two BE flavors documented in SKILL.md:** + +| `BE_FLAVOR=` | Boots | Routes served | FE compatible | +| --- | --- | --- | --- | +| `dreamverse` (default) | `dreamverse-server` | `/healthz`, `/readyz`, `/curated-presets`, `/v1/stream`, devtools, session monitor | ✓ full | +| `fastvideo` | `fastvideo serve --config ` | `/health`, `/v1/stream` | ⚠ FE will surface fetch errors for `/curated-presets`, `/readyz` until those routes migrate into FastVideo's `build_app` | + +The fastvideo flavor exists today as the verifiable typed-config path +(YAML parses, streaming worker boots, dotted overrides work). It is not +yet a drop-in for the FE — see "Open follow-ups" below. + +--- + +## Verified + +* `222 passed, 1 skipped` across `fastvideo/tests/api/`, + `fastvideo/tests/contract/`, + `fastvideo/tests/ops/quantization/test_nvfp4_*`, + `tests/local_tests/pipelines/test_ltx2_pipeline_smoke.py`. +* `8 passed` Playwright e2e (backend-health 5, frontend-shell 2, + preset-prompt-generation 1) against the live `dreamverse-server` + + Next.js stack. +* `streaming_demo.yaml` parses cleanly against `ServeConfig`; the + validation path of `fastvideo serve --config ` runs without + error and accepts dotted overrides like `--server.port 8010`. +* FastVideo `bash -n` clean across all four launch scripts. + +--- + +## Critical context (gotchas a successor should know) + +### NVFP4 layer set is asymmetric — by design + +`NVFP4Config.fp4_layers` covers: + +* `attn1.{to_q,to_k,to_v,to_out}` — full self-attention +* `attn2.{to_q,to_out}` — cross-attn Q + out only (text context not quantized) +* `audio_to_video_attn.{to_q,to_out}` — AV cross Q + out +* `video_to_audio_attn.{to_k,to_v}` — VA cross K + V +* `ffn.{fc_in,fc_out}` — video FFN +* `adaln_single.linear` — but this is `nn.Linear` (not `LinearBase`), + so it never actually gets FP4'd. List entry has no effect; matches + internal. + +**NOT in the set:** audio self-attention (`audio_attn1.*`), audio +cross-attention (`audio_attn2.*`), audio FFN (`audio.ffn.*`). Audio +path is cheap enough that quant overhead isn't worth it. Test +`test_basic_av_block_propagates_quant_config_to_all_children` locks +this in — if you add audio quantization later, update the test. + +### `LinearBase` fallback is load-bearing + +`fastvideo/layers/linear.py:191-202`: when `quant_config.get_quant_method` +returns `None` (layer not in the quant config's set), we fall back to +`UnquantizedLinearMethod`. **Do not remove this fallback** — it would +break every non-tagged `ReplicatedLinear` constructed with a +`NVFP4Config`, and `assert quant_method is not None` in +`ReplicatedLinear.__init__` would fire on unmatched layers. + +### Typed `transformer_quant` precedence + +`FastVideoArgs._apply_transformer_quant` only writes +`dit_config.quant_config` when it's currently `None`. If a caller has +explicitly set `pipeline_config.dit_config.quant_config = NVFP4Config(...)`, +the explicit setter wins. Dreamverse's `video_generation.py` relies on +this — it sets `NVFP4Config()` directly because the typed +`transformer_quant: "NVFP4"` doesn't expose `layer_profile`. + +### Pre-existing AbsMaxFP8 test failure is NOT mine + +`fastvideo/tests/ops/quantization/test_absmax_fp8.py::test_create_weights_rejects_invalid_dtype` +fails on `main` and on this branch with the same error +("AssertionError not raised"). I confirmed via `git stash` that the +failure pre-dates my changes. Not blocking; tracked as separate tech +debt. + +### `transformer_refine` is auto-compiled with the master DiT flag + +Set `enable_torch_compile=True` and `transformer_refine` compiles +along with `transformer` and `transformer_2`. There is **no separate +`enable_torch_compile_refine` flag** — by design, refine inherits the +DiT compile state to keep the typed surface small. If you need them +decoupled, add a new field; don't repurpose existing ones. + +### `prepare_for_compile` is a duck-type protocol, not a base class method + +Defined nowhere; called via `getattr(module, "prepare_for_compile", None)` +in `composed_pipeline_base._maybe_compile_pipeline_module`. Currently +only Gemma implements it (to materialize HF weights outside Dynamo). +Add to other models that have lazy external state if you observe +compile-time graph breaks. + +### Public typed `PromptEnhancerConfig.provider` is `Literal["cerebras", "groq"]` + +Internal supports `"cerebras_ifm"` (config.py:143). The public typed +schema does not. The `streaming_demo.yaml` defaults to `"cerebras"`. +For agents that need `cerebras_ifm`, the `dreamverse-server` flavor +respects the `FASTVIDEO_PROMPT_PROVIDER` env var (legacy path); +`fastvideo serve --config` does not currently expose it. + +### Dreamverse `pipeline_config` is still a Python object passed via `experimental` + +The typed `GeneratorConfig` doesn't have a clean home for an +in-memory `PipelineConfig` instance with mutated `dit_config`. We +pass it via `pipeline.experimental["pipeline_config"]` — the +`compat.py` legacy adapter recognizes that key and threads it through +to `FastVideoArgs.from_kwargs`. This is fine but not pretty; if +someone designs a typed `dit_config` carrier later, this becomes +obsolete. + +### `fastvideo serve --config` is not yet a drop-in for the FE + +`fastvideo.entrypoints.streaming.server.build_app` exposes only +`/health` and `/v1/stream`. The Dreamverse Next.js shell expects +`/healthz`, `/readyz`, `/status`, `/curated-presets`, +`/curated-presets/append`, `/prompt-system-config`, and the devtools +routes. These all live in `Dreamverse/server/main.py` + +`Dreamverse/server/routes/`. Until they migrate into FastVideo's +`build_app` (or are exposed via a Dreamverse-side proxy), the +`BE_FLAVOR=fastvideo` flavor is for verifying the typed serve config +path only — not for full FE compatibility. + +--- + +## Open follow-ups (prioritized) + +### High + +1. **Migrate FE-required routes into FastVideo's `build_app`.** + `/healthz`, `/readyz`, `/status` look obviously fastvideo-side + (they're streaming-server health). `/curated-presets` and + `/prompt-system-config` are operator-side surfaces and should + probably stay in Dreamverse (or migrate as opt-in routes that the + FE feature-detects). Without this, `BE_FLAVOR=fastvideo` is + permanently a "diagnostic" flavor. Closes the + `launch-demo` skill TODO. + +2. **AbsMaxFP8 test failure cleanup.** Pre-existing. Either fix the + test (`AbsMaxFP8LinearMethod.create_weights` no longer asserts on + invalid dtype — restore the assert if intentional, otherwise drop + the test). + +### Medium + +3. **Add `cerebras_ifm` to public `PromptEnhancerConfig.provider` + Literal.** Trivial schema change; needs paired enhancer-side + provider implementation in + `fastvideo/entrypoints/streaming/prompt/providers/`. + +4. **Expose `layer_profile` on typed `engine.quantization`.** Today + `transformer_quant: "NVFP4"` always constructs `NVFP4Config()` + with the default `layer_profile="refine"`. To support stage-1 + profiles (no `attn2.to_out`, no cross-modal AV) via typed config, + add `transformer_quant_layer_profile: str | None = None` and + thread it through `compat.py`. Dreamverse currently dodges this + by setting `NVFP4Config()` directly via `experimental`. + +5. **Typed `dit_config.quant_config` carrier.** The + `experimental["pipeline_config"]` escape hatch in Dreamverse + should eventually become a typed field. Design TBD. + +### Low + +6. **Audio attention quantization profile.** If an audio-quant + profile is added to `NVFP4Config.fp4_layers` (currently audio attn + and FFN are bf16), update + `test_basic_av_block_propagates_quant_config_to_all_children`. + +7. **Schema parity inventory.** A few internal-only fields are not + exposed publicly (`PROMPT_HTTP_TIMEOUT_MS`, + `PROMPT_INITIAL_STAGE_TIMEOUT_MS`, `PROMPT_TEMPERATURE`, + `PROMPT_MAX_COMPLETION_TOKENS`, `PROMPT_AUTO_SLEEP_MS`, + `PROMPT_AUTO_TIMEOUT_MS`, the curated-presets file paths). + These all flow via env vars on `dreamverse-server` today; if + `fastvideo serve --config` becomes the canonical entrypoint, + they'll need typed homes. + +8. **Empty `apps/web/test-results/` directory locally.** The + `.gitignore` entry I added makes it invisible to `git status`, + but the dir itself still has a stale `.last-run.json` (45 bytes) + from a prior Playwright run. Harness blocked auto-cleanup + ("pre-existing files"); the user can `rm -rf + apps/web/test-results` whenever convenient. + +--- + +## How to pick up work + +### Quick orientation (run these first) + +```bash +# FastVideo state +cd /home/william5lin/FastVideo +git checkout will/ltx2_sr_port +git log --oneline cfccd292..HEAD # six commits added this round +.venv/bin/python -m pytest fastvideo/tests/api/ \ + fastvideo/tests/contract/ \ + fastvideo/tests/ops/quantization/test_nvfp4_*.py \ + tests/local_tests/pipelines/test_ltx2_pipeline_smoke.py \ + -q --no-header # expect 222 passed, 1 skipped + +# Dreamverse state +cd /home/william5lin/Dreamverse +git log --oneline 248060b..HEAD # three commits added this round +cat serve_configs/streaming_demo.yaml | head -40 +ls .agents/skills/launch-demo/ + +# Live stack health (already running on this host) +curl -s http://localhost:8009/readyz | head -c 200 +curl -s http://localhost:5274/ | head -c 100 +( cd apps/web && npx playwright test --reporter=line ) # expect 8 passed +``` + +### Reference docs + +* **FastVideo internal/ui parity source:** `../FastVideo-internal/ui/ltx2-streaming/server/config.py` +* **NVFP4 source on internal:** `../FastVideo-internal/fastvideo/layers/quantization/fp4_config.py` +* **Worker-trace audit:** `../FastVideo/dreamverse_review.md` (D-1 + multi-model, D-5 audio re-encode, prior gap inventory) +* **Schema parity inventory:** `docs/design/inference_schema_parity_inventory.yaml` +* **PR-plan for the broader migration:** `../FastVideo/PR plan.md` + +### Files most likely to need touches in follow-ups + +* `fastvideo/api/schema.py` — `CompileConfig`, `QuantizationConfig`, + `PromptEnhancerConfig` Literal extension. +* `fastvideo/api/compat.py` — typed → flat translation. +* `fastvideo/fastvideo_args.py` — carrier fields and + `_apply_transformer_quant`. +* `fastvideo/entrypoints/streaming/server.py::build_app` — add + `/healthz`, `/readyz`, `/status` routes for FE compatibility (high + priority follow-up #1). +* `Dreamverse/server/video_generation.py` — typed `GeneratorConfig` + builder (current). +* `Dreamverse/serve_configs/streaming_demo.yaml` — every parity + knob; edit here, not in shell scripts. + +--- + +## Don't / Cautions + +* **Don't pop the Dreamverse stash on this branch.** It's 3867 lines + of orphan modular refactor (server/{config,prompting,runtime,session}/) + with broken absolute imports. If anyone wants to resurrect it, do so + on a separate feature branch. +* **Don't remove the `LinearBase` `UnquantizedLinearMethod` fallback.** + See "Critical context" above. +* **Don't repurpose `enable_torch_compile` to mean DiT-only.** It also + drives `transformer_refine` and `transformer_2` compile. Add a new + flag if decoupling is needed. +* **Don't change `NVFP4Config` buffer names back to `_fp4_*`.** The + rename is intentional to disambiguate from MX-FP4 / OCP-FP4. +* **Don't bypass the typed surface for new options.** New compile / + quant / refine knobs should land on the dataclass + compat.py + + parity inventory together. The existing test suite locks this in. +* **Don't merge to main without a CI run that covers FP4.** Current + CI doesn't run flashinfer-dependent paths; the wiring tests in + `test_nvfp4_ltx2_wiring.py` are CPU-only by design and don't + exercise the actual FP4 kernels. + +--- + +*Last updated: end of session that landed `c6c14c55` on FastVideo and +`3d7fd89` on Dreamverse. Stack remains green; no dirty state.* diff --git a/.agents/memory/dreamverse-integration/source-archive/streaming-server-upstream-plan.md b/.agents/memory/dreamverse-integration/source-archive/streaming-server-upstream-plan.md new file mode 100644 index 0000000000..9cf100f925 --- /dev/null +++ b/.agents/memory/dreamverse-integration/source-archive/streaming-server-upstream-plan.md @@ -0,0 +1,539 @@ +# FastVideo Streaming Server Upstream — Design & Plan + +## Status +Exploration / design draft. Captures the re-evaluation triggered by the +decision to upstream `FastVideo-internal/ui/ltx2-streaming/server/` into +the public repo. Not yet approved for execution. + +## Related Documents +- [PR plan.md](../../PR%20plan.md) — PR-by-PR implementation plan for the API refactor +- [apirefactor.md](../../apirefactor.md) — design spec this plan implements +- `../../../FastVideo-internal/ui/ltx2-streaming/` — upstream source (server side) +- `../../../dynamo/` — local clone of ai-dynamo/dynamo; backend patterns at + `components/src/dynamo/{vllm,sglang,trtllm}/` and `CLAUDE.md` files +- https://github.com/ai-dynamo/dynamo/pull/7544 — draft PR that promotes + FastVideo to a native Dynamo backend (CLOSED, superseded — but establishes + the integration shape) + +## Context + +The internal `FastVideo-internal/ui/ltx2-streaming/` directory contains a +complete LTX2 streaming service. The user has decided: + +- **Frontend clients** (`client/`, `prod-ui/`) stay in the internal repo +- **Everything server-side** — FastAPI/WebSocket server, GPU pool, prompt + enhancer, router, auxiliaries — will be upstreamed to FastVideo + +In parallel, FastVideo is becoming a **first-class Dynamo backend** (same +tier as vllm, sglang, trtllm). The refactor must produce an API that +Dynamo's `components/src/dynamo/fastvideo/` package can consume as a +pure Python import, without re-introducing the legacy flat-kwarg +surface. Draft PR ai-dynamo/dynamo#7544 defines the concrete integration +shape we need to support. + +This materially changes the tail of the API refactor plan. The current +PR 5 ("wire `ServeConfig.default_request` into the OpenAI-compatible +HTTP server") addresses only the stateless endpoint; the real upstream +target is a much larger, session-based stack **plus** a clean Dynamo +backend contract. + +This document captures: +- what's being upstreamed and where it lands +- four design decisions that shape the upstream (continuation model, + streaming server layout, LLM provider abstraction, Dynamo backend + integration) +- a revised PR sequence for the tail of the refactor + +## What's being upstreamed + +| Internal path | Size | Role | Upstream target | +|---|---|---|---| +| `server/main.py` | 94KB | FastAPI + WebSocket, session lifecycle, segment orchestration | `fastvideo/entrypoints/streaming/server.py` + handlers | +| `server/gpu_pool.py` | 66KB | GPU orchestration, subprocess workers | `fastvideo/entrypoints/streaming/gpu_pool.py` | +| `server/prompt_enhancer.py` | 69KB | LLM orchestration (cerebras_ifm, cerebras, groq) | `fastvideo/entrypoints/streaming/prompt/` package | +| `server/mock_server.py` | 45KB | Mock backend for dev/tests | `fastvideo/entrypoints/streaming/mock_server.py` | +| `server/prompt_safety.py` | 7KB | Optional fasttext-gated prompt safety | `fastvideo/entrypoints/streaming/prompt/safety.py` | +| `server/session_init_image.py` | 3KB | i2v init image handling | `fastvideo/entrypoints/streaming/session_init_image.py` | +| `server/rewrite_prompt_payload.py` | 3KB | Rewrite flow payload builder | `fastvideo/entrypoints/streaming/prompt/rewrite.py` | +| `server/session_logger.py` | 1KB | Session JSONL logs | `fastvideo/entrypoints/streaming/session_logger.py` | +| `server/config.py` | 9KB | Env-driven server config | Typed `ServeConfig` extensions | +| `router/main.py` | 27KB | Multi-replica load balancer + WS proxy | `fastvideo/entrypoints/streaming/router/` (or separate package) | +| `slurm/` | — | Deployment scripts | Likely stays internal | + +## FastVideo contact surface today + +Direct calls from the internal stack into FastVideo, all in `gpu_pool.py`: + +| Location | Call | Notes | +|---|---|---| +| `gpu_pool.py:164` | `from fastvideo.entrypoints.video_generator import VideoGenerator` | Subprocess-level import, post-`CUDA_VISIBLE_DEVICES` setup | +| `gpu_pool.py:230` | `PipelineConfig.from_pretrained(config_model_path)` | Direct access to legacy `PipelineConfig` | +| `gpu_pool.py:231` | `pipeline_config.dit_config.quant_config = FP4Config()` | Direct internals mutation | +| `gpu_pool.py:264-267` | `VideoGenerator.from_pretrained(model_root, **load_kwargs)` | Flat legacy kwargs | +| `gpu_pool.py:837` | `generator.generate_video(**request_kwargs)` | Per-segment flat kwargs | +| `gpu_pool.py:282-288` | `LTX2AudioEncoder`, `AudioProcessor`, `get_diffusers_config` | Audio re-encode path | + +`load_kwargs` at `gpu_pool.py:233-260` contains: +`ltx2_refine_enabled`, `ltx2_refine_upsampler_path`, `ltx2_refine_lora_path`, +`ltx2_refine_num_inference_steps`, `ltx2_refine_guidance_scale`, +`ltx2_refine_add_noise`, `pipeline_config`, `torch_compile_kwargs`, +`dit_cpu_offload`, `dit_layerwise_offload`, `vae_cpu_offload`, +`text_encoder_cpu_offload`, `pin_cpu_memory`, `ltx2_vae_tiling`, +`use_fsdp_inference`, `enable_torch_compile`. + +`request_kwargs` at `gpu_pool.py:837` includes: +`ltx2_audio_clean_latent`, `ltx2_audio_denoise_mask`, +`ltx2_video_conditions`, `video_position_offset_sec`, standard sampling +fields. + +**Implication**: upstreaming `gpu_pool.py` as-is perpetuates the flat +kwarg surface inside the public server. We need a typed translation +(PR 6 expansion) at the worker boundary before, or as part of, the +gpu_pool upstream. + +## Session / continuation semantics today + +Per-session state (in `server/main.py`): +- `locked_segment_prompts`, `curated_prompts`, `segment_idx`, + `generated_segment_count`, `loop_iteration` + +Per-**GPU** (not per-session) continuation cache (in `gpu_pool.py`): +- `ltx2_continuation_images` — last 9 decoded frames for clip conditioning +- `ltx2_continuation_audio_latents` — denoised audio latents for audio conditioning + +Segment N+1 automatically conditions on segment N's trailing frames and +audio. On session reset or handoff (`USER_JOIN`), the per-GPU cache is +cleared. There is currently **no way for a client to serialize and +resume continuation state elsewhere** — it lives on the GPU only. + +## Design Decision 1: Continuation model + +### Options + +**A. Opaque client-round-trip payload** (current plan PR 7 design) +- Server returns `ContinuationState(kind, payload)`; client sends it back. +- Pro: stateless server, trivially load-balanceable, survives disconnects. +- Con: large payloads (frames + audio latents) over every request hop; + bandwidth heavy on multi-segment WebSocket sessions. + +**B. Server-held session state** (internal reality) +- Continuation lives per-GPU; implicit between adjacent segments. +- Pro: zero client bandwidth; fast; matches today. +- Con: needs GPU affinity, no resume after disconnect, harder to scale horizontally. + +**C. Hybrid** (recommended) +- Server-held is the default for streaming WebSocket sessions. +- Server exposes a `snapshot_state` message that returns the opaque + payload form for migration/retry. +- Stateless HTTP endpoints always use round-trip opaque payloads. +- One serialization format underlies both surfaces. + +### Decision: **C (Hybrid)** + +Rationale: matches both internal streaming use (server-held, fast) and +stateless API use (client-round-trip, resumable). Cost is one serialization +layer that serves both. + +### Implications +- `ContinuationState.kind` identifies the payload schema + (e.g. `"ltx2.v1"`). +- `ContinuationState.payload` must cover: + - trailing conditioning frames (or a tensor reference) + - audio latents (or a tensor reference) + - segment index / rollout position + - any model-specific conditioning metadata (e.g. audio sample rate, + `video_position_offset_sec`) +- For large tensors, payload may reference a server-side blob by ID + rather than inline everything. +- Streaming server has a `SessionStore` keyed by session ID that holds + a typed `LTX2ContinuationState` object. +- `SessionStore.snapshot(session_id) -> ContinuationState` serializes + the current state for export. +- `SessionStore.hydrate(state: ContinuationState) -> session_id` loads + a state into a new session. +- Plan PR 7 expands to cover both surfaces and define the payload schema. + +## Design Decision 2: Streaming server layout + +### Options + +- **A. `fastvideo/entrypoints/streaming/`** — parallel to + `fastvideo/entrypoints/openai/` +- **B. `fastvideo/entrypoints/server/{stateless,streaming}/`** — reorg both +- **C. `fastvideo/streaming/`** — top-level package, not under entrypoints + +### Decision: **A (parallel subpackage)** + +Rationale: lowest-friction, no existing code moves, both servers share +the same `fastvideo/entrypoints/*` namespace and import style. Shared +utilities can be factored into `fastvideo/entrypoints/server_common/` +later if needed. Option B creates churn across every openai/ import for +marginal organizational win. + +### Target layout + +```text +fastvideo/entrypoints/ +├── openai/ # existing: stateless HTTP POST +│ ├── api_server.py +│ ├── video_api.py +│ ├── image_api.py +│ ├── common_api.py +│ ├── protocol.py +│ ├── state.py +│ ├── stores.py +│ └── utils.py +├── streaming/ # NEW: session WebSocket +│ ├── server.py # FastAPI + WebSocket entry +│ ├── session.py # session lifecycle, state machine +│ ├── session_store.py # typed session state + snapshot/hydrate +│ ├── protocol.py # JSON WebSocket message schemas +│ ├── stream.py # fMP4 encoding (av_fmp4 mode) +│ ├── gpu_pool.py # subprocess workers +│ ├── worker.py # per-GPU worker loop +│ ├── continuation.py # typed LTX2 state payload +│ ├── session_init_image.py +│ ├── session_logger.py +│ ├── mock_server.py +│ ├── prompt/ +│ │ ├── enhancer.py # provider-agnostic prompt ops +│ │ ├── rewrite.py +│ │ ├── safety.py # optional fasttext +│ │ ├── payload.py # rewrite payload builder +│ │ └── providers/ +│ │ ├── base.py # LLMProvider protocol +│ │ ├── cerebras.py +│ │ ├── cerebras_ifm.py +│ │ └── groq.py +│ └── router/ # or separate top-level package +│ ├── main.py +│ └── registry.py +├── cli/ # existing +└── video_generator.py # existing +``` + +### Config integration + +`ServeConfig` gets an optional `streaming: StreamingConfig | None` field: + +```python +@dataclass +class StreamingConfig: + session_timeout_seconds: int = 300 + generation_segment_cap: int = 6 + stream_mode: Literal["av_fmp4", "legacy_jpeg"] = "av_fmp4" + warmup: WarmupConfig = field(default_factory=WarmupConfig) + pool: GpuPoolConfig = field(default_factory=GpuPoolConfig) + prompt: PromptEnhancerConfig | None = None + safety: PromptSafetyConfig | None = None + +@dataclass +class GpuPoolConfig: + num_workers: int | None = None # default: CUDA_VISIBLE_DEVICES count + enable_audio_reencode: bool = True + conditioning_num_frames: int = 9 + conditioning_end_offset: int = 0 + +@dataclass +class PromptEnhancerConfig: + provider: Literal["cerebras_ifm", "cerebras", "groq"] = "cerebras_ifm" + model: str = "gpt-oss-120b" + timeout_ms: int = 20000 + system_prompt_dir: str | None = None # hot-reloadable system prompts + +@dataclass +class PromptSafetyConfig: + enabled: bool = False + classifier_path: str | None = None +``` + +## Design Decision 3: LLM provider abstraction + +### Problem + +`prompt_enhancer.py` (69KB) hard-codes three providers (cerebras_ifm, +cerebras, groq) with provider-specific request/response handling +scattered throughout. Upstreaming as-is locks FastVideo to those three +providers and couples the prompt operations to their response shapes. + +### Shape + +Introduce an `LLMProvider` protocol: + +```python +from typing import Protocol, AsyncIterator, Literal +from dataclasses import dataclass + +@dataclass +class LLMMessage: + role: Literal["system", "user", "assistant"] + content: str + +@dataclass +class LLMRequest: + messages: list[LLMMessage] + model: str + max_tokens: int | None = None + temperature: float | None = None + timeout_ms: int | None = None + +@dataclass +class LLMResponse: + content: str + provider: str + model: str + latency_ms: float + fallback_used: bool = False + +class LLMProvider(Protocol): + name: str + async def complete(self, request: LLMRequest) -> LLMResponse: ... +``` + +### Decision: **Protocol + built-in implementations for cerebras, cerebras_ifm, groq** + +Rationale: keeps the prompt enhancer free of provider-specific branching; +users (and future OpenAI/Anthropic/local additions) can register their +own provider without modifying FastVideo. Each built-in provider is +100-200 LOC; the enhancer becomes provider-agnostic prompt orchestration. + +### Implications +- `prompt_enhancer.py` splits into `enhancer.py` (prompt operations) + + `providers/` (IO). +- Config moves from scattered env vars to typed `PromptEnhancerConfig` + under `ServeConfig.streaming.prompt`. +- Hot-reloadable system prompts stay — exposed as a management endpoint + on the streaming server. +- Fallback behavior (retry across providers in priority order) moves + into the enhancer layer, orthogonal to provider implementations. + +## Design Decision 4 preamble: what Dynamo expects from FastVideo + +Dynamo's backend pattern (observed in +`dynamo/components/src/dynamo/sglang/` and confirmed by PR #7544) is a +**pure Python import** pattern. Dynamo owns the backend subpackage in its +own repo; FastVideo only needs to expose a stable, typed, aggregated +and (later) streaming generation surface. + +### Contract surface Dynamo consumes + +| Surface | Shape | Notes | +|---|---|---| +| Constructor | `VideoGenerator.from_pretrained(model_path, **typed_kwargs)` | Already exists; `typed_kwargs` must be a stable subset from `GeneratorConfig` — no flat LTX2 legacy kwargs. | +| Sync execution | `generator.generate_video(request: GenerationRequest) -> VideoResult` | Aggregated mode; Dynamo wraps in `asyncio.to_thread` under an `asyncio.Lock`. | +| Async execution | `generator.generate_async(request: GenerationRequest) -> AsyncGenerator[VideoEvent, None]` | Needed for: (a) streaming server fMP4 chunks; (b) future Dynamo disaggregation. Events: `Progress`, `Partial?`, `Final`. | +| Typed request | `fastvideo.api.GenerationRequest`, `SamplingConfig`, `InputConfig` | Stable import path; Dynamo's adapter builds this from `NvCreateVideoRequest` + `VideoNvExt`. | +| Typed result | `VideoResult` with `video_bytes` or tensor frames, plus `ContinuationState?` | Must be picklable / JSON-serializable enough for Dynamo RPC. | +| Continuation | `ContinuationState(kind, payload)` with schema-versioned payloads | Used by FastVideo's session store today; tomorrow by Dynamo disaggregated workers. | +| Health check input | `VideoGenerator.default_health_check_request() -> GenerationRequest` | Minimal 256x256 / 8 frames / 1 step; lets Dynamo's `FastVideoHealthCheckPayload.to_dict()` produce the Dynamo `health_check_payload` kwarg without knowledge of FastVideo internals. | +| Config dump | `GeneratorConfig.to_dict()` / `ServeConfig.to_dict()` | Dynamo calls `dynamo.common.config_dump.dump_config(path, config)` at worker start; we already have `config_to_dict()`. | + +### Request/response mapping (Dynamo ↔ FastVideo) + +Dynamo's video protocol (`NvCreateVideoRequest` / `NvVideosResponse`): + +``` +NvCreateVideoRequest -> fastvideo.api.GenerationRequest + prompt -> sampling.prompt + size="WxH" -> sampling.width, sampling.height + seconds -> (seconds * nvext.fps) -> sampling.num_frames + input_reference -> input.image_path / input.video_path + nvext.fps -> sampling.fps + nvext.num_frames -> sampling.num_frames (overrides seconds*fps) + nvext.num_inference_steps -> sampling.num_inference_steps + nvext.guidance_scale -> sampling.guidance_scale + nvext.seed -> sampling.seed + nvext.negative_prompt -> sampling.negative_prompt + response_format -> (handled by adapter at output) + +VideoFinalEvent -> NvVideosResponse + video_bytes -> data[0].b64_json (if response_format=b64_json) + video_url (after upload) -> data[0].url (if response_format=url) + metadata.inference_time_s -> inference_time_s +``` + +All fields already exist (or will exist after PR 6 expansion) on +FastVideo's typed schema. No FastVideo changes required beyond what the +rest of this plan already covers **except**: + +1. `generate_async` must exist (new in PR 7.10). +2. `default_health_check_request()` helper (new in PR 7.10). +3. The sync `generate_video(request=...)` path must be reachable without + extra wrapping (exists since PR 2; confirm stability). + +### Where the Dynamo subpackage lives + +The Dynamo-side integration (`FastVideoHandler`, `register_fastvideo_model`, +`FastVideoHealthCheckPayload`, args parsing, main.py, Dockerfile, +request/response mapping) lives **entirely in the Dynamo repo** at +`components/src/dynamo/fastvideo/`, matching the pattern used by vllm +and sglang. FastVideo does **not** host any Dynamo-related subpackage, +Dynamo dependency, or Dynamo-specific CLI. FastVideo's only obligation +is to expose a clean, stable, typed Python API that Dynamo's backend +package can import. + +## Design Decision 4: Dynamo as first-class backend target + +### Problem + +PR #7544 (closed) shows two frictions with the pre-refactor API: + +1. **Flat legacy kwargs** — the Dynamo handler had to know about + LTX2-specific flat names. +2. **Sync-only generation** — Dynamo's async handler wrapped + `generator.generate(...)` in `asyncio.to_thread` under a lock; no + progress streaming, no disaggregation path. + +The refactor's stateless OpenAI server, WebSocket streaming server, and +Dynamo backend all want the same thing: **a typed async API that yields +progress events and a typed final result**. If we build it once in +`VideoGenerator`, all three adapters become thin. + +### Options + +**A. Keep sync-only, each adapter wraps** +- Simple; matches PR #7544. +- Con: streaming server needs its own async runner; Dynamo loses progress + streaming; no path to disaggregation. + +**B. Add async event stream to `VideoGenerator`** +- `generate_async(request) -> AsyncGenerator[VideoEvent, None]`. +- Sync `generate_video` becomes a thin `asyncio.run` wrapper internally. +- Pro: one canonical execution API; streaming server, OpenAI server, + and Dynamo all consume events directly. +- Con: larger delta in `VideoGenerator` — must thread async through the + pipeline step loop. + +**C. Queue-based `generate(request, event_cb)` callback** +- Middle ground; callback receives events. +- Pro: no async rewrite needed. +- Con: callers have to invert control; awkward for Dynamo's async + handler. + +### Decision: **B (async event stream)** + +Rationale: one substrate serves all three consumers. The cost is a +`generate_async` implementation that runs the pipeline step loop in a +thread and bridges events back via an asyncio queue — standard pattern, +limited surface area. + +### Implications + +- New PR 7.10 adds `generate_async` on `VideoGenerator` with three event + types: `VideoProgressEvent(step, total_steps, stage)`, + `VideoPartialEvent(frames_ndarray, index)` (optional; emitted only in + the streaming path), `VideoFinalEvent(video_bytes_or_tensor, metadata, + continuation_state?)`. +- Sync `generate_video(request=...)` becomes `asyncio.run(...)` over + `generate_async`, collecting events and returning the final. +- Streaming server's fMP4 encoder consumes `VideoPartialEvent` frames + directly, never re-decoding through disk. +- Dynamo adapter consumes `generate_async` and yields one + `NvVideosResponse` per `VideoFinalEvent` (aggregated mode; ignores + intermediate events today; can surface progress via Dynamo's + status/progress fields in the future). +- `ContinuationState` can be attached to `VideoFinalEvent.metadata`, + giving Dynamo a first-class way to surface state for disaggregation + later. +- Stable public exports: `from fastvideo import VideoGenerator`; + `from fastvideo.api import GenerationRequest, SamplingConfig, + ContinuationState, VideoResult, VideoEvent`. +- No Dynamo subpackage, dep, or CLI lives in FastVideo. The adapter + (`NvCreateVideoRequest ↔ GenerationRequest` mapping, handler, + registration) lives entirely in the Dynamo repo at + `components/src/dynamo/fastvideo/`. + +### Constraints this adds to earlier PRs + +- **PR 6** (typed LTX2 kwargs): every flat kwarg must have a typed home + **reachable from `GeneratorConfig`**, so Dynamo can construct the + generator without importing internal compat paths. +- **PR 7** (continuation state): `ContinuationState.payload` must be + JSON/YAML serializable (no raw torch tensors inline; use blob + indirection) so it survives Dynamo RPC transport. +- **PR 7.5** (streaming skeleton): consume `generate_async` rather than + re-implementing a progress loop around `generate_video`. +- **PR 2/3/4 already landed**: the typed request shape is fixed and + matches Dynamo's mapping needs — no backtracking required. + +## Revised PR sequence (PR 5 onwards) + +PRs 0-4 are unchanged and already landed. PR 5 is narrowed; PRs 5.5-7.9 +are new inserts; PRs 8-13 are reshaped or kept. + +| # | Title | Change | Key deliverables | +|---|---|---|---| +| **5** | Stateless `ServeConfig.default_request` merge | **Narrowed.** Wire typed default-request into `fastvideo/entrypoints/openai/`. | `_merge_default_request` helper, validated-against-preset, tests for default+user-override precedence | +| **5.5** | Server architecture split | **NEW.** Introduce `fastvideo/entrypoints/streaming/` subpackage skeleton. No behavior change. | Empty subpackage + stub server.py; CLI subcommand `fastvideo streaming-serve` (raises NotImplementedError); doc on layout | +| **6** | LTX2 public preset + stage overrides + config colocation | **Expanded.** Also add typed replacements for every flat kwarg used by internal `gpu_pool.py`. | `ltx2_two_stage` preset, `LTX2RefineStageOverride`, `CompileConfig` field types, typed `FP4Config` integration, colocation | +| **7** | Continuation state (public + session) | **Expanded.** Define both opaque payload AND server-held session store. | `ContinuationState.payload` schema, `LTX2ContinuationState` typed subclass, `SessionStore` interface, snapshot/hydrate APIs | +| **7.5** | Streaming server skeleton | **NEW.** Minimum viable WebSocket server: session lifecycle, JSON messages, fMP4 output, single-generator. | `server.py`, `session.py`, `protocol.py`, `stream.py` (fMP4), typed `StreamingConfig` | +| **7.6** | GPU pool upstream | **NEW.** Upstream `gpu_pool.py` with typed config boundary. | `gpu_pool.py`, `worker.py`, job queue, session-to-GPU binding, session timeout handling | +| **7.7** | Prompt enhancer upstream | **NEW.** Upstream `prompt_enhancer.py` with `LLMProvider` abstraction. | `prompt/enhancer.py`, `prompt/providers/{base,cerebras,cerebras_ifm,groq}.py`, hot-reloadable system prompts | +| **7.8** | Streaming auxiliaries | **NEW.** Small, isolated. | `prompt/safety.py`, `session_init_image.py`, `prompt/rewrite.py`, `session_logger.py`, `mock_server.py` | +| **7.9** | Router upstream | **NEW.** Multi-replica load balancer + WS proxy. | `streaming/router/` (or separate top-level package), health checks, WS proxy | +| **7.10** | Dynamo backend contract | **NEW.** Add `VideoGenerator.generate_async` event stream + `default_health_check_request()` helper. FastVideo exposes the async API only; the Dynamo backend package (handler, adapter, registration) lives entirely in the Dynamo repo at `components/src/dynamo/fastvideo/`. Streaming server (PR 7.5) and Dynamo backend both consume the same async API. | `generate_async` with `VideoProgressEvent`/`VideoPartialEvent`/`VideoFinalEvent`; sync `generate_video` becomes a thin wrapper; contract tests against a mock Dynamo-style handler that imports only public FastVideo APIs | +| **8** | Internal-UI ↔ public-server contract docs & tests | **Reframed.** Was "Dreamverse Server Adaptation Layer." Also covers Dynamo integration reference. | WebSocket protocol reference, contract tests, migration examples, Dynamo adapter example that upstream PR can copy verbatim | +| **9** | LongCat preset migration + colocation | **Keep.** | Stage overrides, colocation | +| **10** | Hunyuan15 SR preset migration + colocation | **Keep.** | Stage overrides, SR field migration POC, colocation | +| **11** | SSIM / perf test migration | **Keep.** Now blocked on PR 6 expansion. | Typed API migration of golden tests | +| **12** | Docs + examples | **Keep, expand.** | Streaming server docs now part of scope | +| **13** | Deprecation + cleanup | **Keep, expand.** | Also deprecate flat kwargs that internal gpu_pool uses today | + +Total PR count: 13 → ~20 (13 original + 5 streaming-upstream inserts + +1 architecture split + 1 Dynamo contract). Each new PR is small and +self-contained because the streaming components are already cleanly +separated in the internal repo, and the Dynamo contract rides on top of +the async API that the streaming server already needs. + +## Open questions + +1. **Router: in-repo or separate package?** — It's orthogonal to inference; + in-repo couples deploy cycles, separate leaves FastVideo cleaner. + Recommendation: separate package `fastvideo-router/` or + `fastvideo/contrib/router/`; defer final call to PR 7.9. +2. **Session ID authority** — internal uses ad-hoc client IDs. + Recommendation: server-generated UUID, accept externally provided + session ID only for resume flows. +3. **Torch compile kwargs typing** — `CompileConfig.kwargs: dict[str, Any]` + today accepts `mode`, `backend`, `fullgraph`, `dynamic`. Options: keep + as opaque dict; fully type; hybrid (type the common four + allow + extras). Recommendation: hybrid, type common fields. +4. **Prompt safety / fasttext dependency** — heavy for users who don't + need it. Recommendation: ship as optional extra + `pip install fastvideo[prompt-safety]`. +5. **Audio-specific tensor payloads** — `ltx2_audio_clean_latent`, + `ltx2_audio_denoise_mask`, `ltx2_audio_latents` are not in the current + public schema. PR 7 should classify them (probably as opaque fields + inside `LTX2ContinuationState.payload`, not top-level sampling fields). +6. **Batching behavior** — internal `test_batching.py` suggests batching + is exercised. Scope this into PR 7.5 or defer to a post-cleanup perf PR? +7. ~~**Dynamo subpackage home**~~ — **Resolved.** No Dynamo code lives + in FastVideo. The full backend package (handler, adapter, + registration, health check) is owned by the Dynamo repo at + `components/src/dynamo/fastvideo/`, same pattern as vllm/sglang. + FastVideo only guarantees the public API contract listed above. +8. **Disaggregation readiness** — PR #7544 is aggregated-only. Our + `ContinuationState` hybrid already supports a future prefill/decode + split (prefill yields state; decode hydrates it). Should PR 7.10 + explicitly validate that `ContinuationState` survives round-trip + through a Dynamo-style RPC (pickle or JSON), even though Dynamo + isn't using it today? Recommendation: yes; cheap contract test that + prevents drift. +9. **Dynamo progress/status passthrough** — `NvVideosResponse` has + `status` and `progress` fields. Should PR 7.10's handler contract + emit intermediate `NvVideosResponse` chunks keyed off + `VideoProgressEvent`, or stay aggregated-final-only to match PR + #7544? Recommendation: stay aggregated-final for PR 7.10; revisit + after Dynamo clarifies their streaming/progress semantics. + +## Immediate path forward + +1. Land `will/api_5` cleanup commits — **done** (`e03ca7d9`, `41f93179` + force-pushed without Claude co-author). +2. Review this plan with a human — commit the doc to capture the state. +3. Execute PR 5 (narrow stateless merge) and PR 5.5 (subpackage split) + in parallel. Both small; both unblock the streaming upstream that + follows. +4. Start PR 6 expansion (typed replacements for flat LTX2 kwargs) as the + critical path for PR 7.6 (gpu_pool upstream). diff --git a/.agents/memory/dreamverse-integration/source-archive/video-generator-config-api-design.md b/.agents/memory/dreamverse-integration/source-archive/video-generator-config-api-design.md new file mode 100644 index 0000000000..c1d7e586cf --- /dev/null +++ b/.agents/memory/dreamverse-integration/source-archive/video-generator-config-api-design.md @@ -0,0 +1,93 @@ +# Exploration Log: Video Generator Config API Design + +## Status: draft + +## Context +FastVideo's Python inference API currently mixes generator-instance settings, +pipeline initialization settings, and per-request sampling/runtime settings +through broad `**kwargs` surfaces on `VideoGenerator.from_pretrained(...)` and +`VideoGenerator.generate_video(...)`. + +This exploration compares the current FastVideo design with +`sglang/multimodal_gen` and examines how to upstream multi-stage LTX2 / +Dreamverse behavior without growing more ad hoc top-level flags. + +## Progress +- [x] Read FastVideo onboarding, codebase map, and relevant design docs. +- [x] Inspect current FastVideo generator, args, sampling, registry, and + workflow abstractions. +- [x] Inspect internal LTX2 streaming server usage and current two-stage / + continuation requirements. +- [x] Inspect SGL diffusion generator, server args, sampling params, and + request preparation boundary. +- [x] Inspect vLLM-Omni stage config, stage metadata, request, and orchestration + surfaces for multi-stage pipeline ideas. +- [x] Inspect current FastVideo CLI/config-file loading and compare with the + training YAML-only entrypoint. +- [ ] Convert findings into a concrete implementation plan for FastVideo. + +## Findings +- FastVideo already has the right internal separation points: + `FastVideoArgs`, `PipelineConfig`, `SamplingParam`, and `ForwardBatch`. +- The public boundary is the unstable part: + init-time and request-time knobs are mixed through `**kwargs`. +- Unknown init keys can be silently filtered, while unknown request keys can be + only logged rather than rejected. This makes API drift hard to detect. +- SGL's split is cleaner: + `ServerArgs` for engine/runtime, `PipelineConfig` for model-family wiring, + and `SamplingParams` for per-request settings. +- SGL also has better merge semantics for user request overrides: + it preserves model defaults, tracks explicitly provided fields, and validates + request params against pipeline task type. +- SGL still has a design smell worth avoiding in FastVideo: + `SamplingParams._adjust(...)` depends on `ServerArgs`, which leaks + engine/pipeline concerns back into the request object. +- vLLM-Omni contributes a useful extra abstraction beyond SGL: + model-owned multi-stage topology via `ModelPipeline` and `StageConfig`, + with per-stage defaults (`default_sampling_params`) and runtime override + layering. +- vLLM-Omni's best reusable idea for FastVideo is not the serving stack, but + the separation between: + 1. model-defined stage topology and per-stage defaults, + 2. runtime engine overrides, + 3. request-time sampling/state handoff. +- vLLM-Omni also shows the downside of exposing stage-indexed request lists too + directly: `sampling_params_list` works for a serving engine, but is too + positional and low-level for FastVideo's higher-level Python API. +- FastVideo already supports YAML/JSON config files for inference CLI, but the + current mechanism flattens nested documents back into argparse flags. This + preserves backward compatibility but keeps the CLI surface as the canonical + schema instead of a typed document model. +- The training stack has a cleaner precedent: a YAML-first config loaded into a + typed schema, with dotted CLI overrides applied onto the nested document + before parsing. Inference can likely adopt a lighter variant of that pattern. +- Multi-stage generation should be unified at the orchestration layer, not by + forcing LongCat refine, Hunyuan SR, and LTX2 continuation into one leaf config. + +## Mistakes / Dead Ends +- A fully free-form string-dict API would lose too much type safety and would + likely recreate the current drift problem under a different shape. +- A single universal `RefineConfig` for all models would become a sparse bag of + nullable fields and would not map cleanly to existing model families. + +## Proposed Standardization +- Introduce a typed public split: + `GeneratorConfig` for instance-lifetime engine/init settings and + `GenerationRequest` for per-call inputs/sampling/output. +- Allow dict input only as an interchange layer that is parsed immediately into + typed configs with strict unknown-key validation. +- Add a typed `GenerationPlan` / multi-stage orchestration layer with + discriminated stage configs: + `SampleStageConfig`, `LongCatRefineStageConfig`, + `HunyuanSRStageConfig`, `LTX2ContinuationStageConfig`. +- Let model families own stage defaults and stage topology through named + profiles or model-defined stage plans, similar in spirit to vLLM-Omni's + pipeline YAMLs, but expose them through typed Python config objects rather + than raw stage-indexed lists in the primary API. +- Make YAML/JSON a first-class serialization of the same typed inference + schema, not just a file format that expands into CLI flags. +- Prefer a YAML-first CLI pattern for nested configs: + `fastvideo generate --config run.yaml --request.sampling.seed 42`, + while keeping a compatibility layer for existing flat flags during migration. +- Upstream LTX2 two-stage / continuation behavior as a first-class stage or + pipeline profile rather than more `ltx2_*` top-level kwargs. diff --git a/.agents/memory/dreamverse-integration/state.md b/.agents/memory/dreamverse-integration/state.md new file mode 100644 index 0000000000..7e5e18d8e8 --- /dev/null +++ b/.agents/memory/dreamverse-integration/state.md @@ -0,0 +1,196 @@ +# Current State — 2026-05-06 (D-26 rebase onto origin/main; PR base flipped) + +Point-in-time snapshot of branches, commits, and live infrastructure. +Update whenever commits land or services restart. + +For HOW to commit / push / verify see [runbook.md](runbook.md). For +roster of co-authors to credit on every commit see +[authors.md](authors.md). + +## Branch tips + +| Repo | Branch | Tip | Distance | +|---|---|---|---| +| FastVideo | `will/ltx2_sr_port` (**PR #1288 head**) | `fbd823df` | merged-into-main pending; latest tip post-D-16 + integration-review + integration-plan + GPU4 smoke validation | +| FastVideo | **`will/dreamverse-monorepo`** (**REBASED ONTO `origin/main`**, was forked from `will/ltx2_sr_port`) | `83829c5e` | 66 commits ahead of `origin/main` (`c17d33bf`). Contains the full LTX-2 SR port + NVFP4 + Dreamverse monorepo migration + audio kwarg fix + warmup + NVENC build + benchmarks + integration memory dir, all rebased to be openable as a single PR against main. PR #1288 on `will/ltx2_sr_port` is untouched. End-to-end verified on GPU4 pre-rebase with audio continuation across segments 1→2 (`Cached audio latents shape=(1, 8, 126, 16) for segment 2`, `Segment 2: relayed av chunks=22, bytes=3.8MB`, no BrokenPipeError). NVENC build supported but not usable on this dev host (B200 has no NVENC silicon — verified by direct ffmpeg probe). See [decisions-log.md D-19](decisions-log.md#d-19) + [D-20](decisions-log.md#d-20) + [D-21](decisions-log.md#d-21) + [D-26](decisions-log.md#d-26). | +| FastVideo | `will/dreamverse-monorepo-pre-main-rebase-backup-20260506` | `2ee839a3` | **local-only safety backup** of the pre-rebase chain (the same 66 commits stacked on `2aaeee2a`). Keep until the new chain is fully verified by the next round of e2e on a non-stuck dev box or until the PR merges. | +| FastVideo | `will/api_7.10` | `6ae7a99f` | **deprecated** — PR #1287 closed in favor of #1288. Branch can be deleted on origin and locally; kept for now as historical reference. | +| FastVideo | `will/api_8`, `will/ltx2_sr_runtime`, `will/ltx2_nvfp4`, `will/ltx2_post_fixes`, `will/agents_cleanup` | (various) | **deprecated** split bookmarks. Strategy reversed to single mega-PR (D-17). Safe to delete locally; not pushed to origin. | +| FastVideo | `will/ltx2_sr_port-pre-1286-rebase` | `1baa60bb` | **local-only safety backup** of pre-rebase chain (37 commits); keep until next slice merges | +| Dreamverse | `will/integrate-public-fastvideo` | `ec8ef92` | 10 commits ahead of `737f3c1` (the dep switch) | +| FastVideo-internal | their `main` | (read-only ref) | — | + +FastVideo worktree default branch is `will/ltx2_sr_port`. Other agents +share this worktree — if `git branch --show-current` shows something +else, switch back cleanly with `git checkout will/ltx2_sr_port` (don't +disturb their uncommitted work). I observed this happen repeatedly in +the 2026-05-05 session — confirmed harmless; switching back was always +safe with a clean working tree. + +## Post-#1286 rebase summary + +PR #1286 merged at `2aaeee2a` (squash). `will/ltx2_sr_port` was rebased +onto new `origin/main`, dropping 4 commits whose content is now in main: + +- `cd76cf51` `[feat] streaming: router (multi-replica load balancer)` +- `1ac1e732` `[feat] streaming: fastvideo router-serve CLI` +- `b0b7f59c` `[test] streaming: router registry + health loop ...` +- `40e265b8` `[fix] streaming: router polish — bridge cancel + state + machine + deps` (squashed into `2aaeee2a` via cherry-pick `a152cb77`) + +Rebase was clean — no conflicts. All 33 surviving commits got new SHAs +(rebase rewrites). The pre-rebase tip `1baa60bb` is preserved on the +local backup branch `will/ltx2_sr_port-pre-1286-rebase`. + +## New linearized chain (33 commits, slice indices for STACK.md) + +| Slice | PR | Commits | Tip SHA | Subject | +|---|---|---|---|---| +| 1-3 | 7.10 (PR #1287) | 3 | `6ae7a99f` | `[test] streaming: generate_async coverage + refreshed streaming test` | +| 4-6 | 8 | 3 | `f32e31ec` | `[test] streaming: contract tests for Dreamverse + Dynamo shapes` | +| 7-15 | LTX-2 SR | 9 | `e7297519` | `feat(ltx2): full i2v conditioning + continuation latent port` | +| 16-21 | NVFP4 | 6 | `6793166b` | `test(nvfp4): lock LTX-2 wiring + typed transformer_quant flow` | +| 22-23 | LTX-2 post-fixes | 2 | `25897b67` | `[fix]: unwrap list-of-generator before torch.randn in LTX-2 latent prep` | +| 24-33 | agents_cleanup | 10 | `b34d9704` | `[docs] dreamverse-integration: add runbook + fresh-context onboarding` | + +5 PRs landed (7.5, 7.6, 7.7, 7.8, 7.9), 1 in flight (7.10), 5 remaining +(8 / LTX-2 SR / NVFP4 / post-fixes / agents_cleanup). + +## Historical commit chain analysis (pre-#1286 rebase) + +The layered chain analysis below documented the pre-rebase SHAs (LTX-2 +SR layer, NVFP4 layer, post-handoff fixes layer). Those SHAs no longer +exist on `will/ltx2_sr_port` — they live only on +`will/ltx2_sr_port-pre-1286-rebase`. Content semantics are unchanged; +SHAs were rewritten by the rebase. Kept here for narrative continuity. + +## FastVideo: commit chain `cfccd292..156103b9` + +Three layers since LTX-2 i2v port: + +### Layer 1 — LTX-2 SR port + alignment harness (5 commits) + +``` +365a66c7 feat(quantization): upstream LTX-2 FP4Config with lazy flashinfer +433d26b2 feat(ltx2): port LTX-2 SR runtime — upsampler, refine stages, refine args +751d05de feat(ltx2): wire SR pipeline graph + port denoising/latent-prep stages +af6bbfea test(ltx2-sr): add numerical alignment harness — public vs internal +974cd430 fix(ltx2-sr): close port gaps surfaced by alignment harness retries +b6ac7630 test(ltx2-sr): pin ltx2 sampling knobs in harness for parity diff +b043d550 fix(api): align public SamplingParam ltx2 defaults with distilled +663dda80 fix(registry): order LTX-2 detectors so distilled wins for distilled paths +cfccd292 feat(ltx2): full i2v conditioning + continuation latent port (BASE) +``` + +(Predates the May 2 handoff.) + +### Layer 2 — NVFP4 wire-up + per-component compile (6 commits, May 2 handoff) + +``` +a4760bae fix(api): propagate generic refine_* args + match internal randn +221cb20a feat(api): typed per-component CompileConfig + FastVideoArgs carriers +6da342ba feat(compile): per-component compile + transformer_refine + prepare hook +42b30bf9 feat(ltx2): wire FP4 inference through fastvideo.layers.quantization +94c983a2 refactor(quant): rename FP4 → NVFP4 to disambiguate from other FP4 variants +c6c14c55 test(nvfp4): lock LTX-2 wiring + typed transformer_quant flow +``` + +See [quantization.md](quantization.md) for what each commit locks in. + +### Layer 3 — Post-handoff parity/perf fixes (3 commits, since May 2) + +``` +a5fcd19c [fix]: lazy-import flash_attn 2 fallback in attention backend +d4ee5be2 [fix]: avoid model.to() round-trip in Gemma encoder forward +156103b9 [fix]: unwrap list-of-generator before torch.randn in LTX-2 latent prep (HEAD) +``` + +Three small fixes — no new features. Continued parity tightening with internal. + +## Dreamverse: commit chain `737f3c1..ec8ef92` + +``` +737f3c1 chore: switch fastvideo dep from FastVideo-internal to public FastVideo +4cc6b30 chore: gitignore Playwright + Next.js build artifacts under apps/web +33caa92 test(e2e): align Playwright specs with the actual production composer +6fd137c test(e2e): tighten frontend-shell + preset specs to match actual UI +248060b test(e2e): add Playwright tier with backend-health smoke + preset run +d80c2a8 refactor(server): drive FP4 + per-component compile via typed GeneratorConfig +3d7fd89 feat(skill): launch-demo orchestrator + fastvideo serve YAML +72f69b9 Update ffmpeg installation instructions. +1ba5635 fix(server): block startup on GPU warmup readiness, propagate failures +ec8ef92 fix(server): detect worker death in _send_command via proc.sentinel (HEAD) +``` + +The post-handoff trio (`72f69b9`, `1ba5635`, `ec8ef92`) hardens server +startup robustness — ffmpeg install docs, GPU warmup readiness gate, and +worker-death detection. + +## Live services (do not duplicate) + +| Port | Service | PID | Status | +|---|---|---|---| +| 8009 | `dreamverse-server` | 705513 | `/readyz` returns 200, 1 GPU worker on GPU 4, NVFP4 (50.9 GiB), `ENABLE_TORCH_COMPILE=0`, `FASTVIDEO_FFMPEG_BIN=$HOME/opt/ffmpeg-native/bin/ffmpeg`, `FASTVIDEO_VIDEO_CODEC=libx264` (post-D-20 deploy at 2026-05-05 14:??) | +| 5274 | `next-server` (dev) | 707746 | 200 | +| 8000 | unknown FastAPI | — | **Not in handoff.** Probably stray `fastvideo serve`. Verify with `lsof -i :8000` before launching a new BE on the default port. | + +## Stashes — DO NOT POP + +| Repo | Stash | Reason | +|---|---|---| +| FastVideo | `stash@{0}: WIP on main: 71bfc13d HunyuanVideo plugin` | Pre-existing, unrelated to integration work | +| Dreamverse | `stash@{0}: wip: server modular refactor (split config/prompting/runtime/session)` | 3867-line orphan modular split, **not part of `will/integrate-public-fastvideo`**. Recover on a separate branch if needed. | + +## Test status + +| Suite | Status | +|---|---| +| FastVideo `fastvideo/tests/api/` (post-D-20) | 185 passed (was 222 before some tests moved; new `test_extra_overrides_routing.py` adds 7) | +| FastVideo `contract/` + `nvfp4_*` + `ltx2_pipeline_smoke` (May 2 handoff) | 222 passed, 1 skipped | +| Playwright e2e against live BE+FE (D-19) | 8 passed (5 backend-health + 2 frontend-shell + 1 preset-prompt-generation) | +| Live segment-1→segment-2 audio continuation (D-20) | passes — `Cached audio latents shape=(1, 8, 126, 16) for segment 2` + `Segment 2: relayed av chunks=22, bytes=3.8MB`, no BrokenPipeError | +| `dreamverse-deploy.sh` flag parser standalone test (D-20) | 13/13 permutations pass + bad-flag rejection (defaults / single flags / both flags / `--no-*` overrides / env-only / flag-overrides-env / both-env+both-no-flags / flags interleaved with positional args) | +| `fastvideo serve --config streaming_demo.yaml` validation (May 2 handoff) | parses cleanly; dotted overrides work | +| `bash -n` on `apps/dreamverse/scripts/install_native_ffmpeg.sh` + `dreamverse-deploy.sh` (D-20) | clean | + +## Pre-existing failures (NOT caused by this work) + +| Test | Failure | Notes | +|---|---|---| +| `fastvideo/tests/ops/quantization/test_absmax_fp8.py::test_create_weights_rejects_invalid_dtype` | `AssertionError not raised` | Pre-existing on `main`. Verified via `git stash` that NVFP4 work doesn't introduce it. See [open-threads.md](open-threads.md) item #2. | + +## Source docs (archived 2026-05-03) + +The 7 source docs that this memory dir consolidates have been moved into +[`source-archive/`](source-archive/) — see the +[archive README](source-archive/README.md) for the archive policy and +synthesis mapping. + +Other untracked items at the FastVideo repo root: +- Nested clones: `dynamo/`, `ray/`, `vllm-omni/` +- Lock files: `uv.lock`, `fastvideo/tests/ssim/.reference_videos_download.lock` +- Skill dirs: `.agents/skills/diagnose-ssim-failure/`, `.agents/skills/review-pr-link/` +- `.agents/exploration/pr-link-review.md` (kept; already promoted to a skill) + +## Quick orientation commands + +```bash +# FastVideo state +cd /home/william5lin/FastVideo +git log --oneline cfccd292..HEAD # 14 commits this round + +# Dreamverse state +cd /home/william5lin/Dreamverse +git log --oneline 737f3c1..HEAD # 10 commits this round + +# Live stack health (already running) +curl -s http://localhost:8009/readyz | head -c 300 +curl -s http://localhost:5274/ -o /dev/null -w "%{http_code}\n" + +# Re-verify test suite +.venv/bin/python -m pytest fastvideo/tests/api/ \ + fastvideo/tests/contract/ \ + fastvideo/tests/ops/quantization/test_nvfp4_*.py \ + tests/local_tests/pipelines/test_ltx2_pipeline_smoke.py \ + -q --no-header +``` diff --git a/.agents/memory/dreamverse-integration/streaming-server.md b/.agents/memory/dreamverse-integration/streaming-server.md new file mode 100644 index 0000000000..e26775c52e --- /dev/null +++ b/.agents/memory/dreamverse-integration/streaming-server.md @@ -0,0 +1,389 @@ +# Streaming Server Upstream — PRs 5.5 → 7.10 + +The `FastVideo-internal/ui/ltx2-streaming/server/` stack is being +upstreamed into public FastVideo at `fastvideo/entrypoints/streaming/`. +In parallel, FastVideo is becoming a first-class Dynamo backend (same +tier as vllm, sglang, trtllm). This file covers both threads since they +share `generate_async` as the substrate. + +For PR sequence/status see [pr-roadmap.md](pr-roadmap.md). For the +Dreamverse-side adoption see [cross-repo-surfaces.md](cross-repo-surfaces.md). + +**Last updated:** 2026-05-03. + +## What's being upstreamed + +| Internal path | Size | Role | Public target | +|---|---|---|---| +| `server/main.py` | 94 KB | FastAPI + WebSocket, session lifecycle, segment orchestration | `fastvideo/entrypoints/streaming/server.py` + handlers | +| `server/gpu_pool.py` | 66 KB | GPU orchestration, subprocess workers | `fastvideo/entrypoints/streaming/gpu_pool.py` | +| `server/prompt_enhancer.py` | 69 KB | LLM orchestration (cerebras_ifm, cerebras, groq) | `fastvideo/entrypoints/streaming/prompt/` package | +| `server/mock_server.py` | 45 KB | Mock backend for dev/tests | `fastvideo/entrypoints/streaming/mock_server.py` | +| `server/prompt_safety.py` | 7 KB | Optional fasttext-gated prompt safety | `prompt/safety.py` | +| `server/session_init_image.py` | 3 KB | i2v init image handling | `streaming/session_init_image.py` (PR 7.5, already public) | +| `server/rewrite_prompt_payload.py` | 3 KB | Rewrite flow payload builder | `prompt/rewrite.py` | +| `server/session_logger.py` | 1 KB | Session JSONL logs | `streaming/session_logger.py` | +| `server/config.py` | 9 KB | Env-driven server config | typed `ServeConfig.streaming` extensions | +| `router/main.py` | 27 KB | Multi-replica load balancer + WS proxy | `fastvideo/entrypoints/streaming/router/` | +| `slurm/` | — | Deployment scripts | Stays internal | + +Frontend clients (`client/`, `prod-ui/`) stay in the internal repo. + +## Four design decisions that shape the upstream + +### D-1: Continuation model — Hybrid (server-held + opaque client-round-trip) + +Streaming WebSocket sessions hold continuation per-GPU (matches today's +internal behavior, fast, zero client bandwidth). Stateless HTTP endpoints +use opaque round-trip payloads. Server exposes a `snapshot_state` message +that returns the opaque form for migration/retry. + +One serialization layer underlies both surfaces. + +Implementation: `SessionStore` (in-memory default, pluggable for +redis/etc.) keyed by session ID, holds typed `LTX2ContinuationState`. +- `snapshot(session_id) -> ContinuationState` exports for migration +- `hydrate(state: ContinuationState) -> session_id` loads state into new session + +Payload schema covers: trailing conditioning frames (or tensor-blob ID), +audio latents (or blob ID), segment index, audio sample rate, +`video_position_offset_sec`, model-specific metadata. + +Landed in PR 7. See [cross-repo-surfaces.md](cross-repo-surfaces.md) for +the full wire format. + +### D-2: Streaming server layout — Parallel subpackage `fastvideo/entrypoints/streaming/` + +Sits next to `fastvideo/entrypoints/openai/`. No existing code moves. +Both servers share the `entrypoints/*` namespace. Shared utilities can be +factored into `fastvideo/entrypoints/server_common/` later if needed. + +### D-3: LLM provider abstraction — `LLMProvider` protocol + built-in providers + +`prompt_enhancer.py` (69 KB) hard-coded three providers (cerebras_ifm, +cerebras, groq) with provider-specific request/response handling +scattered throughout. Upstreaming as-is would lock FastVideo to those +providers. + +Protocol shape: + +```python +@dataclass +class LLMRequest: + messages: list[LLMMessage] + model: str + max_tokens: int | None = None + temperature: float | None = None + timeout_ms: int | None = None + +@dataclass +class LLMResponse: + content: str + provider: str + model: str + latency_ms: float + fallback_used: bool = False + +class LLMProvider(Protocol): + name: str + async def complete(self, request: LLMRequest) -> LLMResponse: ... +``` + +PR 7.7 ships built-in providers for cerebras, groq. **Public Literal +currently restricts to `Literal["cerebras", "groq"]`** — `cerebras_ifm` +is internal-only and remains environment-driven on `dreamverse-server`. +See [open-threads.md](open-threads.md) follow-up #3. + +Hot-reloadable system prompts via management endpoint. Sequential +fallback across providers in priority order — race-based fallback (the +internal optimization) deferred per [decisions-log.md](decisions-log.md) +D-3. + +### D-4: Dynamo as first-class backend target — async event stream + +PR ai-dynamo/dynamo#7544 (closed draft) showed two frictions: + +1. Flat legacy kwargs — Dynamo handler had to know LTX-2-specific names. +2. Sync-only generation — Dynamo wrapped `generator.generate(...)` in + `asyncio.to_thread` under a lock; no progress streaming, no + disaggregation path. + +Decision: **add `generate_async`** as the canonical execution API. + +```python +async def generate_async( + self, + request: GenerationRequest, +) -> AsyncGenerator[VideoEvent, None]: ... +``` + +Events: + +```python +@dataclass +class VideoProgressEvent: + step: int + total_steps: int + stage: str # "denoise" | "refine" | "decode" | ... + +@dataclass +class VideoPartialEvent: + frames: np.ndarray # (num_frames, H, W, 3) + index: int # monotonic chunk index + +@dataclass +class VideoFinalEvent: + video_bytes: bytes | None + tensor: torch.Tensor | None + metadata: dict[str, Any] + continuation_state: ContinuationState | None +``` + +The sync `generate_video(request=...) -> VideoResult` becomes a thin +`asyncio.run` wrapper over `generate_async` that collects events and +returns the final. + +**Three consumers, one substrate:** + +| Consumer | Transport | Request shape | State | +|---|---|---|---| +| Stateless OpenAI (`fastvideo/entrypoints/openai/`) | HTTP POST | `GenerationRequest` merged onto `ServeConfig.default_request` | Stateless; opaque payload | +| Streaming WebSocket (`fastvideo/entrypoints/streaming/`) | WebSocket JSON + binary fMP4 | `GenerationRequest` per segment, session-scoped | Server-held; per-GPU continuation cache | +| Dynamo native backend (`ai-dynamo/dynamo/components/src/dynamo/fastvideo/`) | Dynamo RPC endpoint | `NvCreateVideoRequest` ↔ adapter ↔ `GenerationRequest` | Aggregated today; future disaggregated via `ContinuationState` | + +**FastVideo does NOT host any Dynamo code.** The full backend package +(`args.py`, `main.py`, `backend.py`, `register.py`, `health_check.py`) +lives entirely in the Dynamo repo at `components/src/dynamo/fastvideo/`, +matching the vllm/sglang pattern. FastVideo's only obligation is the +stable public Python API. + +PR 7.10 lands the FastVideo-side contract. Dynamo backend code lives in +ai-dynamo/dynamo (next iteration of #7544 reopens against PR 8 reference +docs). + +## Target package layout + +``` +fastvideo/entrypoints/ +├── openai/ # existing: stateless HTTP POST +├── streaming/ # NEW: session WebSocket +│ ├── server.py # FastAPI + WebSocket entry +│ ├── session.py # session lifecycle, state machine +│ ├── session_store.py # typed session state + snapshot/hydrate +│ ├── protocol.py # JSON WebSocket message schemas +│ ├── stream.py # fMP4 encoding (av_fmp4 mode) +│ ├── gpu_pool.py # subprocess workers (PR 7.6) +│ ├── worker.py # per-GPU worker loop +│ ├── continuation.py # typed LTX2 state payload +│ ├── session_init_image.py +│ ├── session_logger.py +│ ├── mock_server.py +│ ├── prompt/ +│ │ ├── enhancer.py # provider-agnostic prompt ops +│ │ ├── rewrite.py +│ │ ├── safety.py # optional fasttext +│ │ └── providers/ +│ │ ├── base.py # LLMProvider protocol +│ │ ├── cerebras.py +│ │ ├── cerebras_ifm.py +│ │ └── groq.py +│ └── router/ +│ ├── main.py +│ └── registry.py +├── cli/ +└── video_generator.py +``` + +## Typed config integration + +`ServeConfig` gets an optional `streaming: StreamingConfig | None`: + +```python +@dataclass +class StreamingConfig: + session_timeout_seconds: int = 300 + generation_segment_cap: int = 6 + stream_mode: Literal["av_fmp4", "legacy_jpeg"] = "av_fmp4" + warmup: WarmupConfig = field(default_factory=WarmupConfig) + pool: GpuPoolConfig = field(default_factory=GpuPoolConfig) + prompt: PromptEnhancerConfig | None = None + safety: PromptSafetyConfig | None = None + +@dataclass +class GpuPoolConfig: + num_workers: int | None = None # default: CUDA_VISIBLE_DEVICES count + enable_audio_reencode: bool = True + conditioning_num_frames: int = 9 + conditioning_end_offset: int = 0 + +@dataclass +class PromptEnhancerConfig: + provider: Literal["cerebras", "groq"] = "cerebras" # cerebras_ifm pending + model: str = "gpt-oss-120b" + timeout_ms: int = 20000 + system_prompt_dir: str | None = None # hot-reloadable + +@dataclass +class PromptSafetyConfig: + enabled: bool = False + classifier_path: str | None = None +``` + +## `build_app` route contract — open follow-up + +Today `fastvideo.entrypoints.streaming.server.build_app` exposes only: + +- `GET /health` +- `WS /v1/stream` + +The Dreamverse Next.js shell expects these additional routes that the +upstream plan (and Dreamverse FE today) require: + +| Route | Owner per upstream plan | Status | +|---|---|---| +| `GET /healthz` | Streaming-server-side health (FastVideo) | 🔴 NOT YET MIGRATED | +| `GET /readyz` | Streaming-server-side health (FastVideo) | 🔴 NOT YET MIGRATED | +| `GET /status` | Streaming-server-side health (FastVideo) | 🔴 NOT YET MIGRATED | +| `GET /curated-presets` | Operator-side surface (Dreamverse) | 🟡 stays in Dreamverse, FE feature-detects | +| `POST /curated-presets/append` | Operator-side surface (Dreamverse) | 🟡 stays in Dreamverse | +| `GET /prompt-system-config` | Operator-side surface (Dreamverse) | 🟡 stays in Dreamverse | +| Devtools routes | Dreamverse-only | 🟡 stays in Dreamverse | + +Until the three health routes migrate into FastVideo's `build_app`, the +`BE_FLAVOR=fastvideo` flavor of `launch_demo.sh` is a "diagnostic" flavor +only (verifies typed serve-config path) — not FE-compatible. See +[open-threads.md](open-threads.md) follow-up #1. + +The streaming-upstream plan listed `/healthz`, `/readyz`, `/status`, +`/ws` as the contract that the upstream of `realtime/` → `streaming/` +must preserve. They were deferred from PR 7.5's MVP. + +## PR 7.5 status — open as #1251 + +Single-generator WebSocket end-to-end shipped (8 commits): + +1. `feat(streaming): protocol schemas + session state machine` +2. `feat(streaming): fMP4 encoder + session init-image persistence` +3. `feat(streaming): single-generator WebSocket server entry` +4. `test(streaming): server lifecycle + protocol + fMP4 coverage` +5. `docs(streaming): server contract spec` +6. `fix(streaming): restore missing-streaming-block guard + retire stub-era test` +7. `simplify(streaming): review follow-ups (idle timeout via asyncio.wait_for, _send_error helper, _cleanup_session, Protocol-typed generator, cleanup-on-disconnect)` +8. `fix(streaming): enforce idle timeout on receive_json + flag generator-cancellation gap (TODO → PR 7.10)` + +Deferred TODOs (intentionally) blocking on PR 7.10: + +- **Per-step progress events** — only terminal `step_complete` today; + needs `generate_async` for per-step `VideoProgressEvent` emission. +- **Mid-segment cancellation on client disconnect** — TODO marker in + `server.py` near `pool.run`. Needs `generate_async`'s cancellation + propagation. + +## PR 7.6 status — branch ready, not yet PR'd + +`will/api_7.6` (5 commits, rebased on 7.5): + +1. `feat [7.6/n]: GPU pool manager with typed worker boundary` +2. `refactor [7.6/n]: route streaming server through GpuPool` +3. `test [7.6/n]: GPU pool coverage (in-process + subprocess)` +4. `fix(streaming): restore missing asyncio import in server` (rebase fixup) +5. `feat(streaming): extract worker.py and add two-segment warmup` + +Tests: 17/17 gpu_pool tests + 89/89 streaming tests green. + +Ships: +- `GpuPool` ABC + `InProcessGpuPool` + `SubprocessGpuPool` + + `PoolAssignment` / `PoolHealth` / `PoolAcquireTimeout` +- `worker.py` — per-GPU `worker_main` and two-segment warmup helper +- Subprocess startup uses typed `GeneratorConfig`, NOT flat kwargs +- Session-to-GPU binding with timeout + queue for contention +- Two-segment startup warmup per worker (segment 1 fresh + segment 2 + with returned `ContinuationState` so both compile branches are primed) +- `SessionStore` (from PR 7) wired for per-GPU continuation cache + +Deferred to PR 7.10: + +- **Audio re-encode (`LTX2AudioEncoder`, `AudioProcessor`)**: internal + `_re_encode_audio` runs *inside* the per-step streaming loop + (`_stream_av_fmp4_events` / `do_step_ltx2`). The whole-segment + `pool.run()` path PR 7.6 ships doesn't need it. Re-encode is a + per-step streaming concern that belongs with `generate_async`. +- **Deprecate `VideoGenerator.from_pretrained(**flat_kwargs)`**: belongs + with PR 13 cleanup. + +## PR 7.10 — the unlock PR + +PR 7.10 adds `generate_async` and closes three open threads +simultaneously: + +- Q-5 / D-5: audio re-encode for cross-segment continuity +- Q-9: Dynamo progress passthrough +- PR 7.5's mid-segment cancellation TODO (client disconnect → + `asyncio.CancelledError` → GPU work stops) + +Plus health-check helper: + +```python +def default_health_check_request(self) -> GenerationRequest: ... +# Returns 256x256, 8 frames, 1 step. Lets Dynamo's +# FastVideoHealthCheckPayload.to_dict() produce a Dynamo +# health_check_payload kwarg without knowledge of FastVideo internals. +``` + +Stable public exports: + +```python +from fastvideo import VideoGenerator +from fastvideo.api import ( + GenerationRequest, SamplingConfig, ContinuationState, + VideoResult, VideoEvent, + VideoProgressEvent, VideoPartialEvent, VideoFinalEvent, +) +``` + +Streaming server (PR 7.5) gets rewired to consume `generate_async` +directly — no wrapper duplication. + +## Dynamo request/response mapping + +``` +NvCreateVideoRequest -> fastvideo.api.GenerationRequest + prompt -> sampling.prompt + size="WxH" -> sampling.width, sampling.height + seconds -> seconds * nvext.fps -> sampling.num_frames + input_reference -> input.image_path | input.video_path + nvext.fps -> sampling.fps + nvext.num_frames -> sampling.num_frames (overrides seconds*fps) + nvext.num_inference_steps -> sampling.num_inference_steps + nvext.guidance_scale -> sampling.guidance_scale + nvext.seed -> sampling.seed + nvext.negative_prompt -> sampling.negative_prompt + response_format -> (handled at adapter's output stage) + +VideoFinalEvent -> NvVideosResponse + video_bytes -> data[0].b64_json (response_format=b64_json) + uploaded URL -> data[0].url (response_format=url) + metadata.inference_time_s -> inference_time_s + continuation_state -> (reserved for future disaggregation) +``` + +## Open questions + +1. **Router placement** — in-tree at `fastvideo/entrypoints/streaming/router/` + (current implementation per PR 7.9) or separate package + `fastvideo-router/` / `fastvideo/contrib/router/`. Effectively + resolved in-tree by the PR 7.9 implementation. +2. **Session ID authority** — server-generated UUID; accept externally + provided session ID only for resume flows. +3. **Disaggregation readiness contract test** — should PR 7.10 validate + `ContinuationState` survives round-trip through Dynamo-style RPC + (pickle or JSON), even though Dynamo isn't using it today? + Recommended: yes; cheap regression guard. +4. **Dynamo progress/status passthrough** — should PR 7.10's handler + contract emit intermediate `NvVideosResponse` chunks keyed off + `VideoProgressEvent`, or stay aggregated-final-only? Recommended: + stay aggregated-final for PR 7.10; revisit after Dynamo clarifies. +5. **`video_position_offset_sec` semantics** — see [decisions-log.md](decisions-log.md) + open question; needs decision before PR 7.6 emits state. +6. **`SessionStore` / `BlobStore` lifecycle** — eviction, TTL, blob-drop + on state replacement; defer to PR 7.5 design pass. diff --git a/.agents/memory/index.jsonl b/.agents/memory/index.jsonl index 9a61e2ef4f..0d3919272b 100644 --- a/.agents/memory/index.jsonl +++ b/.agents/memory/index.jsonl @@ -2,3 +2,4 @@ {"name": "evaluation-registry", "description": "Catalog of all evaluation metrics with detailed explanations, implementation status, and usage guides", "path": "evaluation-registry/README.md", "status": "draft", "trust": "medium"} {"name": "experiment-journal", "description": "Living log of all experiments with hypotheses, configs, metrics, and insights", "path": "experiment-journal/README.md", "status": "draft", "trust": "medium"} {"name": "related-work", "description": "Index of related papers, repos, and blog posts with structured comparisons to FastVideo", "path": "related-work/README.md", "status": "draft", "trust": "low"} +{"name": "dreamverse-integration", "description": "Consolidated knowledge base for the FastVideo public API refactor (PRs 0-17), LTX-2 streaming server upstream, Dreamverse migration from FastVideo-internal, and NVFP4 quantization landing", "path": "dreamverse-integration/README.md", "status": "ready", "trust": "high"} diff --git a/.agents/skills/dreamverse-deploy/SKILL.md b/.agents/skills/dreamverse-deploy/SKILL.md new file mode 100644 index 0000000000..7c15e49821 --- /dev/null +++ b/.agents/skills/dreamverse-deploy/SKILL.md @@ -0,0 +1,185 @@ +# dreamverse-deploy — redeploy migrated Dreamverse on a chosen GPU + +**Scope:** project (lives in this repo at `.agents/skills/dreamverse-deploy/`) + +**When to use:** you want to (re)launch the migrated `apps/dreamverse/` backend ++ frontend on this dev node, pinned to a specific physical GPU. Tears down +any existing deploy on the same ports first, then boots fresh and waits for +both `/readyz` and the FE root to return 200. + +**Pairs with:** [`integration-plan.md`](../../memory/dreamverse-integration/integration-plan.md) +"Local GPU4 verification hook" + [`decisions-log.md D-19`](../../memory/dreamverse-integration/decisions-log.md#d-19). + +## Prerequisites + +- Working tree on a branch that has `apps/dreamverse/` (e.g. `will/dreamverse-monorepo`) +- Local conda env at `~/miniconda3/envs/fv-main/` with `flashinfer-python`, + `cerebras-cloud-sdk`, `openai` installed (override the default path with + `DREAMVERSE_PYTHON=/path/to/python`) +- `~/.env` exporting `CEREBRAS_API_KEY`, `GROQ_API_KEY`, etc. +- pnpm installed at `/home/william5lin/.local/share/pnpm/pnpm` (or in `$PATH`) +- `gcc-13` + `g++-13` at `/usr/bin/` (workaround for nvcc gcc-15 rejection) +- **Recommended:** native ffmpeg env file at `apps/dreamverse/scripts/ffmpeg-env.sh` + (built once via `bash apps/dreamverse/scripts/install_native_ffmpeg.sh`). + When present, the deploy sources it inside the backend setsid block so the + worker spawns ffmpeg from `$HOME/opt/ffmpeg-native/bin/ffmpeg` (LTO + libx264 + + native arch) instead of the system `/usr/bin/ffmpeg`. When missing, the + deploy falls back to system ffmpeg with a warning. Set + `DREAMVERSE_REQUIRE_NATIVE_FFMPEG=true` to make the missing env file a hard + failure. + +If any required prereq is missing, the script fails fast with a clear message. + +## Usage + +```bash +# Deploy on GPU 4 with default ports (backend 8009, FE 5274) — torch.compile +# and warmup are both OFF by default so first-segment cold start is ~45s +# instead of ~3-4min. +./.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh 4 + +# Deploy on GPU 6 with custom ports +./.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh 6 8089 5275 + +# Deploy on GPU 0 with warmup enabled +./.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh --warmup 0 + +# Deploy with torch.compile enabled (max-autotune; first segment ~3-4min, +# subsequent segments save ~3s — only worth it for benchmarking) +./.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh --torch-compile 4 + +# Deploy with both warmup AND torch.compile enabled +./.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh --warmup --torch-compile 4 + +# Flags can appear before, between, or after positional args +./.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh 4 8089 5275 --warmup +``` + +### Arguments + +| Position | Name | Default | Notes | +|---|---|---|---| +| 1 | `GPU` | (required) | Physical GPU index, e.g. `4` | +| 2 | `BACKEND_PORT` | `8009` | TCP port for the FastAPI server | +| 3 | `FRONTEND_PORT` | `5274` | TCP port for the Next.js dev server | + +### Flags + +| Flag | Default | Notes | +|---|---|---| +| `--warmup` / `--no-warmup` | off | Run GPU warmup at boot (~minutes). Overrides `DREAMVERSE_WARMUP` | +| `--torch-compile` / `--no-torch-compile` | off | Enable max-autotune `torch.compile`. First segment ~3-4min when on, ~45s when off. Overrides `DREAMVERSE_TORCH_COMPILE` | +| `--nvenc` / `--no-nvenc` | off | Use `h264_nvenc` hardware encoder instead of `libx264` software. Eliminates ~1100ms/segment of CPU encoding cost (raises realtime ratio from ~0.78x → ≥1.0x, eliminating inter-segment buffer-drain stutter). Requires native ffmpeg built with `--enable-nvenc` (the install script's default since the NVENC update). Hard-fails up-front if the binary is missing or lacks NVENC. Overrides `DREAMVERSE_NVENC` | +| `-h` / `--help` | — | Show usage | + +Flags can appear in any position relative to the positional args. Explicit flag values always win over env-var defaults. + +### Environment variables (used when no flag is given) + +| Var | Default | Purpose | +|---|---|---| +| `DREAMVERSE_WARMUP` | `false` | Same as `--warmup`/`--no-warmup`. Flag takes precedence | +| `DREAMVERSE_TORCH_COMPILE` | `false` | Same as `--torch-compile`/`--no-torch-compile`. Flag takes precedence | +| `DREAMVERSE_NVENC` | `false` | Same as `--nvenc`/`--no-nvenc`. Flag takes precedence | +| `DREAMVERSE_PYTHON` | `~/miniconda3/envs/fv-main/bin/python` | Conda env python used for prereq probes (flashinfer import). The wrapper at `apps/dreamverse/scripts/dreamverse-server` still resolves python via the `.venv` symlink, which points at the same interpreter on this dev node | +| `DREAMVERSE_REPO_ROOT` | git rev-parse | Repo root override | +| `DREAMVERSE_LOG_DIR` | `/tmp/opencode/dreamverse-deploy` | Where to write `backend.log` / `frontend.log` | +| `DREAMVERSE_REQUIRE_NATIVE_FFMPEG` | `false` | If `true`, fail when `$HOME/opt/ffmpeg-native/bin/ffmpeg` is absent | + +## What it does + +1. Validates prereqs. +2. Kills any process on the target backend/frontend ports + waits for the + target GPU to release memory (allows up to 30s for cleanup). +3. Sources `~/.env`. +4. Exports the env recipe required for boot: + - `CUDA_VISIBLE_DEVICES=` + - `FASTVIDEO_ENABLE_DEVTOOLS=1` + - `FASTVIDEO_ENABLE_STARTUP_WARMUP=` + - `FASTVIDEO_GPU_COUNT=1` + - `ENABLE_TORCH_COMPILE=<0|1 derived from DREAMVERSE_TORCH_COMPILE>` + - `CC=/usr/bin/gcc-13 CXX=/usr/bin/g++-13 CUDAHOSTCXX=/usr/bin/g++-13` + - `NVCC_PREPEND_FLAGS="-ccbin /usr/bin/gcc-13 -allow-unsupported-compiler"` + - `FASTVIDEO_FFMPEG_BIN=$HOME/opt/ffmpeg-native/bin/ffmpeg` + + `FASTVIDEO_VIDEO_CODEC=libx264` (when the native binary exists) +5. Launches the backend via `apps/dreamverse/scripts/dreamverse-server` in a + detached `setsid` session, captures PID. +6. Polls `/readyz` until 200 (max 5 min). +7. Launches the frontend via `pnpm run dev:devtools` in a detached session, + captures PID. +8. Polls FE `/` until 200 (max 60s). +9. Prints URLs, PIDs, and log paths. + +## What it does NOT do + +- Does not modify `~/.env` or the FastVideo `.venv`. +- Does not push code or commit anything. +- Does not run Playwright. Use the e2e wrapper separately: + ```bash + cd apps/dreamverse/web + PLAYWRIGHT_SKIP_WEBSERVER=1 BACKEND_URL=http://127.0.0.1:8009 \ + PLAYWRIGHT_BASE_URL=http://127.0.0.1:5274 \ + NEXT_PUBLIC_INCLUDE_DEVTOOLS=1 \ + pnpm exec playwright test + ``` + The fast suite (8 specs, ~5s) runs by default; the long-running + two-segment audio-continuation spec is gated behind + `PLAYWRIGHT_LONG_RUNNING=1` (see below). + +## Long-running e2e (paired with `--warmup --torch-compile`) + +[`apps/dreamverse/web/e2e/long-running-segments.spec.ts`](../../../apps/dreamverse/web/e2e/long-running-segments.spec.ts) +drives a real two-segment session through the FE, captures every WS +frame, and asserts segments 1 AND 2 both reach `media_segment_complete` +with at least one binary fMP4 chunk per segment — the canonical +regression guard against the D-20 BrokenPipe pattern documented in +[`decisions-log.md D-20`](../../memory/dreamverse-integration/decisions-log.md#d-20). +Skipped by default. Enable with: + +```bash +./.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh \ + --warmup --torch-compile 4 + +cd apps/dreamverse/web +PLAYWRIGHT_SKIP_WEBSERVER=1 \ + BACKEND_URL=http://127.0.0.1:8009 \ + PLAYWRIGHT_BASE_URL=http://127.0.0.1:5274 \ + NEXT_PUBLIC_INCLUDE_DEVTOOLS=1 \ + PLAYWRIGHT_LONG_RUNNING=1 \ + pnpm exec playwright test e2e/long-running-segments.spec.ts +``` + +Expected runtime: ~7-9 minutes on a B200 (torch.compile max-autotune +warm-up dominates the cold start; per-test timeout is 900s). The spec +hard-fails on any WS `error`/`step_error` frame so the BrokenPipe +regression surfaces with the actual ffmpeg/audio diagnostics rather +than an opaque "test timed out". + +## Teardown + +Stop both services without redeploying: + +```bash +# Stop services on default ports (port-pattern based) +./.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh --stop + +# Stop AND nuke any process holding GPU N +./.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh --stop 4 +``` + +The redeploy path (`` mode) automatically nukes any process holding the +target GPU before launching — including orphan `multiproc_executor` worker +subprocesses left over from a parent backend that was killed without grace. +This was the failure mode of an earlier naive port-only kill: parent dies, +children survive, GPU stays full, next deploy OOMs. + +## Notes + +- The wrapper at `apps/dreamverse/scripts/dreamverse-server` is what makes + the migrated `apps/dreamverse/server/main.py` run instead of the legacy + conda-installed Dreamverse — see [decisions-log.md D-19](../../memory/dreamverse-integration/decisions-log.md#d-19) for why + this matters. +- The B200 / sm_100a NVCC flags are mandatory on this dev node because the + conda toolchain ships gcc-15, which nvcc rejects. If you're on a machine + with a supported native gcc, those exports are still safe (no-op when the + paths don't exist; the script verifies them upfront). diff --git a/.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh b/.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh new file mode 100755 index 0000000000..665aaf7155 --- /dev/null +++ b/.agents/skills/dreamverse-deploy/scripts/dreamverse-deploy.sh @@ -0,0 +1,400 @@ +#!/usr/bin/env bash +# See ../SKILL.md for full usage. + +set -euo pipefail + +if [[ "${1:-}" == "--stop" ]]; then + for pat in 'apps/dreamverse/server/main.py' 'main.py --host 0.0.0.0 --port' 'next dev --port' 'next-server (v'; do + pkill -KILL -f "${pat}" 2>/dev/null || true + done + if [[ -n "${2:-}" ]] && [[ "${2}" =~ ^[0-9]+$ ]]; then + gpu_uuid="$(nvidia-smi --query-gpu=index,uuid --format=csv,noheader 2>/dev/null | awk -F', ' -v g="${2}" '$1==g {print $2}')" + if [[ -n "${gpu_uuid}" ]]; then + for pid in $(nvidia-smi --query-compute-apps=pid,gpu_uuid --format=csv,noheader 2>/dev/null \ + | awk -F', ' -v u="${gpu_uuid}" '$2==u {print $1}'); do + kill -9 "${pid}" 2>/dev/null || true + done + fi + fi + sleep 2 + echo "stopped: ports may take a few seconds to free" + exit 0 +fi + +# --------------------------------------------------------------------------- +# Args +# --------------------------------------------------------------------------- + +usage() { + cat < [BACKEND_PORT] [FRONTEND_PORT] + $(basename "$0") --stop [GPU] + +Positional: + GPU Physical GPU index (required), e.g. 4 + BACKEND_PORT default 8009 + FRONTEND_PORT default 5274 + +Flags (override env vars when both set): + --warmup / --no-warmup run GPU warmup at boot (default off) + --torch-compile / --no-torch-compile + enable max-autotune torch.compile + (default off — first segment ~3-4min + when on, ~45s when off) + --nvenc / --no-nvenc use h264_nvenc hardware encoder (default + off — uses libx264 software encoder). + Requires native ffmpeg built with NVENC. + -h, --help show this help + +Env overrides: + DREAMVERSE_WARMUP 'true'|'false' (default false) + DREAMVERSE_TORCH_COMPILE 'true'|'false' (default false) + DREAMVERSE_NVENC 'true'|'false' (default false) + DREAMVERSE_REPO_ROOT default: \$(git rev-parse --show-toplevel) + DREAMVERSE_LOG_DIR default: /tmp/opencode/dreamverse-deploy + DREAMVERSE_REQUIRE_NATIVE_FFMPEG 'true'|'false' (default false) +USAGE +} + +WARMUP_OVERRIDE="" +TORCH_COMPILE_OVERRIDE="" +NVENC_OVERRIDE="" +POSITIONAL=() +while [[ $# -gt 0 ]]; do + case "$1" in + -h|--help) usage; exit 0 ;; + --warmup) WARMUP_OVERRIDE=true; shift ;; + --no-warmup) WARMUP_OVERRIDE=false; shift ;; + --torch-compile) TORCH_COMPILE_OVERRIDE=true; shift ;; + --no-torch-compile) TORCH_COMPILE_OVERRIDE=false; shift ;; + --nvenc) NVENC_OVERRIDE=true; shift ;; + --no-nvenc) NVENC_OVERRIDE=false; shift ;; + --) shift; while [[ $# -gt 0 ]]; do POSITIONAL+=("$1"); shift; done ;; + -*) echo "error: unknown flag '$1'" >&2; usage >&2; exit 2 ;; + *) POSITIONAL+=("$1"); shift ;; + esac +done +set -- "${POSITIONAL[@]+"${POSITIONAL[@]}"}" + +if [[ $# -lt 1 ]]; then + usage >&2 + exit 2 +fi + +GPU="${1}" +BACKEND_PORT="${2:-8009}" +FRONTEND_PORT="${3:-5274}" + +if ! [[ "${GPU}" =~ ^[0-9]+$ ]]; then + echo "error: GPU must be a non-negative integer (got '${GPU}')" >&2 + exit 2 +fi + +WARMUP="${WARMUP_OVERRIDE:-${DREAMVERSE_WARMUP:-false}}" +case "${WARMUP}" in + true|false) ;; + *) echo "error: warmup must be 'true' or 'false' (got '${WARMUP}')" >&2; exit 2 ;; +esac + +TORCH_COMPILE="${TORCH_COMPILE_OVERRIDE:-${DREAMVERSE_TORCH_COMPILE:-false}}" +case "${TORCH_COMPILE}" in + true|false) ;; + *) echo "error: torch-compile must be 'true' or 'false' (got '${TORCH_COMPILE}')" >&2; exit 2 ;; +esac +TORCH_COMPILE_FLAG=$([[ "${TORCH_COMPILE}" == "true" ]] && echo 1 || echo 0) + +NVENC="${NVENC_OVERRIDE:-${DREAMVERSE_NVENC:-false}}" +case "${NVENC}" in + true|false) ;; + *) echo "error: nvenc must be 'true' or 'false' (got '${NVENC}')" >&2; exit 2 ;; +esac + +REPO_ROOT="${DREAMVERSE_REPO_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}" +LOG_DIR="${DREAMVERSE_LOG_DIR:-/tmp/opencode/dreamverse-deploy}" + +# --------------------------------------------------------------------------- +# Prereq checks +# --------------------------------------------------------------------------- + +bail() { echo "error: $*" >&2; exit 3; } + +[[ -d "${REPO_ROOT}/apps/dreamverse" ]] \ + || bail "REPO_ROOT '${REPO_ROOT}' does not contain apps/dreamverse/. Are you on a migration branch?" +[[ -x "${REPO_ROOT}/apps/dreamverse/scripts/dreamverse-server" ]] \ + || bail "wrapper script missing or not executable: apps/dreamverse/scripts/dreamverse-server" + +CONDA_ENV_PYTHON="${DREAMVERSE_PYTHON:-${HOME}/miniconda3/envs/fv-main/bin/python}" +[[ -x "${CONDA_ENV_PYTHON}" ]] \ + || bail "conda env python missing at ${CONDA_ENV_PYTHON} (set DREAMVERSE_PYTHON to override)" +"${CONDA_ENV_PYTHON}" -c 'import flashinfer' 2>/dev/null \ + || bail "flashinfer-python not installed in ${CONDA_ENV_PYTHON} (run: ${CONDA_ENV_PYTHON} -m pip install flashinfer-python --no-build-isolation)" + +PNPM="${PNPM:-/home/william5lin/.local/share/pnpm/pnpm}" +command -v "${PNPM}" >/dev/null 2>&1 || PNPM="$(command -v pnpm 2>/dev/null || true)" +[[ -n "${PNPM}" ]] && [[ -x "${PNPM}" ]] || bail "pnpm not found in PATH or at /home/william5lin/.local/share/pnpm/pnpm" + +GCC13=/usr/bin/gcc-13 +GPP13=/usr/bin/g++-13 +[[ -x "${GCC13}" ]] || bail "${GCC13} not executable (needed for nvcc workaround)" +[[ -x "${GPP13}" ]] || bail "${GPP13} not executable (needed for nvcc workaround)" + +[[ -f "${HOME}/.env" ]] || echo "warn: ${HOME}/.env missing — provider API keys may be unset" >&2 + +NATIVE_FFMPEG_BIN="${HOME}/opt/ffmpeg-native/bin/ffmpeg" +if [[ "${NVENC}" == "true" ]]; then + NATIVE_VIDEO_CODEC=h264_nvenc +else + NATIVE_VIDEO_CODEC=libx264 +fi +REQUIRE_NATIVE_FFMPEG="${DREAMVERSE_REQUIRE_NATIVE_FFMPEG:-false}" +case "${REQUIRE_NATIVE_FFMPEG}" in + true|false) ;; + *) bail "DREAMVERSE_REQUIRE_NATIVE_FFMPEG must be 'true' or 'false' (got '${REQUIRE_NATIVE_FFMPEG}')" ;; +esac +if [[ -x "${NATIVE_FFMPEG_BIN}" ]]; then + if [[ "${NVENC}" == "true" ]]; then + encoder_list="$("${NATIVE_FFMPEG_BIN}" -hide_banner -encoders 2>/dev/null || true)" + if [[ "${encoder_list}" != *h264_nvenc* ]]; then + bail "--nvenc requested but ${NATIVE_FFMPEG_BIN} was not built with NVENC. Rebuild: bash apps/dreamverse/scripts/install_native_ffmpeg.sh (with ENABLE_NVENC=1, the default)" + fi + if ! "${NATIVE_FFMPEG_BIN}" -hide_banner -loglevel error -y \ + -f lavfi -i 'color=red:size=64x64:rate=24:duration=0.2' \ + -c:v h264_nvenc -f null - >/dev/null 2>&1; then + bail "--nvenc requested but the GPU on this host has no NVENC silicon (probe failed: 'OpenEncodeSessionEx unsupported device'). Datacenter Blackwell (B200) and some H100 SKUs ship without NVENC; --nvenc only works on hosts with NVENC-capable GPUs (RTX 50-series, T4, A10, etc.)." + fi + fi + echo " native ffmpeg: ${NATIVE_FFMPEG_BIN} (codec=${NATIVE_VIDEO_CODEC})" +elif [[ "${REQUIRE_NATIVE_FFMPEG}" == "true" ]] || [[ "${NVENC}" == "true" ]]; then + bail "${NATIVE_FFMPEG_BIN} missing (required by --nvenc or DREAMVERSE_REQUIRE_NATIVE_FFMPEG=true). Run: bash apps/dreamverse/scripts/install_native_ffmpeg.sh" +else + echo "warn: ${NATIVE_FFMPEG_BIN} missing — backend will fall back to system ffmpeg (\$(command -v ffmpeg))." >&2 + echo " Build native ffmpeg with: bash apps/dreamverse/scripts/install_native_ffmpeg.sh" >&2 +fi +echo " python: ${CONDA_ENV_PYTHON}" + +mkdir -p "${LOG_DIR}" + +# --------------------------------------------------------------------------- +# Teardown anything on target ports +# --------------------------------------------------------------------------- + +echo "[1/8] killing any existing deploy on ports ${BACKEND_PORT}/${FRONTEND_PORT} and GPU ${GPU}..." + +kill_port_pid() { + local port="$1" + local pid + pid="$(ss -tlnp 2>/dev/null | grep -E ":${port}\b" | sed -nE 's/.*pid=([0-9]+).*/\1/p' | head -1 || true)" + if [[ -n "${pid}" ]]; then + kill -9 "${pid}" 2>/dev/null || true + fi +} + +for pat in "main.py --host 0.0.0.0 --port ${BACKEND_PORT}" "next dev --port ${FRONTEND_PORT}" "NEXT_PUBLIC_INCLUDE_DEVTOOLS=1 next dev --port ${FRONTEND_PORT}"; do + pkill -KILL -f "${pat}" 2>/dev/null || true +done +kill_port_pid "${BACKEND_PORT}" +kill_port_pid "${FRONTEND_PORT}" + +gpu_uuid="$(nvidia-smi --query-gpu=index,uuid --format=csv,noheader 2>/dev/null | awk -F', ' -v g="${GPU}" '$1==g {print $2}')" +if [[ -n "${gpu_uuid}" ]]; then + for pid in $(nvidia-smi --query-compute-apps=pid,gpu_uuid --format=csv,noheader 2>/dev/null \ + | awk -F', ' -v u="${gpu_uuid}" '$2==u {print $1}'); do + if [[ -n "${pid}" ]] && [[ "${pid}" != "$$" ]]; then + cmd="$(ps -p "${pid}" -o comm= 2>/dev/null || true)" + kill -9 "${pid}" 2>/dev/null && echo " killed GPU${GPU} pid=${pid} (${cmd:-?})" || true + fi + done +fi + +for i in $(seq 1 30); do + free_be=true + free_fe=true + ss -tln 2>/dev/null | grep -qE ":${BACKEND_PORT}\b" && free_be=false + ss -tln 2>/dev/null | grep -qE ":${FRONTEND_PORT}\b" && free_fe=false + gpu_mem="$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits 2>/dev/null | sed -n "$((GPU + 1))p" || echo 99999)" + if "${free_be}" && "${free_fe}" && [[ "${gpu_mem}" -lt 1000 ]]; then + break + fi + sleep 1 +done + +gpu_mem="$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits 2>/dev/null | sed -n "$((GPU + 1))p" || echo 0)" +echo " ports cleared; GPU${GPU} at ${gpu_mem} MiB" + +# --------------------------------------------------------------------------- +# Launch backend +# --------------------------------------------------------------------------- + +echo "[2/8] launching backend on GPU ${GPU} port ${BACKEND_PORT} (warmup=${WARMUP} torch_compile=${TORCH_COMPILE} nvenc=${NVENC})..." + +backend_log="${LOG_DIR}/backend-gpu${GPU}.log" +: > "${backend_log}" + +setsid bash -c " + set -a + if [[ -f \"${HOME}/.env\" ]]; then + source \"${HOME}/.env\" + fi + set +a + if [[ -x \"${NATIVE_FFMPEG_BIN}\" ]]; then + export FASTVIDEO_FFMPEG_BIN=\"${NATIVE_FFMPEG_BIN}\" + export FASTVIDEO_VIDEO_CODEC=\"${NATIVE_VIDEO_CODEC}\" + fi + export DREAMVERSE_PYTHON=\"${CONDA_ENV_PYTHON}\" + export CUDA_VISIBLE_DEVICES=${GPU} + export FASTVIDEO_ENABLE_DEVTOOLS=1 + export FASTVIDEO_ENABLE_STARTUP_WARMUP=${WARMUP} + export FASTVIDEO_GPU_COUNT=1 + export ENABLE_TORCH_COMPILE=${TORCH_COMPILE_FLAG} + export CC=${GCC13} + export CXX=${GPP13} + export CUDAHOSTCXX=${GPP13} + export NVCC_PREPEND_FLAGS=\"-ccbin ${GCC13} -allow-unsupported-compiler\" + cd \"${REPO_ROOT}\" + exec ./apps/dreamverse/scripts/dreamverse-server --host 0.0.0.0 --port ${BACKEND_PORT} +" > "${backend_log}" 2>&1 < /dev/null & +disown + +# Wait briefly, then resolve actual python PID (the inner process, not the +# wrapper bash). +sleep 4 +backend_pid="$(pgrep -f "main.py --host 0.0.0.0 --port ${BACKEND_PORT}" | head -1 || true)" + +if [[ -z "${backend_pid}" ]]; then + echo "error: backend failed to spawn. Last 30 lines of log:" >&2 + tail -30 "${backend_log}" >&2 + exit 4 +fi + +echo " backend pid=${backend_pid} log=${backend_log}" + +# Poll /readyz. Deadline scales with warmup + torch.compile flags +# because warmup runs two synthetic segments before /readyz=200, and +# torch.compile max-autotune adds ~3-4min cold start to the first +# segment. Empirical worst case (warmup=true, torch_compile=true): +# ~7 min on B200; we budget 15 min for safety. +if [[ "${WARMUP}" == "true" ]] && [[ "${TORCH_COMPILE}" == "true" ]]; then + READYZ_BUDGET_SECONDS=900 +elif [[ "${WARMUP}" == "true" ]] || [[ "${TORCH_COMPILE}" == "true" ]]; then + READYZ_BUDGET_SECONDS=480 +else + READYZ_BUDGET_SECONDS=300 +fi +READYZ_POLL_INTERVAL=6 +READYZ_MAX_ITERS=$(( READYZ_BUDGET_SECONDS / READYZ_POLL_INTERVAL )) + +echo "[3/8] polling http://127.0.0.1:${BACKEND_PORT}/readyz (budget=${READYZ_BUDGET_SECONDS}s) ..." +ready=0 +for i in $(seq 1 ${READYZ_MAX_ITERS}); do + code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 "http://127.0.0.1:${BACKEND_PORT}/readyz" 2>/dev/null || echo 000)" + if [[ "${code}" == "200" ]]; then + ready=1 + break + fi + if ! kill -0 "${backend_pid}" 2>/dev/null; then + echo "error: backend pid ${backend_pid} died. Last 50 lines:" >&2 + tail -50 "${backend_log}" >&2 + exit 5 + fi + sleep ${READYZ_POLL_INTERVAL} +done + +if [[ "${ready}" != "1" ]]; then + echo "error: backend did not become /readyz=200 within ${READYZ_BUDGET_SECONDS}s. Last 50 lines:" >&2 + tail -50 "${backend_log}" >&2 + exit 5 +fi + +echo "[4/8] backend /readyz OK" + +# --------------------------------------------------------------------------- +# Launch frontend +# --------------------------------------------------------------------------- + +echo "[5/8] launching frontend on port ${FRONTEND_PORT}..." + +frontend_log="${LOG_DIR}/frontend-port${FRONTEND_PORT}.log" +: > "${frontend_log}" + +# Resolve dev script: dev:devtools forces port 5274 + devtools env. If the +# requested port differs, run `next dev --port` directly with devtools env. +fe_cmd="run dev:devtools" +if [[ "${FRONTEND_PORT}" != "5274" ]]; then + fe_cmd="exec next dev --port ${FRONTEND_PORT}" +fi + +setsid bash -c " + cd \"${REPO_ROOT}/apps/dreamverse/web\" + export NEXT_PUBLIC_INCLUDE_DEVTOOLS=1 + export BACKEND_URL=http://127.0.0.1:${BACKEND_PORT} + export BACKEND_HOST=127.0.0.1 + export BACKEND_PORT=${BACKEND_PORT} + exec '${PNPM}' ${fe_cmd} +" > "${frontend_log}" 2>&1 < /dev/null & +disown + +sleep 4 +frontend_pid="$(pgrep -f "next dev --port ${FRONTEND_PORT}" | head -1 || true)" +if [[ -z "${frontend_pid}" ]]; then + echo "error: frontend failed to spawn. Last 30 lines:" >&2 + tail -30 "${frontend_log}" >&2 + exit 6 +fi + +echo " frontend pid=${frontend_pid} log=${frontend_log}" + +# Poll FE root +echo "[6/8] polling http://127.0.0.1:${FRONTEND_PORT}/ ..." +fe_ready=0 +for i in $(seq 1 30); do + code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 "http://127.0.0.1:${FRONTEND_PORT}/" 2>/dev/null || echo 000)" + if [[ "${code}" == "200" ]]; then + fe_ready=1 + break + fi + if ! kill -0 "${frontend_pid}" 2>/dev/null; then + echo "error: frontend pid ${frontend_pid} died. Last 30 lines:" >&2 + tail -30 "${frontend_log}" >&2 + exit 7 + fi + sleep 2 +done + +if [[ "${fe_ready}" != "1" ]]; then + echo "error: frontend did not respond 200 within 60s. Last 30 lines:" >&2 + tail -30 "${frontend_log}" >&2 + exit 7 +fi + +echo "[7/8] frontend / OK" + +# --------------------------------------------------------------------------- +# Print summary +# --------------------------------------------------------------------------- + +cwd="$(readlink "/proc/${backend_pid}/cwd" 2>/dev/null || echo unknown)" +gpu_mem_now="$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits 2>/dev/null | sed -n "$((GPU + 1))p" || echo 0)" +ffmpeg_in_use="$(tr '\0' '\n' < "/proc/${backend_pid}/environ" 2>/dev/null | sed -n 's/^FASTVIDEO_FFMPEG_BIN=//p' | head -1)" +[[ -z "${ffmpeg_in_use}" ]] && ffmpeg_in_use="$(command -v ffmpeg 2>/dev/null || echo '') (system fallback)" + +cat <.md`: - -```markdown ---- -title: -source: <URL or citation> -type: paper | repo | blog -date_indexed: <ISO-8601> -tags: [world-model, distillation, evaluation, ...] ---- - -## Summary -<1-2 paragraph summary.> - -## Key Differences from FastVideo -- <comparison points> - -## Actionable Insights -- <what we could adopt or adapt> -``` - -### 3. Update the catalog - -If `.agents/memory/related-work/_catalog.md` exists, append the new entry. -If not, create it: - -```markdown -# Related Work Catalog - -| Slug | Title | Type | Tags | Date | -|------|-------|------|------|------| -| <slug> | <title> | <type> | <tags> | <date> | -``` - -## Outputs -- New file in `.agents/memory/related-work/<slug>.md`. -- Updated catalog. - -## Example Usage - -``` -Index the Self-Forcing paper: - - source: https://arxiv.org/abs/2406.xxxxx - type: paper - tags: [world-model, self-forcing, distillation] -``` - -## References -- `.agents/memory/related-work/README.md` — schema documentation - -## Changelog -| Date | Change | -|------|--------| -| 2026-03-02 | Initial version | diff --git a/.agents/skills/index.jsonl b/.agents/skills/index.jsonl index 8b84d134ed..9bfb8cebb0 100644 --- a/.agents/skills/index.jsonl +++ b/.agents/skills/index.jsonl @@ -3,8 +3,6 @@ {"name": "summarize-run", "description": "Extract a W&B run summary into a structured experiment report", "path": "summarize-run/SKILL.md", "status": "draft", "trust": "low"} {"name": "log-experiment", "description": "Append or update an experiment entry in the experiment journal", "path": "log-experiment/SKILL.md", "status": "draft", "trust": "low"} {"name": "evaluate-video-quality", "description": "Evaluate generated video quality using available metrics (SSIM, loss trajectory, caption consistency)", "path": "evaluate-video-quality/SKILL.md", "status": "draft", "trust": "low"} -{"name": "index-related-work", "description": "Ingest a paper or repository into the related work index", "path": "index-related-work/SKILL.md", "status": "draft", "trust": "low"} -{"name": "search-related-work", "description": "Query the related work index for relevant papers, repos, or comparisons", "path": "search-related-work/SKILL.md", "status": "draft", "trust": "low"} {"name": "seed-ssim-references", "description": "Run a new or updated fastvideo/tests/ssim/ test on Modal, pull generated videos, and upload them to FastVideo/ssim-reference-videos so the test has a regression baseline", "path": "seed-ssim-references/SKILL.md", "status": "draft", "trust": "low"} {"name": "reseed-ssim-references", "description": "Re-seed (overwrite) HF reference videos for an existing fastvideo/tests/ssim/ test and a single model id on Modal L40S. Always backs up current refs first, regenerates on Modal, pauses for the user to eyeball before-vs-after, then uploads with --force scoped to --model-id. Sister skill to seed-ssim-references; use when intentional code change has invalidated existing refs", "path": "reseed-ssim-references/SKILL.md", "status": "draft", "trust": "low"} {"name": "decompose-pipeline-pr", "description": "Decompose an oversized FastVideo pipeline PR into a stack of independently-reviewable PRs. Tiers the diff by blast radius (invisible / dead code / cross-cutting infra / activation), produces a branch graph and worktree bootstrap, drafts the AGENTS.md manifest, flags missing tests on cross-cutting infra changes, and extracts lessons from the PR body. Worked example: PR #1280 daVinci-MagiHuman (9.8k LOC) decomposed into 10 stacked PRs.", "path": "decompose-pipeline-pr/SKILL.md", "status": "tested", "trust": "medium"} diff --git a/.agents/skills/search-related-work/SKILL.md b/.agents/skills/search-related-work/SKILL.md deleted file mode 100644 index 49ecaf9dc8..0000000000 --- a/.agents/skills/search-related-work/SKILL.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -name: search-related-work -description: Query the related work index for relevant papers, repos, or comparisons ---- - -# Search Related Work - -## Purpose -Search through `.agents/memory/related-work/` to find indexed papers, repos, -or blog posts relevant to a query. Use this when you need to understand how -other work compares to FastVideo's approach, or when looking for techniques -to adopt. - -## Prerequisites -- The related work index has entries (`.agents/memory/related-work/*.md`). - -## Inputs - -| Parameter | Required | Description | -|-----------|----------|-------------| -| `query` | Yes | Natural language query | -| `tags` | No | Filter by tags (e.g., `[distillation, evaluation]`) | -| `type` | No | Filter by type (`paper`, `repo`, `blog`) | - -## Steps - -### 1. Search the index - -Use grep-based search through `.agents/memory/related-work/`: - -```bash -# Search by content -grep -rl "<query>" .agents/memory/related-work/ - -# Search by tags (in frontmatter) -grep -l "tags:.*<tag>" .agents/memory/related-work/*.md -``` - -### 2. Rank results - -For each matching file: -1. Read the file. -2. Score relevance to the query based on: - - Title match - - Tag match - - Content match (summary, differences, insights) -3. Return top results. - -### 3. Format output - -```markdown -## Related Work Search: "<query>" - -### 1. <Title> (relevance: high) -- **Source**: <URL> -- **Tags**: <tags> -- **Key insight**: <most relevant excerpt> -- **File**: `.agents/memory/related-work/<slug>.md` - -### 2. <Title> (relevance: medium) -... -``` - -## Outputs -- Ranked list of relevant related work entries with excerpts. - -## Example Usage - -``` -Search for work related to video quality evaluation metrics: - - query: "video generation quality evaluation metrics" - tags: [evaluation] -``` - -## References -- `.agents/memory/related-work/README.md` — index schema - -## Changelog -| Date | Change | -|------|--------| -| 2026-03-02 | Initial version | diff --git a/.agents/workflows/sync-dashboard.md b/.agents/workflows/sync-dashboard.md deleted file mode 100644 index 4ec13a2548..0000000000 --- a/.agents/workflows/sync-dashboard.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -description: Synchronize the STATUS.md dashboard by scanning .agents/ directories ---- - -# Sync Dashboard - -Updates `.agents/STATUS.md` by scanning the skills, workflows, memory, lessons, -and exploration directories to reflect what actually exists on disk. - -## When to Use - -- After adding, removing, or renaming any file in `.agents/`. -- Periodically (e.g., at end of each conversation session). -- When the dashboard feels out of date. - -## Steps - -### 1. Scan directories - -List all files in each directory: - -```bash -echo "=== Skills ===" -ls -1 .agents/skills/*.md 2>/dev/null | grep -v SKILL_TEMPLATE - -echo "=== Workflows ===" -ls -1 .agents/workflows/*.md 2>/dev/null - -echo "=== Memory ===" -ls -1 .agents/memory/*.md 2>/dev/null -ls -1 .agents/memory/related-work/*.md 2>/dev/null | grep -v README - -echo "=== Lessons ===" -ls -1 .agents/lessons/*.md 2>/dev/null | grep -v README - -echo "=== Exploration ===" -ls -1 .agents/exploration/*.md 2>/dev/null | grep -v README -``` - -### 2. Compare with STATUS.md - -For each file found: -- If it's in STATUS.md → leave it (preserve status/trust/tested fields). -- If it's NOT in STATUS.md → add it with status `🔴 Stub`, trust `None`, tested `❌`. - -For each entry in STATUS.md: -- If the file no longer exists → mark it as `❌ Removed` or delete the row. - -### 3. Update counts - -Recalculate the summary table at the top: -- Count files per category. -- Count by status (Ready, Draft, Stub). - -### 4. Update timestamp - -Set `_Last synced: <current date>_` at the top of STATUS.md. - -### 5. Review - -Read through the updated STATUS.md for accuracy. Flag anything that looks wrong. - -## Notes - -- Do NOT change trust levels during sync — those are set manually after testing. -- Do NOT change status during sync — status changes require actual validation. -- This workflow only handles structural sync (file existence), not content review. diff --git a/.gitignore b/.gitignore index 222c3c3a88..9f69c89a21 100644 --- a/.gitignore +++ b/.gitignore @@ -87,6 +87,42 @@ preprocess_output_text/ # Next.js / Node artifacts under ui/: see ui/.gitignore +# Next.js / Node artifacts under apps/dreamverse/web/ +apps/dreamverse/web/node_modules/ +apps/dreamverse/web/.next/ +apps/dreamverse/web/out/ +apps/dreamverse/web/coverage/ +apps/dreamverse/web/test-results/ +apps/dreamverse/web/playwright-report/ +apps/dreamverse/web/.env.local +apps/dreamverse/web/.env.development.local +apps/dreamverse/web/.env.test.local + +# Generated by apps/dreamverse/scripts/install_native_ffmpeg.sh — host-specific +apps/dreamverse/scripts/ffmpeg-env.sh +apps/dreamverse/web/.env.production.local + +# Unignore migrated Dreamverse product assets — root .gitignore globally +# ignores *.png/*.jpg/*.mp4/*.gif, but apps/dreamverse/web/public/ MUST +# be tracked (logo, icons, k2.png, etc.). +!apps/dreamverse/web/public/**/*.png +!apps/dreamverse/web/public/**/*.jpg +!apps/dreamverse/web/public/**/*.jpeg +!apps/dreamverse/web/public/**/*.mp4 +!apps/dreamverse/web/public/**/*.gif +!apps/dreamverse/web/prompts/**/*.png +!apps/dreamverse/web/prompts/**/*.jpg +!apps/dreamverse/web/prompts/**/*.jpeg +!apps/dreamverse/web/prompts/**/*.mp4 +!apps/dreamverse/web/prompts/**/*.gif +!apps/dreamverse/server/prompts/**/*.png +!apps/dreamverse/server/prompts/**/*.jpg +!apps/dreamverse/server/prompts/**/*.jpeg +!apps/dreamverse/server/prompts/**/*.mp4 +!apps/dreamverse/server/prompts/**/*.gif +!apps/dreamverse/gpu-pool.svg +!apps/dreamverse/gpu-pool.drawio + .claude/ .codex/ .sisyphus/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 36e742a417..91b47edd95 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,6 +10,7 @@ exclude: | scripts/.*| fastvideo/dataset/.*| fastvideo/models/.*| + ^apps/dreamverse/web/.*| examples/.*| \.agents/.*| .github/workflows/publish-fastvideo.yml| diff --git a/CLEANUP.md b/CLEANUP.md new file mode 100644 index 0000000000..94194e2d08 --- /dev/null +++ b/CLEANUP.md @@ -0,0 +1,182 @@ +# `.agents/` Cleanup Log — Phase 1 (Deletes Only) + +**Status:** TEMPORARY — delete this file after the cleanup is reviewed/committed. +**Date:** 2026-05-04 +**Branch:** `will/ltx2_sr_port` +**Scope:** Phase 1 of the `.agents/` cleanup plan (deletes only; no rewrites or additions). + +For the full multi-phase plan, see the prior session analysis. This file tracks +exactly what got deleted, why, and what cross-references still point at deleted +content (to fix in a future phase). + +--- + +## Deletions executed + +### Files deleted + +| Path | Size | Reason | +|---|---|---| +| `.agents/STATUS.md` | 3.85 KB | Stale dashboard, last synced 2026-03-02. Counts wrong (claimed 8 skills/4 workflows/4 memory; actual 9/5/5). References old snake_case filenames (`codebase_map.md`/`experiment_journal.md`) that don't exist. Hand-maintained derivative of `.agents/{memory,skills}/index.jsonl` — strictly redundant. | +| `.agents/exploration/pr-link-review.md` | 1.11 KB | Status: "promoted" to `.agents/skills/review-pr-link/`. Per `.agents/exploration/README.md` lifecycle, promoted exploration logs should not linger after the skill exists. | +| `.agents/workflows/sync-dashboard.md` | 1.87 KB | SOP for maintaining `STATUS.md` (which is also deleted). Contained obsolete file paths (`.agents/skills/launch-experiment.md` flat layout vs. actual `<skill>/SKILL.md` per-dir layout). Has never been run successfully (judging by stale dates everywhere). | + +### Skill directories deleted + +| Path | Size | Reason | +|---|---|---| +| `.agents/skills/index-related-work/` | 2.18 KB | Vapor-skill operating on the empty `.agents/memory/related-work/` registry. Never used (the registry has zero entries despite ~6 weeks since skill creation). Re-add when the related-work catalog gains entries. | +| `.agents/skills/search-related-work/` | 1.91 KB | Same: vapor-skill against empty registry. The skill description literally requires "The related work index has entries" as a prerequisite, and there are none. | + +**Total deleted: 5 items, ~10.9 KB.** + +### Registry updates + +| File | Change | +|---|---| +| `.agents/skills/index.jsonl` | Removed entries for `index-related-work` and `search-related-work`. Was 9 entries; now 7. | + +### Symlink hygiene + +`.agents/scripts/sync-skills.sh` was run to prune now-stale symlinks under +`.claude/skills/` that pointed at the deleted skill directories. Output captured +in the run log. + +--- + +## What was KEPT (despite being candidates) + +| Path | Why kept | +|---|---| +| `.agents/scripts/sync-skills.sh` | User explicitly requested keep. **Verified**: this script is INDEPENDENT of STATUS.md / sync-dashboard.md. It mirrors `.agents/skills/` → `.claude/skills/` via symlinks for Claude Code skill discovery. Self-contained, useful, prunes its own stale symlinks. | +| `.agents/memory/related-work/README.md` | Empty placeholder, but the schema/template is reusable. Kept for when first related-work entry is added. | +| `.agents/memory/experiment-journal/README.md` | Same: empty placeholder with template; kept for when journaling begins. | +| `.agents/lessons/README.md` | Same: empty placeholder, reusable schema. | +| `.agents/exploration/README.md` | Active template for new exploration logs. Kept. | + +--- + +## Remaining broken cross-references (FOLLOW-UP NEEDED) + +These files still reference deleted content. **NOT fixed in Phase 1** — track for +the next pass (Phase 2: rewrites/dedupe). + +### References to deleted `STATUS.md` + +| Referencing file | Action needed | +|---|---| +| `.agents/onboarding/README.md` | Quick-reference tree (line ~65) lists `STATUS.md ← dashboard: completeness & trust of all components`. Remove that line + the `ONBOARDING.md` typo (file is `README.md`). | + +### References to deleted `pr-link-review.md` + +| Referencing file | Action needed | +|---|---| +| `.agents/memory/dreamverse-integration/state.md` | "Untracked but present" / "Source docs (archived)" sections still mention `pr-link-review.md` as kept. Update to reflect deletion. | +| `.agents/memory/dreamverse-integration/README.md` | Same — table row for `pr-link-review.md` says "kept in exploration dir". Update or remove the row. | + +### References to deleted skills (`index-related-work`, `search-related-work`) + +| Referencing file | Action needed | +|---|---| +| `.agents/memory/related-work/README.md` | Says "Use the `index-related-work` skill". Either remove that hint or note "skill removed; re-add when registry has entries". | +| `.agents/workflows/evaluation-development.md` | Step 1 says "Search `.agents/memory/related-work/` for existing evaluation approaches" — that's still valid (manual search). No change needed. | + +### References to deleted `sync-dashboard.md` + +| Referencing file | Action needed | +|---|---| +| `.agents/memory/evaluation-registry/README.md` | Doesn't reference sync-dashboard directly. No change. | +| `.agents/STATUS.md` | Already being deleted. | + +--- + +## Other registry inconsistencies discovered (NOT FIXED in Phase 1) + +While editing `.agents/skills/index.jsonl`, two skill directories were found +that exist on disk but **are not registered** in `index.jsonl`: + +| Skill dir | Status | Why missing from index | +|---|---|---| +| `.agents/skills/diagnose-ssim-failure/` | Untracked locally; NOT on `origin/main`. 12.3 KB SKILL.md + `scripts/compare_latent_pt.py`. Recent mtime (2026-05-01). | Created in a prior session but the registration step was skipped. | +| `.agents/skills/review-pr-link/` | Untracked locally; NOT on `origin/main`. 2.9 KB SKILL.md + `scripts/prepare_pr_review.py` + `agents/openai.yaml`. The promotion target of the deleted `pr-link-review.md` exploration log. | Skipped registration when promoted from exploration log. | + +Both skills are functional and exposed via `sync-skills.sh` symlinks (just verified in +`.claude/skills/`), but agents reading `index.jsonl` to discover skills will miss them. + +**Action for Phase 2**: Add entries to `.agents/skills/index.jsonl` for both, +likely with `trust: medium` since they have working scripts and recent use. + +--- + +## Skill registry parity check + +After Phase 1, `.agents/skills/` contains 9 directories but `index.jsonl` lists 7: + +| In `index.jsonl` | On disk | +|---|---| +| ✓ launch-experiment | ✓ launch-experiment/ | +| ✓ monitor-experiment | ✓ monitor-experiment/ | +| ✓ summarize-run | ✓ summarize-run/ | +| ✓ log-experiment | ✓ log-experiment/ | +| ✓ evaluate-video-quality | ✓ evaluate-video-quality/ | +| ✓ seed-ssim-references | ✓ seed-ssim-references/ | +| ✓ reseed-ssim-references | ✓ reseed-ssim-references/ | +| ❌ (missing) | ⚠ diagnose-ssim-failure/ | +| ❌ (missing) | ⚠ review-pr-link/ | + +`.claude/skills/` symlinks (the runtime-discoverable surface) include all 9 ✓. + +--- + +## Phase 2+ items (NOT executed in this session) + +For future cleanup sessions, the prior plan identified: + +**Phase 2 (rewrites)**: +- Rewrite `.agents/onboarding/worldmodel-training/README.md` to drop ~50% structural duplication with `codebase-map/README.md` +- Refresh `.agents/memory/codebase-map/README.md` (last updated 2026-03-08; missing `fastvideo/api/`, `fastvideo/entrypoints/streaming/`, etc.) +- Refresh `.agents/memory/evaluation-registry/README.md` (last updated 2026-03-02; references old `evaluation_registry.md` filename) +- Merge `.agents/workflows/experiment-journaling.md` into `experiment-lifecycle.md` (one SOP per workflow) +- Fix the broken cross-references listed above + +**Phase 3 (additions)**: +- `fastvideo/api/AGENTS.md` +- `fastvideo/entrypoints/AGENTS.md` +- `tests/AGENTS.md` (top-level, distinct from `fastvideo/tests/AGENTS.md`) +- `fastvideo/distributed/AGENTS.md` +- `examples/AGENTS.md` +- `docs/AGENTS.md` +- `benchmarks/AGENTS.md` + +**Phase 4 (registry)**: +- Add `.agents/workflows/index.jsonl` +- Standardize all three index.jsonl schemas + +**Phase 5 (skills quality)**: +- Promote tested skills (`seed-ssim-references`, `reseed-ssim-references`, `diagnose-ssim-failure`, `review-pr-link`) from `trust: low` to `trust: medium` +- Mark untested skills (`launch-experiment`, `monitor-experiment`, `summarize-run`, `log-experiment`, `evaluate-video-quality`) explicitly with their gating prerequisite (e.g. "operates on empty registry") + +--- + +## Recovery + +All deletions are local (`will/ltx2_sr_port`, not committed). To restore any +deleted file: + +```bash +git restore --source=HEAD .agents/STATUS.md +git restore --source=HEAD .agents/exploration/pr-link-review.md +git restore --source=HEAD .agents/workflows/sync-dashboard.md +git restore --source=HEAD .agents/skills/index-related-work/SKILL.md +git restore --source=HEAD .agents/skills/search-related-work/SKILL.md +``` + +--- + +## When to delete THIS file + +Once: +1. The Phase 1 deletions are committed (or merged), AND +2. Phase 2 (broken cross-reference cleanup) is also committed, + +remove this file. Its purpose is transient bookkeeping for a multi-phase cleanup. diff --git a/CO-AUTHORS.md b/CO-AUTHORS.md new file mode 100644 index 0000000000..d25a1d76d1 --- /dev/null +++ b/CO-AUTHORS.md @@ -0,0 +1,88 @@ +# Co-Authors — `will/ltx2_sr_port` Stack + +**Status:** PERMANENT — keep around as the source of truth for who collaborated on this work, even after the stack merges. +**Last updated:** 2026-05-04 + +This file documents the human co-authors credited on every commit in the +`will/ltx2_sr_port` stack and its 10 split PRs. The 4 collaborators below +worked on the FastVideo-internal precursor of this code (LTX-2 streaming +server, NVFP4 wire-up, GPU pool, prompt enhancer, etc.) and are credited as +co-authors on the public-side upstream commits via Git's standard +[`Co-authored-by`](https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors) +trailer convention. + +The trailers are added to every commit on `will/ltx2_sr_port` (see +[`STACK.md`](STACK.md)), which means GitHub will: + +- Show the 4 co-authors on every commit detail page +- Show them on the merge commit / squash commit summary +- Display their avatars in the PR's "Contributors" sidebar +- Surface them in [`/contributors`](https://github.com/hao-ai-lab/FastVideo/contributors) once the stack lands + +## Co-author roster + +| GitHub user | Real name | GitHub ID | Trailer email | +|---|---|---|---| +| [`@Davids048`](https://github.com/Davids048) | Junda (David) Su | 90978028 | `90978028+Davids048@users.noreply.github.com` | +| [`@RandNMR73`](https://github.com/RandNMR73) | Matthew Noto | 99706358 | `99706358+RandNMR73@users.noreply.github.com` | +| [`@XOR-op`](https://github.com/XOR-op) | (unset) | 17672363 | `17672363+XOR-op@users.noreply.github.com` | +| [`@jzhang38`](https://github.com/jzhang38) | Zhang Peiyuan | 42993249 | `42993249+jzhang38@users.noreply.github.com` | + +## Why no-reply emails + +GitHub's `<id>+<username>@users.noreply.github.com` form is the most reliable +way to link a `Co-authored-by` trailer to a GitHub account. It: + +- Always works regardless of whether the user has a public verified email +- Survives the user changing their primary email +- Doesn't expose anyone's personal email to git history +- Is the format GitHub itself produces when you click "Add co-author" in the + web UI + +(All 4 collaborators have this email already used in `FastVideo-internal` +git history, verified via `git log --all` on that repo.) + +## Trailer block (copy-paste ready) + +The trailers added to every commit on `will/ltx2_sr_port`: + +``` +Co-authored-by: Junda (David) Su <90978028+Davids048@users.noreply.github.com> +Co-authored-by: Matthew Noto <99706358+RandNMR73@users.noreply.github.com> +Co-authored-by: XOR-op <17672363+XOR-op@users.noreply.github.com> +Co-authored-by: Zhang Peiyuan <42993249+jzhang38@users.noreply.github.com> +``` + +## How the trailers were applied + +```bash +git rebase --exec ' + git commit --amend --no-edit \ + --trailer "Co-authored-by: Junda (David) Su <90978028+Davids048@users.noreply.github.com>" \ + --trailer "Co-authored-by: Matthew Noto <99706358+RandNMR73@users.noreply.github.com>" \ + --trailer "Co-authored-by: XOR-op <17672363+XOR-op@users.noreply.github.com>" \ + --trailer "Co-authored-by: Zhang Peiyuan <42993249+jzhang38@users.noreply.github.com>" +' origin/main will/ltx2_sr_port +``` + +Git's `--trailer` flag is idempotent (it dedupes by the full `key: value` +string), so re-running the rebase is safe and won't add duplicates. + +## How to add a new co-author later + +1. Add the user to the roster table above. +2. Append their `Co-authored-by` line to the trailer block. +3. Re-run the rebase command above on `will/ltx2_sr_port` — git's + trailer dedupe handles the existing 4; the new one gets appended. +4. Re-slice all 10 split branches per [`STACK.md`](STACK.md). +5. Force-push `will/api_7.6`, `will/api_7.7`, and `will/ltx2_sr_port`. + +## What we do NOT add + +Per [`AGENTS.md`](AGENTS.md): + +> Never add any coding agent or models such as Claude (or Claude Code), GPT, +> Codex or others as a co-author in commits or PRs. + +So no `Co-authored-by: Claude <noreply@anthropic.com>` or similar. Only +human collaborators. diff --git a/fastvideo/attention/backends/bsa_attn.py b/fastvideo/attention/backends/bsa_attn.py index be804f3e52..ddacdb303e 100644 --- a/fastvideo/attention/backends/bsa_attn.py +++ b/fastvideo/attention/backends/bsa_attn.py @@ -358,12 +358,14 @@ def _flash_attn_single_mask( flat_k = torch.cat(k_list, dim=0) flat_v = torch.cat(v_list, dim=0) + # Compute max_seqlen_k from the Python list before moving to GPU to + # avoid a `.item()` round-trip that would force a host/device sync. + max_seqlen_q = Sq + max_seqlen_k = max(b - a for a, b in zip(cu_seqlens_k[:-1], cu_seqlens_k[1:], strict=False)) + cu_seqlens_q_t = torch.tensor(cu_seqlens_q, dtype=torch.int32, device=device) cu_seqlens_k_t = torch.tensor(cu_seqlens_k, dtype=torch.int32, device=device) - max_seqlen_q = Sq - max_seqlen_k = int((cu_seqlens_k_t[1:] - cu_seqlens_k_t[:-1]).max().item()) - orig_dtype = flat_q.dtype compute_dtype = orig_dtype if compute_dtype not in (torch.float16, torch.bfloat16): @@ -445,12 +447,14 @@ def _flash_attn_single_head( flat_k = torch.cat(k_list, dim=0) flat_v = torch.cat(v_list, dim=0) + # Compute max_seqlen_k from the Python list before moving to GPU to + # avoid a `.item()` round-trip that would force a host/device sync. + max_seqlen_q = Sq + max_seqlen_k = max(b - a for a, b in zip(cu_seqlens_k[:-1], cu_seqlens_k[1:], strict=False)) + cu_seqlens_q_t = torch.tensor(cu_seqlens_q, dtype=torch.int32, device=device) cu_seqlens_k_t = torch.tensor(cu_seqlens_k, dtype=torch.int32, device=device) - max_seqlen_q = Sq - max_seqlen_k = int((cu_seqlens_k_t[1:] - cu_seqlens_k_t[:-1]).max().item()) - orig_dtype = flat_q.dtype compute_dtype = orig_dtype if compute_dtype not in (torch.float16, torch.bfloat16): diff --git a/fastvideo/attention/backends/flash_attn.py b/fastvideo/attention/backends/flash_attn.py index 80f3571b3a..3ca5c047ba 100644 --- a/fastvideo/attention/backends/flash_attn.py +++ b/fastvideo/attention/backends/flash_attn.py @@ -57,6 +57,24 @@ def get_builder_cls() -> type["AttentionMetadataBuilder"]: raise NotImplementedError +def _key_padding_mask_from_attn_mask(attn_mask: torch.Tensor, key_len: int) -> torch.Tensor: + # Normalize attn_mask to [B, key_len] where True means valid token. + if attn_mask.dim() == 4: + attn_mask = attn_mask[:, 0, 0, :] + elif attn_mask.dim() == 3: + attn_mask = attn_mask[:, 0, :] + elif attn_mask.dim() != 2: + raise ValueError(f"Unsupported attn_mask shape for FLASH_ATTN: {attn_mask.shape}") + + # SDPA additive mask convention: valid=0, masked=-inf/large negative. + key_padding_mask = attn_mask if attn_mask.dtype == torch.bool else attn_mask >= 0 + + if key_padding_mask.shape[-1] != key_len: + raise ValueError("Invalid key padding mask length for FLASH_ATTN: " + f"expected {key_len}, got {key_padding_mask.shape[-1]}") + return key_padding_mask + + @dataclass class FlashAttnMetadata(AttentionMetadata): current_timestep: int @@ -101,24 +119,6 @@ def forward( value: torch.Tensor, attn_metadata: FlashAttnMetadata, ): - - def _key_padding_mask_from_attn_mask(attn_mask: torch.Tensor, key_len: int) -> torch.Tensor: - # Normalize attn_mask to [B, key_len] where True means valid token. - if attn_mask.dim() == 4: - attn_mask = attn_mask[:, 0, 0, :] - elif attn_mask.dim() == 3: - attn_mask = attn_mask[:, 0, :] - elif attn_mask.dim() != 2: - raise ValueError(f"Unsupported attn_mask shape for FLASH_ATTN: {attn_mask.shape}") - - # SDPA additive mask convention: valid=0, masked=-inf/large negative. - key_padding_mask = attn_mask if attn_mask.dtype == torch.bool else attn_mask >= 0 - - if key_padding_mask.shape[-1] != key_len: - raise ValueError("Invalid key padding mask length for FLASH_ATTN: " - f"expected {key_len}, got {key_padding_mask.shape[-1]}") - return key_padding_mask - if (attn_metadata is not None and hasattr(attn_metadata, "attn_mask") and attn_metadata.attn_mask is not None): from fastvideo.attention.utils.flash_attn_no_pad import ( flash_attn_no_pad, @@ -136,6 +136,7 @@ def _key_padding_mask_from_attn_mask(attn_mask: torch.Tensor, key_len: int) -> t device=query.device, ) key_padding_mask = _key_padding_mask_from_attn_mask(attn_mask, key.shape[1]).to(device=key.device) + return flash_attn_varlen_qk_no_pad( query, key, @@ -148,9 +149,8 @@ def _key_padding_mask_from_attn_mask(attn_mask: torch.Tensor, key_len: int) -> t ) qkv = torch.stack([query, key, value], dim=2) - - attn_mask = F.pad(attn_mask, (qkv.shape[1] - attn_mask.shape[1], 0), value=True) - output = flash_attn_no_pad(qkv, attn_mask, causal=False, dropout_p=0, softmax_scale=None) + attn_mask_padded = F.pad(attn_mask, (qkv.shape[1] - attn_mask.shape[1], 0), value=True) + output = flash_attn_no_pad(qkv, attn_mask_padded, causal=False, dropout_p=0, softmax_scale=None) else: output = flash_attn_func( query, # type: ignore[no-untyped-call] diff --git a/fastvideo/attention/backends/sla.py b/fastvideo/attention/backends/sla.py index 59b232b3ad..efb3cf8820 100644 --- a/fastvideo/attention/backends/sla.py +++ b/fastvideo/attention/backends/sla.py @@ -307,9 +307,12 @@ def forward( # Sparse attention o_s = _attention.apply(q, k, v, sparse_map, lut, real_topk, self.BLKQ, self.BLKK) - # Linear attention with feature maps - q_linear = self.feature_map_q(q).contiguous().to(self.dtype) - k_linear = self.feature_map_k(k).contiguous().to(self.dtype) + # Linear attention with feature maps. Note: softmax / elu / relu + # are elementwise and preserve layout, so the inputs are already + # contiguous from the transpose-contiguous above — no need to + # call .contiguous() again here. + q_linear = self.feature_map_q(q).to(self.dtype) + k_linear = self.feature_map_k(k).to(self.dtype) o_l = self._calc_linear_attention(q_linear, k_linear, v) # Project linear attention output and combine @@ -539,9 +542,10 @@ def forward( False, 1, scale, 0) # ========== END SPARGE ========== - # Linear attention with feature maps - q_linear = self.feature_map_q(q).contiguous().to(self.dtype) - k_linear = self.feature_map_k(k).contiguous().to(self.dtype) + # Linear attention with feature maps (see SLAAttentionImpl.forward + # for why .contiguous() is unnecessary here). + q_linear = self.feature_map_q(q).to(self.dtype) + k_linear = self.feature_map_k(k).to(self.dtype) o_l = self._calc_linear_attention(q_linear, k_linear, v) # Project linear attention output and combine diff --git a/fastvideo/attention/backends/video_sparse_attn.py b/fastvideo/attention/backends/video_sparse_attn.py index 43960a9401..3ab483222c 100644 --- a/fastvideo/attention/backends/video_sparse_attn.py +++ b/fastvideo/attention/backends/video_sparse_attn.py @@ -140,6 +140,18 @@ class VideoSparseAttentionMetadata(AttentionMetadata): reverse_tile_partition_indices: torch.LongTensor variable_block_sizes: torch.LongTensor non_pad_index: torch.LongTensor + # Precomputed fancy index that fuses ``x[:, non_pad_index][:, reverse_tile_partition_indices]`` + # in postprocess_output(). Avoids materializing the intermediate + # ``[B, len(non_pad_index), H, D]`` tensor on every layer. + untile_combined_index: torch.LongTensor + # Per-step shared padded buffer used by tile(). Lazily populated on + # the first layer's call and reused by every subsequent VSA layer in + # the same denoising step. Scoping to metadata (not class/instance) + # makes the reuse thread-safe across concurrent requests and keeps + # the "pad positions are zero" invariant trivially true (the buffer + # is freshly zeroed alongside ``non_pad_index`` so the index set + # cannot drift between calls). + tile_buf: torch.Tensor | None = None class VideoSparseAttentionMetadataBuilder(AttentionMetadataBuilder): @@ -171,6 +183,7 @@ def build( # type: ignore reverse_tile_partition_indices = get_reverse_tile_partition_indices(dit_seq_shape, VSA_TILE_SIZE, device) variable_block_sizes = construct_variable_block_sizes(dit_seq_shape, num_tiles, device) non_pad_index = get_non_pad_index(variable_block_sizes, math.prod(VSA_TILE_SIZE)) + untile_combined_index = non_pad_index[reverse_tile_partition_indices] return VideoSparseAttentionMetadata( current_timestep=current_timestep, @@ -181,7 +194,8 @@ def build( # type: ignore tile_partition_indices=tile_partition_indices, # type: ignore reverse_tile_partition_indices=reverse_tile_partition_indices, variable_block_sizes=variable_block_sizes, - non_pad_index=non_pad_index) + non_pad_index=non_pad_index, + untile_combined_index=untile_combined_index) class VideoSparseAttentionImpl(AttentionImpl): @@ -200,37 +214,59 @@ def __init__( sp_group = get_sp_group() self.sp_size = sp_group.world_size - def tile(self, x: torch.Tensor, num_tiles: list[int], tile_partition_indices: torch.LongTensor, - non_pad_index: torch.LongTensor) -> torch.Tensor: + def tile(self, x: torch.Tensor, attn_metadata: VideoSparseAttentionMetadata) -> torch.Tensor: + """Tile ``x`` into ``attn_metadata.tile_buf`` and return it. + + The returned tensor aliases the per-metadata buffer and is only + valid until the next ``tile()`` / ``preprocess_qkv`` call on the + same ``attn_metadata``. Callers must consume (or copy) the + result before invoking another VSA layer with the same metadata. + Today both call sites materialize copies via + ``.transpose(...).contiguous()`` inside ``forward()``, so the + contract holds; future callers must preserve it. + """ + num_tiles = attn_metadata.num_tiles t_padded_size = num_tiles[0] * VSA_TILE_SIZE[0] h_padded_size = num_tiles[1] * VSA_TILE_SIZE[1] w_padded_size = num_tiles[2] * VSA_TILE_SIZE[2] - - x_padded = torch.zeros((x.shape[0], t_padded_size * h_padded_size * w_padded_size, x.shape[-2], x.shape[-1]), - device=x.device, - dtype=x.dtype) - x_padded[:, non_pad_index] = x[:, tile_partition_indices] - return x_padded - - def untile(self, x: torch.Tensor, reverse_tile_partition_indices: torch.LongTensor, - non_pad_index: torch.LongTensor) -> torch.Tensor: - x = x[:, non_pad_index][:, reverse_tile_partition_indices] - return x + target_shape = (x.shape[0], t_padded_size * h_padded_size * w_padded_size, x.shape[-2], x.shape[-1]) + + # Reuse the per-step buffer stashed on metadata (lazily allocated + # on the first VSA layer's call within a denoising step). Pad + # positions are zero from the initial torch.zeros and never + # written to. Scoping to metadata makes reuse safe across + # concurrent requests and keeps the "pad positions are zero" + # invariant trivially true: ``non_pad_index`` is fixed within + # a single metadata instance. + buf = attn_metadata.tile_buf + if (buf is None or buf.shape != target_shape or buf.dtype != x.dtype or buf.device != x.device): + buf = torch.zeros(target_shape, device=x.device, dtype=x.dtype) + attn_metadata.tile_buf = buf + + buf[:, attn_metadata.non_pad_index] = x[:, attn_metadata.tile_partition_indices] + return buf + + def untile(self, x: torch.Tensor, untile_combined_index: torch.LongTensor) -> torch.Tensor: + # Single fancy index using precomputed combined indices; avoids + # the intermediate ``[B, len(non_pad_index), H, D]`` tensor that + # the two-step ``x[:, non_pad_index][:, reverse_tile_partition_indices]`` + # would allocate on every layer. + return x[:, untile_combined_index] def preprocess_qkv( self, qkv: torch.Tensor, attn_metadata: VideoSparseAttentionMetadata, ) -> torch.Tensor: - return self.tile(qkv, attn_metadata.num_tiles, attn_metadata.tile_partition_indices, - attn_metadata.non_pad_index) + """Tile QKV; aliasing contract: see ``tile()``.""" + return self.tile(qkv, attn_metadata) def postprocess_output( self, output: torch.Tensor, attn_metadata: VideoSparseAttentionMetadata, ) -> torch.Tensor: - return self.untile(output, attn_metadata.reverse_tile_partition_indices, attn_metadata.non_pad_index) + return self.untile(output, attn_metadata.untile_combined_index) def forward( # type: ignore[override] self, diff --git a/fastvideo/pipelines/stages/conditioning.py b/fastvideo/pipelines/stages/conditioning.py index 80fb3b6cc6..95ee9c0d4d 100644 --- a/fastvideo/pipelines/stages/conditioning.py +++ b/fastvideo/pipelines/stages/conditioning.py @@ -6,14 +6,11 @@ import torch from fastvideo.fastvideo_args import FastVideoArgs -from fastvideo.logger import init_logger from fastvideo.pipelines.pipeline_batch_info import ForwardBatch from fastvideo.pipelines.stages.base import PipelineStage from fastvideo.pipelines.stages.validators import StageValidators as V from fastvideo.pipelines.stages.validators import VerificationResult -logger = init_logger(__name__) - class ConditioningStage(PipelineStage): """ @@ -39,31 +36,11 @@ def forward( Returns: The batch with applied conditioning. """ - # TODO!! - if not batch.do_classifier_free_guidance: - return batch - else: - return batch - - logger.info("batch.negative_prompt_embeds: %s", batch.negative_prompt_embeds) - logger.info("do_classifier_free_guidance: %s", batch.do_classifier_free_guidance) - logger.info("cfg_scale: %s", batch.guidance_scale) - - # Ensure negative prompt embeddings are available - assert batch.negative_prompt_embeds is not None, ( - "Negative prompt embeddings are required for classifier-free guidance") - - # Concatenate primary embeddings and masks - batch.prompt_embeds = torch.cat([batch.negative_prompt_embeds, batch.prompt_embeds]) - if batch.attention_mask is not None: - batch.attention_mask = torch.cat([batch.negative_attention_mask, batch.attention_mask]) - - # Concatenate secondary embeddings and masks if present - if batch.prompt_embeds_2 is not None: - batch.prompt_embeds_2 = torch.cat([batch.negative_prompt_embeds_2, batch.prompt_embeds_2]) - if batch.attention_mask_2 is not None: - batch.attention_mask_2 = torch.cat([batch.negative_attention_mask_2, batch.attention_mask_2]) - + # Forward is a no-op: CFG is applied via two separate + # transformer forward passes inside DenoisingStage (e.g. + # denoising.py:364-394, :706, :930). The class is kept because + # verify_input / verify_output still validate CFG fields and + # disable CFG when prompt_embeds is empty. return batch def verify_input(self, batch: ForwardBatch, fastvideo_args: FastVideoArgs) -> VerificationResult: diff --git a/fastvideo/pipelines/stages/denoising.py b/fastvideo/pipelines/stages/denoising.py index c4244e9ac1..c112f48ca0 100644 --- a/fastvideo/pipelines/stages/denoising.py +++ b/fastvideo/pipelines/stages/denoising.py @@ -212,6 +212,23 @@ def forward( trajectory_timesteps: list[torch.Tensor] = [] trajectory_latents: list[torch.Tensor] = [] + # Hoisted out of the per-step loop: depends only on inputs that + # are constant across denoising steps. + use_meanflow = getattr(self.transformer.config, "use_meanflow", False) + embedded_cfg_scale = fastvideo_args.pipeline_config.embedded_cfg_scale + if embedded_cfg_scale is not None: + guidance_expand = (torch.tensor( + [embedded_cfg_scale] * latents.shape[0], + dtype=torch.float32, + device=get_local_torch_device(), + ).to(target_dtype) * 1000.0) + else: + guidance_expand = None + # V2V padding: zero-filled tensor concatenated with each step's + # latent_model_input. Shape is fixed by latents and is never + # written to, so we allocate once. + v2v_zero_pad = torch.zeros_like(latents) if batch.video_latent is not None else None + # Run denoising loop with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): @@ -248,8 +265,7 @@ def forward( # Expand latents for V2V/I2V latent_model_input = latents.to(target_dtype) if batch.video_latent is not None: - latent_model_input = torch.cat([latent_model_input, batch.video_latent, - torch.zeros_like(latents)], + latent_model_input = torch.cat([latent_model_input, batch.video_latent, v2v_zero_pad], dim=1).to(target_dtype) elif batch.image_latent is not None: assert not fastvideo_args.pipeline_config.ti2v_task, "image latents should not be provided for TI2V task" @@ -266,7 +282,6 @@ def forward( t_expand = t.repeat(latent_model_input.shape[0]) t_expand = t_expand.to(get_local_torch_device()) - use_meanflow = getattr(self.transformer.config, "use_meanflow", False) if use_meanflow: if i == len(timesteps) - 1: timesteps_r = torch.tensor([0.0], device=get_local_torch_device()) @@ -285,13 +300,6 @@ def forward( latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) - # Prepare inputs for transformer - guidance_expand = (torch.tensor( - [fastvideo_args.pipeline_config.embedded_cfg_scale] * latent_model_input.shape[0], - dtype=torch.float32, - device=get_local_torch_device(), - ).to(target_dtype) * 1000.0 if fastvideo_args.pipeline_config.embedded_cfg_scale is not None else None) - # Predict noise residual with torch.autocast(device_type="cuda", dtype=target_dtype, enabled=autocast_enabled): if (vsa_available and self.attn_backend == VideoSparseAttentionBackend):