Skip to content

Conversation

@yurekami
Copy link

Summary

Add optional check_legality parameter to set_states() that validates:

  • Batch size consistency between input states and device
  • State normalization (|amplitudes|² should sum to 1)

Problem

As noted in #305, users can set states with mismatched batch sizes or unnormalized states without any warning, leading to confusion and incorrect results.

Solution

Add opt-in validation with informative warnings:

q_device = tq.QuantumDevice(n_wires=2, bsz=1)

# Without validation (default, backwards compatible)
q_device.set_states(states)

# With validation
q_device.set_states(states, check_legality=True)
# Warning: Input states batch size (3) differs from device bsz (1)...
# Warning: Input states are not normalized. Norms: [103.0]...

The device's bsz is updated to match the input states' batch size.

Test plan

  • Verify warning is issued for mismatched batch size
  • Verify warning is issued for unnormalized states
  • Verify no warnings when check_legality=False (default)

Fixes #305

🤖 Generated with Claude Code

Add optional check_legality parameter to set_states() that warns when:
- Input batch size differs from device's bsz (and updates bsz)
- States are not properly normalized (|amplitudes|^2 should sum to 1)

This helps users catch common mistakes like:
- Passing more states than expected batch size
- Using unnormalized states for quantum computations

The validation is opt-in (check_legality=False by default) to maintain
backwards compatibility and avoid performance overhead.

Fixes mit-han-lab#305

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
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.

q_state.bsz is not fix!

1 participant