Repository navigation
Add an async workspace API - #95
Conversation
|
This is the modified version of the shipping example I'm using to test: #!/usr/bin/env python
# coding: utf-8
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import asyncio
import os
from typing import List, Sequence
# Instantiate Workspace object which allows you to connect to the Workspace you've previously deployed in Azure.
# Be sure to fill in the settings below which can be retrieved by running 'az quantum workspace show' in the terminal.
from azure.quantum.aio import Workspace
from azure.quantum.aio.optimization import ParallelTempering, Problem, ProblemType
from azure.quantum.optimization import Term
from rich.console import Console
from rich.table import Table
import numpy as np
NUM_CONTAINERS = 100
CONTAINER_MIN_WEIGHT = 1
CONTAINER_MAX_WEIGHT = 50
# Copy the settings for your workspace below
workspace = Workspace(
resource_id = os.getenv('AZURE_RESOURCE_ID'), # add the Resource ID of your Azure Quantum workspace
location = os.getenv('AZURE_LOCATION', 'westus') # add the location of your Azure Quantum workspace (e.g. "westus")
)
def create_problem_for_container_weights(container_weights: Sequence[int]) -> Problem:
terms: List[Term] = []
# Expand the squared summation
for i in range(len(container_weights)):
for j in range(len(container_weights)):
if i == j:
# Skip the terms where i == j as they form constant terms in an Ising problem and can be disregarded:
# w_i∗w_j∗x_i∗x_j = w_i*w_j∗(x_i)^2 = w_i∗w_j
# for x_i = x_j, x_i ∈ {1, -1}
continue
terms.append(
Term(
c = container_weights[i] * container_weights[j],
indices = [i, j]
)
)
# Return an Ising-type problem
return Problem(name="Ship Sample Problem", problem_type=ProblemType.ising, terms=terms)
# This array contains a list of the weights of the containers
rng = np.random.default_rng()
container_weights = rng.integers(low=CONTAINER_MIN_WEIGHT, high=CONTAINER_MAX_WEIGHT, size=NUM_CONTAINERS)
# Create a problem for the list of containers:
problem1 = create_problem_for_container_weights(container_weights)
# Instantiate a solver to solve the problem.
parallel_solver = ParallelTempering(workspace, timeout=100)
# Print out a summary of the results:
def print_result_summary(result, console):
table = Table(title="Container Allocations")
table.add_column("Container", justify="right", style="cyan", no_wrap=True)
table.add_column("Weight", style="magenta")
table.add_column("Ship", justify="right", style="green")
# Print a summary of the result
ship_a_weight = 0
ship_b_weight = 0
for container in result['configuration']:
container_assignment = result['configuration'][container]
container_weight = container_weights[int(container)]
ship = ''
if container_assignment == 1:
ship = 'A'
ship_a_weight += container_weight
else:
ship = 'B'
ship_b_weight += container_weight
table.add_row(container, str(container_weight), ship)
console.print(table)
print(f'\nTotal weights: \n\tShip A: {ship_a_weight} tonnes \n\tShip B: {ship_b_weight} tonnes\n')
# We can reduce the number of terms by removing duplicates (see associated Jupyter notebook for details)
# In code, this means a small modification to the create_problem_for_container_weights function:
def create_simplified_problem_for_container_weights(container_weights: List[int]) -> Problem:
terms: List[Term] = []
# Expand the squared summation
for i in range(len(container_weights)-1):
for j in range(i+1, len(container_weights)):
terms.append(
Term(
c = container_weights[i] * container_weights[j],
indices = [i, j]
)
)
# Return an Ising-type problem
return Problem(name="Ship Sample Problem (Simplified)", problem_type=ProblemType.ising, terms=terms)
# Check that this creates a smaller problem
# Create the simplified problem
problem2 = create_simplified_problem_for_container_weights(container_weights)
async def submit_problems():
# Schedule three calls *concurrently*:
results = await asyncio.gather(
parallel_solver.optimize(problem1),
parallel_solver.optimize(problem2)
)
console = Console()
print_result_summary(results[0], console)
print_result_summary(results[1], console)
asyncio.run(submit_problems()) |
…removes the need for threading
|
Anthony Shaw (@tonybaloney) I just tried out this feature using the sample copied above but unfortunately it looks like the credentials are incompatible with Am I missing a step? |
|
/azp run |
|
Azure Pipelines successfully started running 2 pipeline(s). |
… and add aio targets.
…ted. Update some of the tests
Update recordings
… test recordings.
|
/azp run |
|
Azure Pipelines successfully started running 2 pipeline(s). |
|
/azp run |
|
Azure Pipelines successfully started running 2 pipeline(s). |
|
Anthony Shaw (@tonybaloney), could you create a new PR to merge it in the branch |
|
Anthony Shaw (@tonybaloney), I opened a PR here to update this branch with the latest changes from |
Merge in changes from main
Guen Prawiroatmodjo (guenp)
left a comment
There was a problem hiding this comment.
Thank you for the awesome contribution! 🙌
* Add an async workspace * Add an async job, async solver and extend the workspace APIs to use the correct types. * Get linked storage has to be async * Add aiohttp requirement * Update conda env as well * refactor into submodule * Add the authentication submodule * Revert some sync job changes leftover * Add async storage and problem interfaces * Refactor the async uses and add an online and streaming problem that removes the need for threading * await problem uploader. * Put the clients into async context managers so that the client sessions are closed. * Workaround for Azure/azure-sdk-for-python#19943 * create client once per workspace * Add async tests and integrate all the refactorings to the job classes and add aio targets. * refactoring async tests * aio streaming problem cant accept terms because that needs to be awaited. Update some of the tests * update the common aio class * update recordings * Add a missing attribute in the recordings and fix a missing await in the job * regex the response URL in the custom response handler * await remaining tests * Fix a bug in the streaming problem causing an infinite loop. Add some test recordings. * clone the sync recordings * add the recordings * refactor the test base to be shared between sync and async * fix broken import * fix UTs * inherit Async classes from Sync classes * add missing targets, add async workspace.get_targets Co-authored-by: XField <[email protected]> Co-authored-by: Guen Prawiroatmodjo <[email protected]>
* Add an async workspace API (#95) * Add an async workspace * Add an async job, async solver and extend the workspace APIs to use the correct types. * Get linked storage has to be async * Add aiohttp requirement * Update conda env as well * refactor into submodule * Add the authentication submodule * Revert some sync job changes leftover * Add async storage and problem interfaces * Refactor the async uses and add an online and streaming problem that removes the need for threading * await problem uploader. * Put the clients into async context managers so that the client sessions are closed. * Workaround for Azure/azure-sdk-for-python#19943 * create client once per workspace * Add async tests and integrate all the refactorings to the job classes and add aio targets. * refactoring async tests * aio streaming problem cant accept terms because that needs to be awaited. Update some of the tests * update the common aio class * update recordings * Add a missing attribute in the recordings and fix a missing await in the job * regex the response URL in the custom response handler * await remaining tests * Fix a bug in the streaming problem causing an infinite loop. Add some test recordings. * clone the sync recordings * add the recordings * refactor the test base to be shared between sync and async * fix broken import * fix UTs * inherit Async classes from Sync classes * add missing targets, add async workspace.get_targets Co-authored-by: XField <[email protected]> Co-authored-by: Guen Prawiroatmodjo <[email protected]> * Add async support for Workspace.get_targets (#135) Add async support for Workspace.get_targets, merge in changes from main: * Add environment variable to set User-Agent prefix (#133) * Add deprecation notice to 3rd party QIO namespaces (#132) * Revert "Support fleet management jobs (#127)" (#134) * Revert "Support fleet management jobs (#127)" * Changing schema of grouped terms and separating term types (#131) * Remove lingering fleet-mgmt (#137) * Update installation instructions in readme and example notebook (#139) * added MANIFEST.in file to include requirements.txt (#140) * Rename env vars to start with AZURE_QUANTUM_ (#141) * Make UT for Workspace.get_targets more robust against provider changes (#144) * Serialize problem name (#64) * Workspace.get_targets() returns generic Target for unknown targets (#148) * Add Qiskit and Cirq plugins for IonQ and Honeywell targets (#149) * fix bug in case insensitive provider lookup (#150) * Update README, add Azure Quantum logo (#154) * Refactor CI/CD steps, add tests against cirq beta (#151) * Update README to use logo file from main branch (#155) Co-authored-by: XField <[email protected]> Co-authored-by: ashwinmayya <[email protected]> Co-authored-by: adelebai <[email protected]> Co-authored-by: Andres Paz <[email protected]> Co-authored-by: Anudeep Gunukula <[email protected]> * set user agent * append user agent info rather than replace it * test if user_agent is set * append with dash instead of space * add test * test long user agent, test from env var * close client sessions before returning * close client for download_blob * close client for download_blob * Fixes to feature/aio (#166) * Async fixes on storage * Fixes on Async workspace * Fixes on Async Workspace * Fixes in the async _authentication * Linting fixes * Fixes on Async job * Fixes in the Async Optimization * Fixes on Async Target * Update azure-quantum/azure/quantum/job/base_job.py Co-authored-by: Guen Prawiroatmodjo <[email protected]> * Revert Async Target changes Co-authored-by: Guen Prawiroatmodjo <[email protected]> * Async oneqbit.py File rename (#167) * Async fixes on storage * Fixes on Async workspace * Fixes on Async Workspace * Fixes in the async _authentication * Linting fixes * Fixes on Async job * Fixes in the Async Optimization * Fixes on Async Target * Update azure-quantum/azure/quantum/job/base_job.py Co-authored-by: Guen Prawiroatmodjo <[email protected]> * Revert Async Target changes * Typo while renaming the file * Typo renaming oneqbit file Co-authored-by: Guen Prawiroatmodjo <[email protected]> * fix circular import * update environment yml files * update env name * Async PR fixes (#170) * Port UserAgent changes from Sync to Async * Fix async streaming problem * Fix Async tests * add async mark * Async PR fixes (#171) * Port UserAgent changes from Sync to Async * Fix async streaming problem * Fix Async tests * Minor fixes * Update recordings * add missing awaits and methosd to streaming problem * rerecord tests, update env var name * copy aio tests * asyncio mark * Remove .aio from azure-quantum async conda env Co-authored-by: Anthony Shaw <[email protected]> Co-authored-by: XField <[email protected]> Co-authored-by: ashwinmayya <[email protected]> Co-authored-by: adelebai <[email protected]> Co-authored-by: Andres Paz <[email protected]> Co-authored-by: Anudeep Gunukula <[email protected]>
Implements #94
aiosubmodule to match the Python SDK patternThe biggest amount of duplication here is because of the
_authenticationsubmodule and the default credential class. All of the Python SDKs would expectget_tokento be async, which comes from different interfaces. This could be refactored.Please let me know your thoughts