Skip to content

Commit 535da56

Browse files
update llm files
1 parent 92af2b8 commit 535da56

File tree

3 files changed

+107
-60
lines changed

3 files changed

+107
-60
lines changed

examples/hamiltonian_building.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,11 @@
4747
h12 = tc.quantum.heisenberg_hamiltonian(
4848
g, hzz=1, hxx=0, hyy=0, hz=0, hx=-1, hy=0, sparse=True
4949
)
50+
# JAX is asynchronous; block to measure execution time
51+
if hasattr(h12, "data") and hasattr(h12.data, "block_until_ready"):
52+
h12.data.block_until_ready()
53+
elif hasattr(h12, "block_until_ready"):
54+
h12.block_until_ready()
5055
time1 = time.perf_counter()
5156

5257
print("tc (jax) time: ", time1 - time0)
@@ -55,6 +60,10 @@
5560
h12 = tc.quantum.heisenberg_hamiltonian(
5661
g, hzz=1, hxx=0, hyy=0, hz=0, hx=-1, hy=0, sparse=True
5762
)
63+
if hasattr(h12, "data") and hasattr(h12.data, "block_until_ready"):
64+
h12.data.block_until_ready()
65+
elif hasattr(h12, "block_until_ready"):
66+
h12.block_until_ready()
5867
time1 = time.perf_counter()
5968

6069
print("tc (jax) time (after jit): ", time1 - time0)

llm.md

Lines changed: 62 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,33 @@
11
# TensorCircuit-NG Repository Guide for AI Agents
22

3-
## Repository Overview
3+
## Core Philosophy
44

5-
TensorCircuit is a high-performance unified quantum computing framework designed for the NISQ (Noisy Intermediate-Scale Quantum) era. It provides a comprehensive set of tools for quantum circuit simulation with support for multiple backends including Numpy, TensorFlow, JAX, and PyTorch.
5+
TensorCircuit is a **Tensor Network-first**, **Multi-Backend** quantum computing framework. When contributing to this codebase, you must adhere to the following architectural principles:
66

7-
## Documentation and AI Native Services
7+
### Unified Backend Interface
8+
- **Rule**: Never use backend-specific libraries (numpy, tensorflow, jax) directly in core logic.
9+
- **Pattern**: Use the `tc.backend` abstraction for all tensor operations.
10+
- **Example**: Use `tc.backend.sin(x)` instead of `np.sin(x)` or `tf.math.sin(x)`. This ensures code runs seamlessly on TensorFlow, JAX, PyTorch, and NumPy.
811

9-
### Official Documentation
12+
### Differentiable Programming (AD)
13+
- **Rule**: All core components must be differentiable.
14+
- **Pattern**: Avoid operations that break the computation graph (e.g., converting to numpy inside a differentiable function, using in-place assignments on tensors).
15+
- **Goal**: End-to-end differentiability allows variational algorithms and gradient-based optimization to work out of the box.
1016

11-
- Main Documentation: https://tensorcircuit-ng.readthedocs.io/
12-
- Quick Start Guide: https://tensorcircuit-ng.readthedocs.io/en/latest/quickstart.html
13-
- Tutorials: https://tensorcircuit-ng.readthedocs.io/en/latest/tutorial.html
14-
- API Reference: Available in docstrings throughout the codebase
17+
### JIT-First Optimization
18+
- **Rule**: Write code that is JIT-compilable (Just-In-Time).
19+
- **Pattern**: Avoid Python control flow (if/else) that depends on tensor values. Use `tc.backend.cond` or `tc.backend.switch` if necessary, or structure code to be statically analyzable.
20+
- **Benefit**: This enables massive speedups on JAX and TensorFlow backends.
1521

16-
### AI-Native Documentation Services
17-
18-
- Devin Deepwiki: https://deepwiki.com/tensorcircuit/tensorcircuit-ng
19-
- Context7 MCP: https://context7.com/tensorcircuit/tensorcircuit-ng
2022

21-
### Educational Resources
23+
## Repository Structure
2224

23-
- Quantum Computing Lectures with TC-NG: https://github.com/sxzgroup/qc_lecture
25+
- `tensorcircuit/`: Core package source code.
26+
- `backends/`: Backend implementations (avoid modifying unless necessary).
27+
- `templates/`: High-level modules (ansatzes, Hamiltonians, graphs).
28+
- `examples/`: Usage demos and benchmarks. Use these as reference implementations.
29+
- `tests/`: Comprehensive test suite. Check these for expected behavior.
30+
- `docs/`: Sphinx documentation source.
2431

2532
## Configuration and Dependencies
2633

@@ -63,42 +70,39 @@ TensorCircuit is a high-performance unified quantum computing framework designed
6370

6471
3. `.pylintrc` - Code style enforcement with specific rules enabled
6572

66-
## Common Bash Commands
6773

68-
### Development Checks
74+
## AI Agent Best Practices
75+
76+
### Code Navigation
77+
- **Search First**: The codebase is extensive. Search for class definitions (e.g., `class Hamiltonian`) rather than guessing file paths.
78+
- **Check Tests**: `tests/test_*.py` files are the ultimate source of truth for how APIs are intended to be used.
79+
80+
### Coding Standards
81+
- **Linting**: We enforce strict **Pylint** and **Black** formatting.
82+
- Run `bash check_all.sh` before submitting changes.
83+
- Target Pylint score: 10.0/10.
84+
- **Type Hinting**: Use type hints liberally to aid static analysis.
85+
- **Documentation**: Write clear docstrings (reStructuredText format) for all public APIs.
6986

87+
### Common Workflows
88+
89+
#### 1. Running Tests
7090
```bash
71-
# Run all checks (black, mypy, pylint, pytest, sphinx)
72-
bash check_all.sh
73-
74-
# Equivalent to the following individual checks:
75-
black . --check # Code formatting check
76-
mypy tensorcircuit # Type checking
77-
pylint tensorcircuit tests examples/*.py # Code linting
78-
pytest -n auto --cov=tensorcircuit -vv -W ignore::DeprecationWarning # Run tests
79-
80-
# Run all tests with coverage report
81-
pytest --cov=tensorcircuit --cov-report=xml -svv --benchmark-skip
82-
83-
# Run specific test file
84-
pytest tests/test_circuit.py
85-
86-
# Install dependencies
87-
pip install --upgrade pip
88-
pip install -r requirements/requirements.txt
89-
pip install -r requirements/requirements-dev.txt
90-
pip install -r requirements/requirements-extra.txt
91-
pip install -r requirements/requirements-types.txt
92-
```
91+
# Run all tests (auto-parallelized)
92+
pytest -n auto
9393

94-
## AI Agent Best Practices
94+
# Run specific test file (useful during debugging)
95+
pytest tests/test_hamiltonians.py
96+
```
9597

96-
### Efficient Code Navigation
98+
#### 2. Checking Code Quality
99+
```bash
100+
# Check formatting
101+
black . --check
97102

98-
- Use the search function to find specific classes and functions rather than browsing files
99-
- Look for example usage in the /examples/ directory when learning new features
100-
- Check tests in /tests/ directory for detailed usage examples
101-
- Refer to docstrings for API documentation
103+
# Run linter on specific file
104+
pylint tensorcircuit/quantum.py
105+
```
102106

103107
### Common Patterns in the Codebase
104108

@@ -108,13 +112,11 @@ pip install -r requirements/requirements-types.txt
108112
- Vectorized operations using tc.backend.vmap patterns
109113
- Context managers for temporary configuration changes
110114

111-
### Working with Quantum Concepts
112-
113-
- Familiarity with quantum computing basics (qubits, gates, measurements)
114-
- Understanding of tensor network concepts for advanced features
115-
- Knowledge of different quantum computing paradigms (digital, analog, noisy, etc.)
115+
### Branch Strategy
116116

117-
## Additional Information
117+
- master branch for stable releases
118+
- beta branch for nightly builds (as seen in nightly_release.yml)
119+
- pull requests for feature development
118120

119121
### Test Structure
120122

@@ -130,18 +132,18 @@ pip install -r requirements/requirements-types.txt
130132

131133
### Package Distribution
132134

133-
- Distributed as tensorcircuit-ng package
135+
- Distributed as tensorcircuit-ng package in PyPI
134136
- Supports extra dependencies for specific backends (tensorflow, jax, torch, qiskit, cloud)
135137

136-
### Core Design Principles
138+
## Further Reading
137139

138-
- Unified interface across multiple backends
139-
- High performance through tensor network optimizations
140-
- Extensible architecture for quantum computing research
141-
- Compatibility with major quantum computing frameworks
140+
- **Specific Protocols**: See `experience.md` for detailed protocols on development, profiling, and performance tuning.
141+
142+
- **Official Docs**: https://tensorcircuit-ng.readthedocs.io/
143+
144+
### AI-Native Documentation Services
145+
146+
- Devin Deepwiki: https://deepwiki.com/tensorcircuit/tensorcircuit-ng
147+
- Context7 MCP: https://context7.com/tensorcircuit/tensorcircuit-ng
142148

143-
### Branch Strategy
144149

145-
- master branch for stable releases
146-
- beta branch for nightly builds (as seen in nightly_release.yml)
147-
- pull requests for feature development

llm_experience.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# TensorCircuit Development Experience & Protocols
2+
3+
This document records specific technical protocols, lessons learned, and advanced practices for developing TensorCircuit. Refer to this when implementing complex features or debugging performance issues.
4+
5+
## JAX, Compilation, and Performance
6+
7+
1. **Benchmarking JAX Code**:
8+
* JAX execution is asynchronous. To measure execution time accurately, always call `.block_until_ready()` on the result's data buffer (e.g., `result.data.block_until_ready()`).
9+
* Failing to block will only measure the dispatch time, leading to confusing results (e.g., "first run faster than second run").
10+
11+
2. **Memory Management (OOM Prevention)**:
12+
* For operations over large batches (e.g., summing $2^{22}$ Pauli strings), `vmap` materializes all intermediate results in memory.
13+
* **Protocol**: Use `jax.lax.scan` or sequential loops for reductions over large inputs to keep peak memory usage constant ($O(1)$) rather than linear ($O(N)$).
14+
15+
## Testing and Robustness
16+
17+
1. **Sparse Matrix Compatibility**:
18+
* TensorCircuit supports multiple sparse formats (Scipy CSR/COO, JAX BCOO, TensorFlow SparseTensor).
19+
* **Protocol**: When handling sparse outputs, do NOT assume specific attributes like `.row` or `.col` exist (missing in JAX BCOO or Scipy CSR).
20+
* **Check**: Use `hasattr(obj, "tocoo")` to detect Scipy sparse matrices and convert them if a standard COO interface is needed.
21+
* **Comparison**: Compare sparse matrices by subtraction (`abs(A - B).max() ≈ 0`) rather than element-wise attribute checks, to be robust against format differences.
22+
23+
## Visualization
24+
25+
1. **Non-Blocking Plots**:
26+
* Library plotting functions (e.g., `Lattice.show`) must accept an optional `ax` (Matplotlib Axis) argument.
27+
* **Protocol**: Draw on the provided `ax` and avoid calling `plt.show()` inside library functions. This allows users to embed plots in subplots and manage the figure lifecycle (saving/closing) themselves.
28+
29+
## Benchmarking External Libraries
30+
31+
1. **Environment Isolation**:
32+
* When benchmarking against external libraries (e.g., QuSpin, Quimb, Qiskit) that may have conflicting dependencies, create a dedicated Conda environment (e.g., `bench_quspin`).
33+
* Install the external library there using pip from the specific conda environment and run the benchmark script using that specific interpreter.
34+
35+
2. **Fair Comparison**:
36+
* Ensure "apples-to-apples" settings (e.g., same precision `complex128`) to support valid performance claims.

0 commit comments

Comments
 (0)