A19grey commited on
Commit
876ad06
·
1 Parent(s): 50f8f8c

fixed new bug calling spaces.gpu incorrectly and reduced extra spaces.gpu calls

Browse files
Files changed (3) hide show
  1. app.py +55 -20
  2. history.md +26 -0
  3. quantum_utils.py +28 -14
app.py CHANGED
@@ -56,22 +56,45 @@ import logging
56
  from logging.handlers import RotatingFileHandler
57
 
58
  # Configure logging
59
- logging.basicConfig(level=logging.DEBUG,
60
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
61
- handlers=[
62
- logging.StreamHandler(), # Console output
63
- RotatingFileHandler(
64
- 'logs/vqe_simulation.log',
65
- maxBytes=1024 * 1024, # 1MB per file
66
- backupCount=3 # Keep 3 backup files
67
- )
68
- ])
69
- logger = logging.getLogger(__name__)
70
- logger.setLevel(logging.DEBUG) # Ensure logger itself is at DEBUG level
71
-
72
- # Force all handlers to DEBUG level
73
- for handler in logger.handlers:
74
- handler.setLevel(logging.DEBUG)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  def install_dependencies():
77
  print("""Install required packages from requirements.txt.""")
@@ -318,18 +341,28 @@ def create_interface():
318
 
319
  def generate_hamiltonian(molecule_choice: str, scale_factor: float) -> tuple:
320
  """Generate Hamiltonian for the selected molecule."""
 
321
  try:
322
  # Get molecule data
 
 
 
 
 
323
  molecule_data = molecules[molecule_choice]
 
324
 
325
  # Generate Hamiltonian only
 
326
  results = run_vqe_simulation(
327
  molecule_data=molecule_data,
328
  scale_factor=scale_factor,
329
  hamiltonian_only=True
330
  )
 
331
 
332
  # Format Hamiltonian results
 
333
  hamiltonian_html = f"""
334
  <div style='padding: 10px; background-color: #f5f5f5; border-radius: 5px; font-size: 0.8em;'>
335
  <h3>Hamiltonian Generated:</h3>
@@ -344,13 +377,16 @@ def create_interface():
344
  </div>
345
  """
346
 
347
- # Format circuit output with monospace preservation and escape special characters
 
348
  circuit_latex = f"""<div class='circuit-output'><pre>{results.get('circuit_latex', 'Circuit visualization not available').replace('`', '&#96;')}</pre></div>"""
349
 
350
- # Enable the VQE button now that Hamiltonian is generated
351
  return hamiltonian_html, circuit_latex, gr.update(interactive=True), None
352
-
353
  except Exception as e:
 
 
354
  error_msg = f"<div style='color: red;'>Error generating Hamiltonian:<br>{str(e)}</div>"
355
  return error_msg, "Error generating circuit visualization", gr.update(interactive=False), None
356
 
@@ -447,7 +483,6 @@ def create_interface():
447
  inputs=[molecule_choice],
448
  outputs=[params_display, scale_factor, molecule_viz]
449
  )
450
-
451
  # Generate Hamiltonian when button is clicked
452
  generate_ham_button.click(
453
  fn=generate_hamiltonian,
 
56
  from logging.handlers import RotatingFileHandler
57
 
58
  # Configure logging
59
+ os.makedirs('logs', exist_ok=True)
60
+
61
+ # Create formatters
62
+ file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
63
+ console_formatter = logging.Formatter('%(levelname)s - %(message)s')
64
+
65
+ # Set up file handler with rotation
66
+ file_handler = RotatingFileHandler(
67
+ 'logs/vqe_simulation.log',
68
+ maxBytes=1024 * 1024, # 1MB per file
69
+ backupCount=3 # Keep 3 backup files
70
+ )
71
+ file_handler.setFormatter(file_formatter)
72
+ file_handler.setLevel(logging.DEBUG)
73
+
74
+ # Set up console handler with less verbose output
75
+ console_handler = logging.StreamHandler()
76
+ console_handler.setFormatter(console_formatter)
77
+ console_handler.setLevel(logging.INFO) # Only show INFO and above in console
78
+
79
+ # Configure root logger
80
+ logger = logging.getLogger()
81
+ logger.setLevel(logging.DEBUG)
82
+
83
+ # Remove any existing handlers
84
+ for handler in logger.handlers[:]:
85
+ logger.removeHandler(handler)
86
+
87
+ # Add our handlers
88
+ logger.addHandler(file_handler)
89
+ logger.addHandler(console_handler)
90
+
91
+ # Disable other loggers that might be too verbose
92
+ logging.getLogger('httpcore.http11').setLevel(logging.WARNING)
93
+ logging.getLogger('httpx').setLevel(logging.WARNING)
94
+ logging.getLogger('gradio').setLevel(logging.WARNING)
95
+
96
+ # Log startup message
97
+ logger.info("VQE Demo Application Starting")
98
 
99
  def install_dependencies():
100
  print("""Install required packages from requirements.txt.""")
 
341
 
342
  def generate_hamiltonian(molecule_choice: str, scale_factor: float) -> tuple:
343
  """Generate Hamiltonian for the selected molecule."""
344
+ logger.info(f"Starting Hamiltonian generation for molecule: {molecule_choice}, scale: {scale_factor}")
345
  try:
346
  # Get molecule data
347
+ logger.debug("Loading molecule data from molecules dictionary")
348
+ if molecule_choice not in molecules:
349
+ logger.error(f"Molecule {molecule_choice} not found in molecules dictionary")
350
+ return "<div>Error: Invalid molecule selection</div>", "", gr.update(interactive=False), None
351
+
352
  molecule_data = molecules[molecule_choice]
353
+ logger.debug(f"Loaded molecule data: {molecule_data}")
354
 
355
  # Generate Hamiltonian only
356
+ logger.info("Calling run_vqe_simulation with hamiltonian_only=True")
357
  results = run_vqe_simulation(
358
  molecule_data=molecule_data,
359
  scale_factor=scale_factor,
360
  hamiltonian_only=True
361
  )
362
+ logger.debug(f"VQE simulation results: {results}")
363
 
364
  # Format Hamiltonian results
365
+ logger.debug("Formatting Hamiltonian results")
366
  hamiltonian_html = f"""
367
  <div style='padding: 10px; background-color: #f5f5f5; border-radius: 5px; font-size: 0.8em;'>
368
  <h3>Hamiltonian Generated:</h3>
 
377
  </div>
378
  """
379
 
380
+ # Format circuit output
381
+ logger.debug("Formatting circuit LaTeX output")
382
  circuit_latex = f"""<div class='circuit-output'><pre>{results.get('circuit_latex', 'Circuit visualization not available').replace('`', '&#96;')}</pre></div>"""
383
 
384
+ logger.info("Successfully generated Hamiltonian and circuit visualization")
385
  return hamiltonian_html, circuit_latex, gr.update(interactive=True), None
386
+
387
  except Exception as e:
388
+ import traceback
389
+ logger.error(f"Error in generate_hamiltonian: {str(e)}\n{traceback.format_exc()}")
390
  error_msg = f"<div style='color: red;'>Error generating Hamiltonian:<br>{str(e)}</div>"
391
  return error_msg, "Error generating circuit visualization", gr.update(interactive=False), None
392
 
 
483
  inputs=[molecule_choice],
484
  outputs=[params_display, scale_factor, molecule_viz]
485
  )
 
486
  # Generate Hamiltonian when button is clicked
487
  generate_ham_button.click(
488
  fn=generate_hamiltonian,
history.md CHANGED
@@ -1,5 +1,14 @@
1
  # Development History
2
 
 
 
 
 
 
 
 
 
 
3
  ## 2024-03-21
4
  - Fixed molecule visualization issues by replacing hydrogen atoms with nitrogen:
5
  * Modified visualization.py to replace H with N atoms for display purposes only
@@ -192,3 +201,20 @@ Steps tried so far:
192
  - Added py3Dmol dependency to requirements.txt
193
  - Updated app interface to use HTML component for 3D molecule viewer
194
  - Improved H2 molecule representation with proper 3D coordinates and styling
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Development History
2
 
3
+ ## 2025-01-15 (Update)
4
+ - Improved logging configuration:
5
+ * Reduced console output verbosity by setting console handler to INFO level
6
+ * Filtered out backend framework messages (httpcore, httpx, gradio)
7
+ * Improved log formatting with more concise console output
8
+ * Maintained detailed DEBUG logging to file for troubleshooting
9
+ * Fixed duplicate logging handlers issue
10
+ - Reverted kernel function to use @cudaq.kernel decorator as per VQE_Example.md reference implementation
11
+
12
  ## 2024-03-21
13
  - Fixed molecule visualization issues by replacing hydrogen atoms with nitrogen:
14
  * Modified visualization.py to replace H with N atoms for display purposes only
 
201
  - Added py3Dmol dependency to requirements.txt
202
  - Updated app interface to use HTML component for 3D molecule viewer
203
  - Improved H2 molecule representation with proper 3D coordinates and styling
204
+
205
+ ## 2025-01-15 (Update 3)
206
+ - Fixed critical bug in spaces.GPU decorator usage:
207
+ * Issue: spaces.GPU decorator was called with direct value `@spaces.GPU(gpu_time)` causing "TypeError: 'int' object is not callable"
208
+ * Fix: Updated to use correct keyword argument format `@spaces.GPU(duration=gpu_time)`
209
+ * This bug was particularly challenging to diagnose as it manifested as a cryptic error message
210
+ * Affected both run_vqe_simulation and generate_hamiltonian functions
211
+ * The fix ensures proper GPU time allocation for quantum simulations
212
+
213
+ ## 2025-01-15 (Update 2)
214
+ - Enhanced molecule visualization debugging:
215
+ * Added detailed logging throughout molecule creation process
216
+ * Switched back to using real H atoms instead of N replacements
217
+ * Added explicit error handling for each molecule creation step
218
+ * Added detailed atom and bond property logging
219
+ * Improved 3D coordinate generation logging
220
+ * Fixed potential issues with implicit hydrogens
quantum_utils.py CHANGED
@@ -25,9 +25,9 @@ from openfermion.transforms import jordan_wigner, get_fermion_operator
25
  # Create logs directory if it doesn't exist
26
  os.makedirs('logs', exist_ok=True)
27
 
28
- # Configure logging to write to both file and stderr
29
- # Create a formatter
30
- formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
31
 
32
  # Set up file handler with rotation
33
  file_handler = RotatingFileHandler(
@@ -35,24 +35,31 @@ file_handler = RotatingFileHandler(
35
  maxBytes=10*1024*1024, # 10MB
36
  backupCount=5
37
  )
38
- file_handler.setFormatter(formatter)
 
39
 
40
- # Set up console handler
41
  console_handler = logging.StreamHandler()
42
- console_handler.setFormatter(formatter)
 
43
 
44
- # Configure root logger
45
- logger = logging.getLogger()
46
  logger.setLevel(logging.DEBUG)
 
 
 
 
 
 
47
  logger.addHandler(file_handler)
48
  logger.addHandler(console_handler)
49
 
50
  # Log startup message
51
- logging.info("VQE Simulation logging initialized")
52
 
53
  print("quantum_utils imported", file=sys.stderr, flush=True)
54
 
55
- @spaces.GPU
56
  def setup_target():
57
  """Set up CUDA-Q target based on available hardware."""
58
  try:
@@ -244,9 +251,10 @@ def generate_hamiltonian(molecule_data: Dict[str, Any],
244
  """
245
  # Get GPU time from molecule data or use default
246
  gpu_time = molecule_data.get('GPU_time', 60)
 
247
 
248
  # Decorate the function with the correct GPU time
249
- @spaces.GPU(gpu_time)
250
  def _generate_hamiltonian_inner():
251
  logging.info(f"Generating Hamiltonian for {molecule_data['name']} with scale factor {scale_factor}")
252
 
@@ -268,7 +276,8 @@ def generate_hamiltonian(molecule_data: Dict[str, Any],
268
  # Get Hamiltonian info
269
  term_count = spin_hamiltonian.get_term_count()
270
  logging.debug(f"Hamiltonian has {term_count} terms.")
271
- logging.debug(f"Hamiltonian details:\n{spin_hamiltonian}")
 
272
 
273
  # Get system parameters
274
  qubit_count = 2 * molecule_data['spatial_orbitals']
@@ -329,12 +338,17 @@ def run_vqe_simulation(molecule_data: Dict[str, Any],
329
  The dictionary containing either just Hamiltonian info or full VQE results
330
  """
331
  # Get GPU time and max iterations from molecule data or use defaults
 
332
  gpu_time = molecule_data.get('GPU_time', 60)
333
-
334
  # Decorate the function with the correct GPU time
335
- @spaces.GPU(gpu_time)
 
 
 
336
  def _run_vqe_simulation_inner():
337
  # Generate Hamiltonian and get system parameters
 
338
  ham_info = generate_hamiltonian(molecule_data, scale_factor)
339
 
340
  # If only Hamiltonian generation is requested, return early
 
25
  # Create logs directory if it doesn't exist
26
  os.makedirs('logs', exist_ok=True)
27
 
28
+ # Create formatters
29
+ file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
30
+ console_formatter = logging.Formatter('%(levelname)s - %(message)s')
31
 
32
  # Set up file handler with rotation
33
  file_handler = RotatingFileHandler(
 
35
  maxBytes=10*1024*1024, # 10MB
36
  backupCount=5
37
  )
38
+ file_handler.setFormatter(file_formatter)
39
+ file_handler.setLevel(logging.DEBUG)
40
 
41
+ # Set up console handler with less verbose output
42
  console_handler = logging.StreamHandler()
43
+ console_handler.setFormatter(console_formatter)
44
+ console_handler.setLevel(logging.INFO) # Only show INFO and above in console
45
 
46
+ # Configure logger
47
+ logger = logging.getLogger(__name__)
48
  logger.setLevel(logging.DEBUG)
49
+
50
+ # Remove any existing handlers
51
+ for handler in logger.handlers[:]:
52
+ logger.removeHandler(handler)
53
+
54
+ # Add our handlers
55
  logger.addHandler(file_handler)
56
  logger.addHandler(console_handler)
57
 
58
  # Log startup message
59
+ logger.info("VQE Simulation module initialized")
60
 
61
  print("quantum_utils imported", file=sys.stderr, flush=True)
62
 
 
63
  def setup_target():
64
  """Set up CUDA-Q target based on available hardware."""
65
  try:
 
251
  """
252
  # Get GPU time from molecule data or use default
253
  gpu_time = molecule_data.get('GPU_time', 60)
254
+ logger.info(f"Generating Hamiltonian with GPU time: {gpu_time}")
255
 
256
  # Decorate the function with the correct GPU time
257
+ # @spaces.GPU(duration=gpu_time)
258
  def _generate_hamiltonian_inner():
259
  logging.info(f"Generating Hamiltonian for {molecule_data['name']} with scale factor {scale_factor}")
260
 
 
276
  # Get Hamiltonian info
277
  term_count = spin_hamiltonian.get_term_count()
278
  logging.debug(f"Hamiltonian has {term_count} terms.")
279
+ # Commented out because it's too much info to show in the logs
280
+ # logging.debug(f"Hamiltonian details:\n{spin_hamiltonian}")
281
 
282
  # Get system parameters
283
  qubit_count = 2 * molecule_data['spatial_orbitals']
 
338
  The dictionary containing either just Hamiltonian info or full VQE results
339
  """
340
  # Get GPU time and max iterations from molecule data or use defaults
341
+ logger.info(f"Running VQE simulation with GPU time")
342
  gpu_time = molecule_data.get('GPU_time', 60)
343
+ logger.info(f"GPU time: {gpu_time}")
344
  # Decorate the function with the correct GPU time
345
+ logger.info(f"Adding GPU time decorator: {gpu_time}")
346
+
347
+ setup_target()
348
+
349
  def _run_vqe_simulation_inner():
350
  # Generate Hamiltonian and get system parameters
351
+ logger.info("Generating Hamiltonian")
352
  ham_info = generate_hamiltonian(molecule_data, scale_factor)
353
 
354
  # If only Hamiltonian generation is requested, return early