Repository navigation
Conversation
|
Thanks for contributing to Relax, @SigureMo! 感谢你为 Relax 做出贡献! 📚 Contribution guide / 贡献指南Describe the problem, your changes, and how you validated them. Keep each PR focused and run 请说明问题、改动和验证方式,保持 PR 聚焦,并在提交前运行 🛠️ CI commands / CI 指令
Put one command on the first line of a new PR comment. Rerun/cancel require PR authorship or repository write access. 在新 PR 评论的首行写一条指令。PR 作者或有仓库写权限的贡献者可以重跑、取消 CI。 🔎 Merge requirements / 合入条件GitHub:⏳ 合入条件未满足
|
Summary
Testing
|
Nyanpasu 审查看板审查状态: 🔎 审查中 审查版本: 67bb71d 目标分支: main 已锁定本次 head 并开始审查;范围已接收 82 个文件,常规与深度核查正在进行。旧发现保留待按当前代码重新验证。
审查发现待处理
已解决或已取代
提交范围 · 接收 82 · 建议移出 0 · 待确认 0接收 82 个文件 · 建议移出 0 个文件 · 待确认 0 个文件。移出与待确认部分暂停深审,不代表审查通过。
Powered by Nyanpasu with gpt-6.1-terra xhigh, please check the suggestions carefully.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# ⭐ Feature ## Route hybrid actor->rollout weight push through DCS (opt-in) Port of the hybrid-DCS path (reference: 9ee2aeca on feat/pojun/gemma4-rl-dev, re-implemented against current dev) so hybrid mode can reuse the full-async elastic-rollout infrastructure (seed push -> register DCS -> per-step broadcast). - New flags: --hybrid-weight-sync-backend cuda_ipc(default)/dcs and --hybrid-weights-backuper-on-gpu (dcs only, keeps the "actor" snapshot on-device). Defaults reproduce existing behavior byte-for-byte. - tensor_backper: backup(tag, on_device=) GPU snapshots via one contiguous per-dtype buffer sliced into views; snapshots carry Megatron TP attributes (copy_tensor_model_parallel_attributes + parallel_mode + defaults backfill) — DCS all_gather_param reads them off the tensor, and snapshot plain tensors bypass its isinstance(Parameter) assert, so missing attrs would silently push TP shards as replicated weights. - device_direct: optional weights_getter (decoupled TensorBackuper snapshot instead of the live model that switches actor/ref/teacher tags); lazy per-subset H2D coercion with TP-attr re-attach; vanilla->global name translation (backuper keys are per-rank local names, bridge task lookup needs PP/VP-offset global names — identical only at PP=1); snapshot-aware _should_sync_tensor via precomputed live-Parameter global-name set. - checkpoint client: thread weights_getter to the backend; warn when a push targets an empty rollout topology (silent no-op otherwise). - megatron/actor: hybrid+dcs creates checkpoint_engine_client reading the "actor" tag; _create_checkpoint_engine_client extracted; train_hybrid pushes via update_weights_fully_async(rollout_only=True) — holds _weight_sync_lock against elastic scale-out seed pushes and registers recovered engines; skip the step push when the rollout handshake failed (actor_fwd_only), matching full-async semantics; _advance_keep_old_actor_queue extracted so the DCS path rolls the old_actor queue too. - components/actor: init-time sync routes hybrid+dcs through update_weights_fully_async(0, rollout_only=True) so resumed checkpoints reach engines before rollout_id 0. - arguments: dcs rejects --disable-weights-backuper (Noop backuper aliases live tensors without TP attributes). # ✅ Tests ## Unit tests for the new snapshot/DCS seams (12 cases) - test_tensor_backper: TP-attr attach + defaults backfill, on_device contiguous-buffer layout (shared storage per dtype), buffer reuse across backups, default CPU-pinned behavior unchanged, Noop signature compat. - test_weights_getter: H2D TP-attr preservation, device passthrough identity, name filter applied before H2D, live-model fallback keeps include_persistent_buffers semantics, engine->backend threading, rollout_only=True skips actor_fwd group init. Co-Authored-By: Claude <[email protected]> (cherry picked from commit 079503e)
# ⭐ Feature ## Join every agentic export across three JSONL streams - Add `Sample.sample_export_id`, stamped by the owning SessionShard at export time and carried unchanged through reward, transfer and training - Add `relax/utils/agentic_obs/`: the on-disk record contract, output layout, sync/async JSONL appenders and the train-side emit hook - Everything is off unless `--agentic-obs-dir` is set; each producer starts with a single `None` check ## Write full trajectories from the SessionShard - Add `ShardTrajectoryRecorder`; `AgenticSessionShard._publish_export` stamps the id before the payload snapshot and queues the trajectory after it, so the driver gets the join key and the record keeps `sample_export_ready_at` - Emit through a queue plus background drain: the record is built while `session.lock` is held, and a synchronous write would stall the shard's event loop and the lock together - `LineageNode` carries what `agentic_trace.turns[]` structurally cannot — `obs` nodes, message content, per-node weight versions - Strip inline `data:` URIs to a sha256 digest; `--dump-trajectory-media` writes the bytes to a content-addressed `media/` ## Record what happened to each export on the rollout driver - Add `StageRecorder` and wire the four drop sites plus the successful write: `filter`, `custom_advantage`, `oversampling`, `shutdown`, `transfer` - Emit `queued_for_train` only after `async_put` returns, so a failed or cancelled write never claims the samples reached training - File stage events under the driver step while keeping `partition_id` a record field: the transfer domain holds two partitions open at once ## Report per-sample training scalars from the actor - Add `sample_export_ids` as a TransferQueue column, gated on the same flag on both the producer and the consumer whitelist so they cannot drift - Reduce on device and cross to host once; per-sample `.item()` would be N synchronous stalls inside the training loop - Fail closed on `advantage_*` under static context parallelism, where each rank holds a zig-zag shard and a per-sample mean is wrong rather than partial; the manifest records `cp_size` so a reader can tell why --- # ♻️ Refactor ## Make the two transfer identifiers distinguishable - Rename `_transfer_batch_to_data_system(rollout_id=)` to `partition_id=`; the value is the physical TQ partition, not always the driver step - Add `TransferDomain.pending_groups()` so shutdown can record the Groups a partition accepted but no batch ever detached - Expose `RewardDomain.last_filter_drop_reason`, which otherwise dies inside `finalize_group` returning `None` --- # ✅ Tests ## Cover the record layer and its real producers - `tests/utils/test_agentic_obs.py`: records, packing, media stripping, both appenders including queue-full and flush-on-close - `tests/test_agentic_observability.py`: trajectory building against a real `SessionForest`, stage records, `TransferDomain.pending_groups()`, the gated TQ column, int64 survival of the packed id, and the train-side reduction including the context-parallel fail-closed path (cherry picked from commit a7fc3cca843b0dcb23d83abc2cc6e6330904d064)
| from relax.utils.agentic_obs.source import SourceRow, snapshot_source | ||
|
|
||
| source = ( | ||
| snapshot_source(data, metadata_key=self.metadata_key, split=getattr(self, "source_split", "train")) |
There was a problem hiding this comment.
启用 --dump-agentic-obs 后,这里的快照发生在正常样本处理之前且没有异常隔离。例如 JSONL 中未使用的字段含转义的孤立代理字符 "\ud800" 时,json.loads 可以读取该行,原处理流程也可忽略该字段,但 prompt_identity 的 UTF-8 编码会抛出 UnicodeEncodeError,使数据集加载失败。固定提交上的 CPU 定向检查确认关闭采集时同一行可加载。请在快照失败时保留未知来源并继续处理样本,或采用能安全编码此类输入的方式,同时保证其他快照异常也不会影响训练。
| exc, | ||
| exc_info=True, | ||
| ) | ||
| record_optimizer_result(bool(update_successful)) |
There was a problem hiding this comment.
这里在 train_one_step 完成之前就提交了 completed 边界;之后的学习率调度、梯度清理或归约仍可能抛错。此时 _record_failure 因 state.stage 已设置而不记录失败,merge_train_updates 会将这些成功的优化器结果合并成 committed,即使文档要求训练异常时结果和成员关系保持未知。定向 CPU 检查在成功记录后抛错,得到的仍是 completed/committed。请等观察范围正常退出后再确定终态;如需保留已发生的优化器结果,可将它作为独立事实记录。
## Bug fixes - Record request completion at the terminal response boundary so resumed partial output is completed and empty capacity rejections are failed. - Read shard identity only after Ray is initialized, avoiding an implicit local cluster start from optional observation code. - Preserve the operator's MEGATRON environment override in the smoke launcher. ## Regression coverage - Check partial/context-capacity observations with collection on and off, and verify optimizer outcomes for healthy updates and nonfinite skips. - Exercise actual terminal responses and current checkpoint tracker behavior. - Build media fixtures through current message normalization and restore streaming test imports so fake MPU references do not escape their tests. - Give hybrid lifecycle fixtures the current advantage estimator default. Test snapshot metadata on ordinary CPU allocations and keep the real pinned allocation case gated on accelerator availability. Co-authored-by: Codex <[email protected]>
a33e230 to
8816a73
Compare
| sock.bind(("", 0)) | ||
| master_port = sock.getsockname()[1] | ||
| if self._use_dcs_hybrid_weight_sync: | ||
| self.checkpoint_engine_client = self._create_checkpoint_engine_client( |
There was a problem hiding this comment.
Hybrid 使用 Bridge、TP > 1 且 Qwen4Exp/Qwen3.8 模型含 GPU PLE 表时,这里改走 DCS 会使 rollout 权重同步挂起或超时。DCS 的 _update_weight_from_distributed 先在各 TP rank 上聚合整张表,然后让非源 rank 返回;源 rank 才调用 BridgeConverter.convert。PLE 映射是惰性的,转换器恢复 TP group 后迭代分片时仍会执行 TP all-reduce,此时其他 rank 已不参与。原 HfWeightIteratorBridge 在所有 TP rank 上逐片调用 iter_ple_shards。
同一导出边界在关联实现的双进程 CPU/Gloo 检查中复现了源 rank 超时,而原分片路径完成;完整模型的 GPU/NCCL 行为未实测。请为 Hybrid DCS 保留全 TP 参与的有界 PLE 分片导出或提供等效实现,并覆盖该生产路径;仅屏蔽映射的 collective 不能保留原有分片语义及内存界限。
Merge public main 65d9356 into the sync branch, retaining the source cherry-picks and their original authorship. Match isolated tests to runtime initialization: supply the run recorder collaborator in the entrypoint test and the enabled weights-backuper default in the shared argument fixture. This addresses the three H20 unit-test failures without changing production behavior. Co-authored-by: Codex <[email protected]>
## What Add optional Agentic observability from source merge `ea979372716677e08a0e83835001214ada280821`, whose code change is identical to `a7fc3cca843b0dcb23d83abc2cc6e6330904d064`. `--dump-agentic-obs` joins prompt, group and session inventories, exported trajectories, stage outcomes and per-sample training scalars. Collection is disabled by default. Includes English/Chinese documentation and colocated / asynchronous example launchers. ## Why Follow an individual exported context from its original prompt through generation, reward, selection, transfer and optimizer application. Stable identities and explicit terminal outcomes make dropped, failed and trained exports distinguishable. Relates to #526, which includes the same observability source alongside hybrid DCS changes. This PR scopes the observability feature independently on current `main`. ## How - Carry `sample_export_id` through SessionShard exports, TransferQueue columns and actor observations; preserve opaque int64 identities in JSON records. - Queue bounded background writes for trajectories, stage events, run outcomes and training scalars. Replace inline media with digests, with optional content-addressed sidecars. - Resolve conflicts with current `main` while retaining partial generation on context exhaustion, router retry ownership, Score Centering fields, pre-shifted SFT labels, nonfinite-gradient skips, peak-memory accounting and fault-event lifecycle. - Retain SFT reader options and rebuild provenance when an observation reader encounters an offsets-only cache, preserving physical JSONL row identities across blank lines. - Place CPU regressions under `tests/cpu/`, isolate the CUDA snapshot test, and adapt checkpoint, entrypoint and normalized-message fixtures to current `main`. ## Testing - [x] `pre-commit run --all-files` passes - [ ] Tests pass (`pytest tests/`) - [x] New tests added (if applicable) - [x] Documentation updated (if applicable) Focused local regression across 24 modules: **623 passed, 14 skipped** with GPUs hidden. Coverage includes observability producers/writers, Agentic runtime and protocol behavior, startup/failure outcomes, checkpoint annotation, CPU optimizer/Gloo behavior, source-row provenance, TransferQueue iteration and HTTP timing. The skipped entries comprise 13 unavailable Megatron imports (including module-level skips) and one CUDA snapshot test. The full suite and multi-node GPU integration were not run because this local environment lacks the Megatron training stack and NVIDIA GPUs; these skips are not counted as regression coverage. Both launchers pass `bash -n` and `DRY_RUN=1`. Changed Python files pass duplicate-definition and Ruff F811 checks; all tracked files pass the sensitive-content scan. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [x] Documentation update - [ ] Refactoring (no functional changes) - [ ] Performance improvement - [ ] CI/CD or build changes ## Screenshots / Logs Local focused result: `623 passed, 14 skipped`. The added cache/provenance regression prevents original JSONL row identifiers from being lost when cached offsets are available. Existing media assertions verify sidecar contents and that media writes leave the event loop free.


What
Sync two source commits onto GitHub
main:079503e5e6dae1ee2fae98f48acc7b8830632b70: hybrid DCS weight synchronization, optional device-resident actor snapshots, receiver weight-load/resume lifecycle, complete-prompt evaluation accounting, and elastic validation tools/recipe.a7fc3cca843b0dcb23d83abc2cc6e6330904d064: Agentic prompt/group/session inventories, export trajectories, stage outcomes, and per-sample training scalars, enabled with--dump-agentic-obs.Includes English/Chinese documentation and regression coverage.
Why
Publish the pending source changes while preserving current
mainbehavior for SFT, Score Centering, routing replay, checkpoint rotation, and nonfinite-gradient skips. Hybrid engines added by the autoscaler need later weight updates; observation records need a stable join key from generation through training.How
--disable-weights-backupermust remove that flag for DCS snapshots to retain tensor-parallel metadata.sample_export_idfrom the SessionShard through TransferQueue into training records; queue observation writes away from the event loop and training hot path. Collection remains disabled by default.mainat65d9356dand align the isolated entrypoint/argument fixtures with the run recorder and default weights backuper, addressing the three H20 unit-test failures.The hybrid/DCS implementation overlaps #502. This PR includes the original
079503e5source change in full and targetsmainindependently. The source also contains GPU snapshot, quantized receiver lifecycle, eval completeness, and validation-tool changes absent from #502; it cannot be treated as fully covered by that PR.Previously published commits are not replayed:
95f1a147is already inmainas 8e0dd363, andaa320b86as 860e2f56.Testing
pre-commit run --all-filespassespytest tests/)Focused regression after merging
main, across 47 modules: 1194 passed, 15 skipped, 3 subtests passed. This includes the three previously failing cases, real CPU Adam/Gloo, pipeline/tensor/data-parallel process-group checks, and the merged optimizer-offload and SFT sample-limit paths. Of the skipped cases, 11 require an accelerator or GPU opt-in; four require newer image-built MTP patches absent from the local validation image. The full test suite and multi-node GPU training were not run locally because this environment has no GPUs. GitHub CI will validate the new head using the CUDA 13 Hopper image frommain.Type of Change
Screenshots / Logs
Validation covers hybrid/DCS snapshots and lifecycle, shared topology and recovery publication, quantized receiver control ordering/failures, complete-prompt eval/pass@k, validation-tool behavior, resident SFT, fused/LoRA weight buckets, DeepSeek-V4 synchronization, and initial weight sync. It also retains the previous Agentic/data/checkpoint/CPU Adam/Gloo regressions. Changed Python files pass duplicate-definition and Ruff F811 checks; the three added launchers pass
bash -n.