Sebastian Berg
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
      • No invitee
    • Publish Note

      Publish Note

      Everyone on the web can find and read all notes of this public team.
      Once published, notes can be searched and viewed by anyone online.
      See published notes
      Please check the box to agree to the Community Guidelines.
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
No invitee
Publish Note

Publish Note

Everyone on the web can find and read all notes of this public team.
Once published, notes can be searched and viewed by anyone online.
See published notes
Please check the box to agree to the Community Guidelines.
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
1
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
Design space of dispatching and NetworkX lessons ================================================ > Opinionated take-aways and summary by [name=seberg] Types of dispatching -------------------- As a pet-peeve of me (seberg), I would like to point out again that we have two main categories of dispatching (also as nomenclature below): 1. **Type dispatching**: * A system inspects the inputs and uses a different implementation for different types. * Examples: *`np.mean(cupy_array) -> cupy_array`. * `dask_array + numpy_array -> dask_array`. (Python binary ops) * Generally the term "Multiple dispatch". * **NetworkX** uses type dispatching (via it's own mechanism). 2. **Backend selection**: * An *alternative* implementation is provided, which could differ only in the algorithm used (i.e. a different computational backend that with comparable results). * Is *not* just selected based on the types (types could play a role). Rather it is (maybe?) user selected or enabled. * Examples (possible, add NetworkX one): * `process_image(numpy_array, backend="gpu") -> numpy_array` * `with config(backend="gpu"): process_image(image)` * ... Backend selection can encompass type dispatching (if it isn't purely a computational backend, e.g. an alternative algorithm implemented by someone else). However, I am mentioning it since type dispatching has (to me) clearer concepts. Things to consider (learn from NetworkX) beyond dispatching ---------------------------------------- I think there are a few take-aways that NetworkX does very well: * NetworkX modifies the doc strings based on the installed backends. * NetworkX has some additional mechanisms, which may not be relevant for everyone: * A conversion cache since conversion can be slow (in the case of NetworkX attached to the consumed objects). * ... **Implementation takeaway: Entrypoints** If listing possible backends in the docs is desired the use of entry-points is definitely required. NetworkX has two entry-points, one of the backend and one for additional information (optional?). These must *not* do any expensive imports but only define the features provided by the backend. Even if we don't do anything with the docs until import, it seems good to have an entry point to be able to discover what is available? How to do the exact dispatching ------------------------------- **Type dispatching:** 1. **NetworkX** attaches `__networkx_backend__ = backend_name` to the object. I.e. it uses an AbstractType defined via the dunder. (Done on the object, not type, although it shouldn't matter much.) * if backend is missing, an error is raised * Does currently not try to promote between multiple backends. (Raise an error, even if one backend signals it cannot handle it.) 2. You can use "proper" multiple dispatching via `isinstance/issubclass` checks: * If you do not wish to import things, there may be ways to do this: * via `__module__ + __qualname__` (could even walk the mro, but I doubt subclassing is relevant) * Could register at import (e.g. `ABC.register()`), but that requires the object provider to have some code. * Allow users to provide ABC. Can do both of the above, but also e.g. `hasattr("__array_namespace__")` 3. The dunder way of Python operators or `__array_function__`: * Ask each type whether it wants to handle it and let the first that does do. (You might sort subclasses first, which only matters if you are not invariant during dispatch. Array-function isn't, but it is unclear that it is helpful.) 4. The uarray way: * Namespaces of possible implementations which are queried for whether they want to handle a function living in its subnamespace. 5. The "linear" way: Simply loop backends (in some order) and use the first which matches. Another point is whether or not other inputs are taken into account. Many dispatchers (e.g. also NetworkX) does this via a `match` or `can_handle` function. **Backend Selection and prioritization:** Possible ways to do backend selection: * `backend="backend"` during function call. * `dispatchable.invoke(type or backend)(...)` (some multiple dispatchers do this, IIRC). * `backend[API]()` or `backend.API()` may be another way. Or `dispatchable.plugin()` (one example https://github.com/metagraph-dev/metagraph) The additional is enabling a backend/prioritizing it through [context managers](https://github.com/networkx/networkx/pull/7485?notification_referrer_id=NT_kwDN8hmxMTA5NTAxOTY5NDk6NjE5Nzc), which is also something uarray does. Automatic conversion? --------------------- A backend system could provide automatic conversion: * Convert input arguments to the required input type * Automatically convert output arguments back again. The first point is mostly interesting if you allow selecting a backend explicitly. If the user very explicitly selects a CuPy backend, then the input could be converted. * This could be part of the normal conversion, e.g. `cp.asarray()` already allows NumPy arrays. * Could be a hook function to provide a specific converter (seberg: I don't have a good reason for this right now) *NetworkX* (not sure!), doesn't care about converting back again. In general, it assumes all return types are interchangable from a user perspective (quack like a dict of dicts). **Fallback implementation:** By allowing to signal conversion a container would allow falling back to another implementation. In practice, even without this implementing `__array__()` or quacking like a dict-of-dicts may work for many of such fallbacks. Should do/Can do? ----------------- * *NetworkX*: * Backend can be queried for support * Backend can choose not to do something (bad parameters, problem too small) * `__array_function__`: Backend would have to implement the fallback itself. No way to defer to "next" backend. * `uarray`: Can return `NotImplemented` to not match. Additional notes on backend priority? ------------------------------------- When it comes to prioritizing backends the `backend=` approach is very explicit. But other approaches could be e.g. context variables. Even if backends are only registered, if backends do not match very strictly (type invariant), multiple backends could match and the order in which they are tried would matter. There are various approaches that could be used to deal with this: * Require users to specify a lit of all active `backends=[...]` which are tried in order. * Prioritize dispatching for type dispatching: * Requires a type hierarchy. E.g. if a backend works for all `Array API` arrays, `issubclass(np.ndarray, ArrayAPICapable)` is true and a multiple-dispatcher can prioritize. * Warning/error could be given when an order cannot be established (seberg: not sure this is necessary clear at registration time). * The use of a `with` statement could prioritize any backend before all (reorder). * This is also the choice of `uarray`, with issues. (It reordered within namespace scopes so that you have to know at which namespace scope level a backend was registered to know if it would be priorized over another.) * API variations -------------- What type of API strictness do you want to enforce or even explicitly allow passing extra kwargs that are backend specific. NetworkX allows additional kwargs (or even different ones maybe?). This is not common in scikit-image/cucim for example (but unsupport kwarg exists). It has it's own way to pass these to a function. Sometimes cuCim uses different accuracy compared to scikit-image. Introspection capabilities -------------------------- What introspection should exist? A `.plan()` that tells you everything of what _would_ happen. Just being able to `.invoke()` to do the dispatching, or a fetch? If parameters are important

Import from clipboard

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template is not available.
Upgrade
All
  • All
  • Team
No template found.

Create custom template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

How to use Slide mode

API Docs

Edit in VSCode

Install browser extension

Get in Touch

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Upgrade to Prime Plan

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

No updates to save
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Upgrade

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Upgrade

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully