Skip to content

feat(alignment): add cross-configuration framework#230

Open
CyberSecurityErial wants to merge 8 commits into
mainfrom
feat/cross-config-alignment
Open

feat(alignment): add cross-configuration framework#230
CyberSecurityErial wants to merge 8 commits into
mainfrom
feat/cross-config-alignment

Conversation

@CyberSecurityErial

@CyberSecurityErial CyberSecurityErial commented Jul 19, 2026

Copy link
Copy Markdown
Collaborator

Summary

Add a compact cross-configuration alignment framework with a CPU-only executable smoke path and explicit extension boundaries for future production adapters.

Functional modules

  • Semantic operator catalog: Extends the existing kernel registry with target-aware capability resolution, explicit fallback traces, and stable implementation fingerprints.
  • Contract and planner: Defines versioned experiment types, the fixed numerical contract, deterministic case IDs, bounded OAT planning, and opt-in pairwise expansion.
  • Runtime materialization: Converts requested knobs into immutable per-side runtime bindings while preserving requested, normalized, materialized, and actual provenance.
  • Paired execution: Scores one canonical token sequence independently on rollout and training sides with lifecycle isolation, timeout handling, and fail-closed validation.
  • Artifacts and resume: Persists append-only attempt artifacts with SHA-256 completion seals and resumes only fully validated completed cases.
  • CPU smoke adapter: Provides two explicitly gated CPU-only selected-logprob backends that exercise pass, mismatch, dual-side replacement, and strict rejection paths.
  • CLI and scenarios: Supplies one executable CPU smoke command plus three planning-only scenario configurations for future distributed and production adapters.

Scope and claim boundary

The executable path validates framework plumbing with a synthetic CPU model. It does not claim production vLLM, FSDP, tensor/context-parallel, distributed, or accelerator numerical alignment. The larger named scenarios are reproducible planning inputs until production adapters expose verified injection and read-back hooks.

Planned cases:

Scenario Cases Evidence
S0 CPU smoke 1 Passes on CPU; a second invocation validates and resumes the same completed attempt.
S1 distributed smoke 5 Planning only; no runtime is constructed.
S2 vLLM TP versus FSDP 10 Planning only; no runtime is constructed.
S3 Qwen3-8B TP=4, CP=4, BF16 11 Planning only; no runtime is constructed.

Validation

  • Focused contract/runtime/runner/CLI and existing regression tests: 60 passed.
  • CPU-collectable repository suite: 418 passed, 242 skipped.
  • MyPy: 87 source files, no issues.
  • Pinned Black, isort, and flake8 checks pass.
  • Strict MkDocs build, JSON parsing, and git diff --check pass.

The CPU suite excludes the two Triton-required collection modules; Gloo and POSIX shared-memory tests were run with host resources available.

Review order

  1. feat(kernels): add semantic operator catalog
  2. feat(alignment): define cross-configuration contracts and plans
  3. feat(alignment): add runtime materialization and scoring bridge
  4. feat(alignment): add execution and artifact primitives
  5. feat(alignment): add provenance-aware paired execution
  6. feat(alignment): add CPU smoke workflow and CLI
  7. test(alignment): add focused cross-configuration coverage
  8. docs(alignment): document cross-configuration workflow

Related: #83, #108, #111, #222.

Summary by CodeRabbit

  • New Features

    • Added cross-configuration experiment planning, validation, execution, comparison, and resumable artifact handling.
    • Added a command-line workflow for planning experiments and running CPU smoke scenarios.
    • Added fixed-threshold log-probability alignment checks with identity and artifact validation.
    • Added example configurations covering CPU smoke, distributed smoke, and larger model scenarios.
    • Added semantic operator selection and explicit smoke-test operator support.
  • Bug Fixes

    • Improved stateless scoring with custom log-probability functions, position IDs, evaluation mode, and state restoration.
    • Added strict handling for invalid JSON, incomplete runs, timeouts, and mismatched scoring results.
  • Documentation

    • Added cross-configuration design and contract documentation, including usage guidance and scenario coverage.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Introduces a versioned cross-configuration framework for strict experiment planning, semantic operator resolution, runtime materialization, paired rollout/training scoring, fixed-threshold comparison, append-only artifacts, resume validation, CLI execution, and CPU smoke testing.

Changes

Cross-configuration alignment

Layer / File(s) Summary
Contracts, configuration, and planning
rl_engine/alignment/cross_config/schema.py, config.py, planner.py, execution_plan.py, docs/design/*, examples/*
Adds validated schemas, strict configuration loading, OAT/pairwise planning, operator binding, execution-plan serialization, and design documentation.
Semantic operator registry and numerical contract
rl_engine/kernels/semantic_registry.py, rl_engine/kernels/registry.py, rl_engine/alignment/cross_config/operators.py, rl_engine/kernels/gtest/tolerance.py
Adds semantic backend descriptors, strict target-specific resolution, provenance fingerprints, selected-logprob bridging, and fixed tolerance lookup/fingerprinting.
Runtime materialization and provenance
rl_engine/alignment/cross_config/runtime.py, _provenance.py
Adds adapter contracts, knob application validation, runtime bindings, lifecycle fingerprints, execution identity, and environment provenance.
Paired scoring, comparison, artifacts, and resume
rl_engine/alignment/cross_config/_execution.py, runner.py, comparison.py, artifacts.py, _resume.py
Adds isolated read-only rollout/training scoring, rank and identity validation, fixed-threshold comparison, atomic append-only artifacts, completion markers, and identity-checked resume.
CPU smoke runtime and stateless scoring
rl_engine/alignment/testing/*, rl_engine/executors/stateless_executor.py
Adds synthetic CPU scoring, opt-in smoke operators, runtime materialization, custom selected-logprob injection, position IDs, and restoration of model training state.
CLI and validation coverage
rl_engine/alignment/cross_config/__main__.py, tests/*, .github/workflows/ci.yml, pyproject.toml, .gitignore
Adds plan/run CLI commands, CPU-safe CI coverage, pytest marker configuration, ignored run artifacts, and end-to-end contract, runtime, runner, CLI, stateless executor, and tolerance tests.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Suggested reviewers: inaniloquentee, flink-ddd, kjldefeated, bitborne

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.03% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: a new cross-configuration alignment framework under the alignment area.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/cross-config-alignment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
rl_engine/executors/stateless_executor.py (1)

259-271: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate the injected operator’s exact device and dtype.

The assignment into result silently casts a wrong dtype, allowing a backend to violate its declared output contract while rank validation still passes.

Proposed validation
     if shifted_logps.shape != shifted_labels.shape:
         raise ValueError(
             "selected_logprob_fn output shape must match selected token IDs, got "
             f"{tuple(shifted_logps.shape)} and {tuple(shifted_labels.shape)}"
         )
+    if shifted_logps.device != logits.device:
+        raise ValueError("selected_logprob_fn output device must match logits")
+    if shifted_logps.dtype != output_dtype:
+        raise ValueError("selected_logprob_fn output dtype must match output_dtype")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rl_engine/executors/stateless_executor.py` around lines 259 - 271, Extend
validation in the shifted_logps handling near result construction to require
that the injected operator output matches the expected device and dtype exactly,
in addition to the existing tensor and shape checks. Raise a clear validation
error before assigning to result, preserving the existing assignment only for
correctly typed and colocated tensors.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rl_engine/alignment/cross_config/__init__.py`:
- Around line 28-40: Update the __all__ list in the cross_config package to
satisfy Ruff RUF022 by sorting the lowercase exports alphabetically: place
build_execution_plan before compare_score_artifacts, followed by load_config,
while leaving the other exports unchanged.

In `@rl_engine/alignment/cross_config/_provenance.py`:
- Around line 51-56: Update the status ordering in the precedence tuple used by
the provenance aggregation logic so MaterializationStatus.UNOBSERVABLE appears
before MaterializationStatus.FALLBACK. Preserve the remaining precedence order
and align this behavior with RuntimeTools._aggregate_status, ensuring mixed
unobservable and fallback results aggregate to UNOBSERVABLE.

In `@rl_engine/alignment/cross_config/_resume.py`:
- Around line 58-75: Update the resume validation flow to canonically validate
every required artifact before returning True, including materialized.json and
the complete comparison.json and COMPLETE contents. Compare persisted
materialization with materialization.materialized_case, reconstruct and compare
the full alignment result and completion summary, or validate hashes for all
artifacts sealed by COMPLETE. Ensure any missing, mutated, or inconsistent
artifact causes resume validation to return False.

In `@rl_engine/alignment/cross_config/comparison.py`:
- Around line 110-147: Sanitize non-finite inactive values before constructing
TokenComparisonArtifact in the comparison flow. Preserve the existing
active-value validation, then replace inactive entries in rollout_logprobs,
training_logprobs, and absolute_diff with finite zero values before persistence,
while keeping active values unchanged.

In `@rl_engine/alignment/cross_config/planner.py`:
- Around line 201-230: Add a fixed framework case-count limit to the
plan-generation logic around normalize_requested, intervention expansion, and
pairwise product generation. Check the count before appending each requested
case, stop immediately when the limit would be exceeded, and raise the planner’s
structured PLAN_TOO_LARGE error rather than allowing unbounded accumulation;
apply the same guard to both single-intervention and pairwise paths.

In `@rl_engine/alignment/cross_config/runtime.py`:
- Around line 312-333: Extend the validation around expected, descriptors, and
applications to reject every normalized path missing from descriptors,
preventing it from bypassing descriptor checks. For APPLIED applications,
require actual to equal materialized, and for non-derived knobs require
materialized to equal the normalized request. Add these failures to problems so
require_executable() cannot trust invalid adapter status.

In `@rl_engine/alignment/cross_config/schema.py`:
- Around line 525-526: Update the fixed_threshold validation in the relevant
schema class to reject all non-finite values, including NaN and positive
infinity, while retaining the existing non-negative requirement. Use an
is-finite check alongside the current comparison before raising the existing
ValueError.

In `@rl_engine/kernels/gtest/tolerance.py`:
- Around line 29-35: Update the threshold handling in the function containing
_normalize_dtype_name and load_contract so values["atol"] is converted and
validated as a real, finite, non-negative number, rejecting booleans, NaN,
infinity, negatives, and malformed entries. Convert any invalid threshold input
into ValueError while preserving the existing missing-dtype ValueError behavior.

In `@rl_engine/kernels/semantic_registry.py`:
- Around line 282-285: Update the topology matching in the strict resolution
flow around _supports so missing required topology fields do not match
accidentally. Require every explicitly declared descriptor topology key,
including world_size, tensor/context parallelism, and sharding, to be present
and matched; only allow an empty or incomplete requirement set when the
descriptor declares the wildcard "*".

In `@tests/test_cross_config_runtime.py`:
- Line 445: Update the pytest.raises match patterns at the affected tests to
escape the dots in “training.attention_backend” (and the corresponding pattern
near the second occurrence), so pytest treats the dotted path literally and
satisfies RUF043.

---

Outside diff comments:
In `@rl_engine/executors/stateless_executor.py`:
- Around line 259-271: Extend validation in the shifted_logps handling near
result construction to require that the injected operator output matches the
expected device and dtype exactly, in addition to the existing tensor and shape
checks. Raise a clear validation error before assigning to result, preserving
the existing assignment only for correctly typed and colocated tensors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: eaaa134d-3ec1-4de6-bb80-2bb55310aa31

📥 Commits

Reviewing files that changed from the base of the PR and between 6df029a and 35073a1.

⛔ Files ignored due to path filters (1)
  • docs/assets/ws2-cross-config-before-after.png is excluded by !**/*.png
📒 Files selected for processing (41)
  • .github/workflows/ci.yml
  • .gitignore
  • docs/design/cross_config_implementation_report.md
  • docs/design/cross_config_logprob_drift_contract.md
  • docs/design/ws2_cross_config_logprob_drift_contract.md
  • examples/cross_config_s0_cpu_smoke.json
  • examples/cross_config_s1_distributed_smoke.json
  • examples/cross_config_s2_vllm_tp_vs_fsdp.json
  • examples/cross_config_s3_qwen3_8b_tp4_cp4_bf16.json
  • pyproject.toml
  • rl_engine/alignment/cross_config/__init__.py
  • rl_engine/alignment/cross_config/__main__.py
  • rl_engine/alignment/cross_config/_execution.py
  • rl_engine/alignment/cross_config/_json.py
  • rl_engine/alignment/cross_config/_provenance.py
  • rl_engine/alignment/cross_config/_resume.py
  • rl_engine/alignment/cross_config/artifacts.py
  • rl_engine/alignment/cross_config/comparison.py
  • rl_engine/alignment/cross_config/config.py
  • rl_engine/alignment/cross_config/execution_plan.py
  • rl_engine/alignment/cross_config/operators.py
  • rl_engine/alignment/cross_config/planner.py
  • rl_engine/alignment/cross_config/runner.py
  • rl_engine/alignment/cross_config/runtime.py
  • rl_engine/alignment/cross_config/schema.py
  • rl_engine/alignment/testing/__init__.py
  • rl_engine/alignment/testing/cpu_cross_config.py
  • rl_engine/alignment/testing/smoke_ops/SMOKE_OPERATORS.md
  • rl_engine/alignment/testing/smoke_ops/__init__.py
  • rl_engine/alignment/testing/smoke_ops/smoke_only_logp_offset.py
  • rl_engine/alignment/testing/smoke_ops/smoke_only_logp_reference.py
  • rl_engine/executors/stateless_executor.py
  • rl_engine/kernels/gtest/tolerance.py
  • rl_engine/kernels/registry.py
  • rl_engine/kernels/semantic_registry.py
  • tests/test_cross_config_cli.py
  • tests/test_cross_config_contract.py
  • tests/test_cross_config_runner.py
  • tests/test_cross_config_runtime.py
  • tests/test_stateless_executor.py
  • tests/test_tolerance_contract.py
💤 Files with no reviewable changes (1)
  • docs/design/ws2_cross_config_logprob_drift_contract.md

Comment thread rl_engine/alignment/cross_config/__init__.py
Comment thread rl_engine/alignment/cross_config/_provenance.py
Comment thread rl_engine/alignment/cross_config/_resume.py
Comment thread rl_engine/alignment/cross_config/comparison.py
Comment thread rl_engine/alignment/cross_config/planner.py Outdated
Comment thread rl_engine/alignment/cross_config/runtime.py
Comment thread rl_engine/alignment/cross_config/schema.py Outdated
Comment thread rl_engine/kernels/gtest/tolerance.py
Comment thread rl_engine/kernels/semantic_registry.py Outdated
Comment thread tests/test_cross_config_runtime.py Outdated
@CyberSecurityErial
CyberSecurityErial force-pushed the feat/cross-config-alignment branch from 35073a1 to 1c4457e Compare July 19, 2026 01:19
@CyberSecurityErial CyberSecurityErial changed the title feat(alignment): add cross-configuration CPU framework feat(alignment): add cross-configuration framework Jul 19, 2026
@Flink-ddd
Flink-ddd requested review from EthanZero2Hero, a-kaa, maxiaosong1124 and zhangj1an and removed request for bitborne July 19, 2026 06:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant