Skip to content

Add an async workspace API - #95

Merged
Guen Prawiroatmodjo (guenp) merged 38 commits into
microsoft:feature/aiofrom
tonybaloney:aio
Aug 25, 2021
Merged

Guen Prawiroatmodjo (guenp) merged 38 commits into
microsoft:feature/aiofrom
tonybaloney:aio

Conversation

@tonybaloney

@tonybaloney Anthony Shaw (tonybaloney) commented Jul 19, 2021 •

Copy link
Copy Markdown
Contributor

Implements #94

  • Async interfaces are within an aio submodule to match the Python SDK pattern
  • Extends the base workspace class to minimise the amount of duplicate code
  • Implements an async job class
  • Had to expose async solvers to inherit from an async solver class. Used the synchronous solver as a base to avoid duplication

The biggest amount of duplication here is because of the _authentication submodule and the default credential class. All of the Python SDKs would expect get_token to be async, which comes from different interfaces. This could be refactored.

Please let me know your thoughts

@tonybaloney
Anthony Shaw (tonybaloney) marked this pull request as draft July 19, 2021 07:04
@tonybaloney

Anthony Shaw (tonybaloney) commented Jul 19, 2021 •

Copy link
Copy Markdown
Contributor Author

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())

@tonybaloney
Anthony Shaw (tonybaloney) marked this pull request as ready for review July 20, 2021 01:34
@guenp

Copy link
Copy Markdown

Anthony Shaw (@tonybaloney) I just tried out this feature using the sample copied above but unfortunately it looks like the credentials are incompatible with asyncio:

adal.adal_error.AdalError: Get Token request returned http error: 400 and server response: {"error":"interaction_required","error_description":"AADSTS70043: The refresh token has expired or is invalid due to sign-in frequency checks by conditional access. The token was issued on 2021-06-22T07:28:32.1570000Z and the maximum allowed lifetime for this request is 43200.\r\nTrace ID: 2f1a2f47-9079-4661-8056-93164e4f6e00\r\nCorrelation ID: 86c30975-a8f9-4b6c-bbd8-e537d318a95a\r\nTimestamp: 2021-07-26 17:09:17Z","error_codes":[70043],"timestamp":"2021-07-26 17:09:17Z","trace_id":"2f1a2f47-9079-4661-8056-93164e4f6e00","correlation_id":"86c30975-a8f9-4b6c-bbd8-e537d318a95a","suberror":"token_expired"}
To open an issue, please run: 'az feedback'

	AzurePowerShellCredential
	InteractiveBrowserCredential: object AccessToken can't be used in 'await' expression
	DeviceCodeCredential: object AccessToken can't be used in 'await' expression

Am I missing a step?

@tonybaloney

Copy link
Copy Markdown
Contributor Author

@guenp

Copy link
Copy Markdown

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 2 pipeline(s).

@guenp

Copy link
Copy Markdown

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 2 pipeline(s).

@guenp

Copy link
Copy Markdown

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 2 pipeline(s).

@vxfield
XField (vxfield) self-requested a review August 24, 2021 03:49
@vxfield

Copy link
Copy Markdown
Member

Anthony Shaw (@tonybaloney), could you create a new PR to merge it in the branch feature/aio?
This way Guen and I can apply some final touches before merging this to main.

inherit Async classes from Sync classes
@guenp
Guen Prawiroatmodjo (guenp) changed the base branch from main to feature/aio August 24, 2021 21:16
@guenp

Guen Prawiroatmodjo (guenp) commented Aug 24, 2021 •

Copy link
Copy Markdown

Anthony Shaw (@tonybaloney), I opened a PR here to update this branch with the latest changes from main.
There is still some more work to do after this (e.g. TargetFactory and _TokenCredential) but we can work on that after this is merged into the feature branch.

Guen Prawiroatmodjo (SHE/HER) and others added 2 commits August 24, 2021 17:50

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thank you for the awesome contribution! 🙌

@guenp
Guen Prawiroatmodjo (guenp) merged commit 406b4d7 into microsoft:feature/aio Aug 25, 2021
Guen Prawiroatmodjo (guenp) pushed a commit that referenced this pull request Oct 19, 2021
* 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]>
XField (vxfield) added a commit that referenced this pull request Oct 21, 2021
* 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]>
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.

3 participants