649 Commits

Author SHA1 Message Date
Jake Hillion
9afc1043ef exo: handle -c flag for multiprocessing helpers in frozen apps
When Python's multiprocessing spawns child processes on macOS (using the
"spawn" method), it also spawns helper processes like the resource tracker
by executing:

    ./frozen_app -c "from multiprocessing.resource_tracker import main; main()"

A frozen PyInstaller app doesn't understand `-c` natively - it just runs
main(). This causes the resource tracker to fail silently.

This adds a minimal `-c` handler that intercepts the flag, extracts the
inline code, and exec()s it before main() runs. This is required for the
Process() spawn in runner_supervisor.py to work correctly in the DMG.

Note that the pyinstaller docs say `freeze_support` is supposed to make
this work, but it doesn't.

Test plan:

Hardware setup: 3x Mac Studio M3 Ultra connected all-to-all with TB5

- Built a DMG[0].
- Installed on the Macs.
- Started an instance. Got an error this time in ~/.exo/exo.log. The
  last DMG from main doesn't show anything when an instance starts, this
  now shows the errors.

[0] https://github.com/exo-explore/exo/actions/runs/20464409279/job/58804485197
2025-12-23 17:08:50 +00:00
Evan Quiney
70c423f5e0 feat: conform to XDG Base Directory Specification on Linux (#988)
This is an extension of #964 with some cleanup.

---------

Co-authored-by: majiayu000 <1835304752@qq.com>
2025-12-23 17:02:55 +00:00
Jake Hillion
a24bdf7680 exo: enable multiprocessing support in PyInstaller bundles
Model loading fails silently when running from the DMG-packaged app,
despite working correctly with `uv run exo`. The bundled app spawns
child processes for model inference via multiprocessing, but these
processes fail to start in a frozen (PyInstaller) environment.

Add `freeze_support()` which is required for multiprocessing to work
in frozen applications.

Test plan:

Hardware setup: 3x Mac Studio M3 Ultra connected all-to-all with TB5

- Built a DMG using a modified .github/workflows/build-app.yml[0] to avoid
  publishing it.
- Installed on all 3 Macs, replacing the existing Exo.
- Downloaded Llama 3.3 70B (FP16).
- Downloaded Qwen3 Coder 235B A22B (8-bit).

Things that work now but didn't on the previous app:
- Topology looks good, previously there was no discovery.

What didn't work:
- Started an instance with Pipeline + MLX Ring + 3 Nodes. Failed.
- Started an instance with Tensor + MLX RDMA + 2 Nodes. Failed.

Will continue debugging the instance starting issues separately.

[0] https://github.com/exo-explore/exo/actions/runs/20461320368
2025-12-23 14:34:21 +00:00
Jake Hillion
e8855959c1 build-app: add branch trigger from named branch
As I've been working on the .dmg, it's become clear we need a way to
test changes to the app. It's too hard to reproduce the full DMG locally
to be reasonable and much more convenient to test if it's signed.

Add a feature to the build-app workflow where if you push specifically
to the `test-app` branch it'll perform a build. The version is stubbed
to `0.0.0-alpha.0`, which is about as low as it gets in semver so you'll
always update away from it automatically with Sparkle. The resulting DMG
won't be pushed to S3 but will be uploaded as a GitHub Actions artifact.

I've been using similar commits to this for a while for testing. It's
worked well and not interfered with auto updating at all.

Test plan:
- Pushed this change to `test-app`.
- Generated action at
  https://github.com/exo-explore/exo/actions/runs/20447213358/job/58752909332
- Installed the DMG on a Mac. It worked as intended.
2025-12-23 12:53:30 +00:00
Jake Hillion
0a7fe5d943 ci: migrate build-app to github hosted runners 2025-12-22 19:51:48 +00:00
rltakashige
51a5191ff3 format readme (#978)
## Motivation

README looks weird after last update. 
<!-- Why is this change needed? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here -->

## Changes

<!-- Describe what you changed in detail -->

## Why It Works

<!-- Explain why your approach solves the problem -->

## Test Plan

### Manual Testing
<!-- Hardware: (e.g., MacBook Pro M1 Max 32GB, Mac Mini M2 16GB,
connected via Thunderbolt 4) -->
<!-- What you did: -->
<!-- - -->
I actually checked the file on GitHub this time.

### Automated Testing
<!-- Describe changes to automated tests, or how existing tests cover
this change -->
<!-- - -->
2025-12-22 18:06:27 +00:00
Evan Quiney
1efbd26388 add architecture.md, move images to docs/imgs (#968)
## Motivation

Documentation will make contribution easier and communicate our
development philosophy and decision process. Closes #967

## Changes

Added `architecture.md` to docs/ and moved the images out of docs and
into their own docs/imgs/ folder
2025-12-22 17:57:43 +00:00
Jake Hillion
02c915a88d pyproject: drop pathlib dependency 2025-12-22 17:52:44 +00:00
rltakashige
fc41bfa1f1 Add all prerequisites to README (#975)
## Motivation

Addresses #974 
```
INFO: pip is looking at multiple versions of exo to determine which version is compatible with other requirements. This could take a while.
ERROR: Could not find a version that satisfies the requirement exo-pyo3-bindings (from exo) (from versions: none)
ERROR: No matching distribution found for exo-pyo3-bindings
```

## Changes

Describes Rust dependency for building from source

## Why It Works

<!-- Explain why your approach solves the problem -->

## Test Plan

### Manual Testing
<!-- Hardware: (e.g., MacBook Pro M1 Max 32GB, Mac Mini M2 16GB,
connected via Thunderbolt 4) -->
<!-- What you did: -->
<!-- - -->
Tested locally and runs after this setup without exo-pyo3-bindings error

### Automated Testing
<!-- Describe changes to automated tests, or how existing tests cover
this change -->
<!-- - -->
2025-12-22 17:38:51 +00:00
Jake Hillion
dd0638b74d pyproject: add pyinstaller to dev-dependencies 2025-12-22 15:49:27 +00:00
majiayu000
e06830ce0b fix: update macOS app to use correct API port (52415)
Fixes #960

The macOS app was incorrectly using port 8000 instead of the default
exo API port 52415. This caused confusion as the README correctly
documents port 52415 but the app was connecting to a different port.
2025-12-22 13:24:09 +00:00
Jake Hillion
1df5079b98 ci: avoid pushing alpha build as latest 2025-12-22 13:00:49 +00:00
Nightguarder
1e75aeb2c2 Add Prerequisites to Readme (#936)
## Motivation
Users need to know what **prerequisites** they need in order to run exo.
Simple addition to docs prevents future raised issues.

## Changes

Updated ``README.md``:
- to include installation instructions for
**[uv](https://github.com/astral-sh/uv)** and
**[macmon](https://github.com/vladkens/macmon)**.

Updated ``CONTRIBUTING.md``:
-  to verify these prerequisites are met before starting development.

- Standardized on brew installation instructions for macOS users to keep
the guide simple.

## Why It Works

By listing these prerequisites upfront, users will set up their
environment correctly before attempting to run exo.

## Test Plan

### Manual Testing
MacBook Pro M4
- Verified that ``uv`` and ``macmon`` were missing initially, causing
failures
- after installing them via brew (as documented), uv run exo starts
successfully.

### Automated Testing
<!-- Describe changes to automated tests, or how existing tests cover
this change -->
<!-- - -->

---------

Co-authored-by: Evan Quiney <evanev7@gmail.com>
2025-12-22 02:28:08 +00:00
Heath Dutton🕴️
c582bdd673 bugfix: Handle MacMon errors gracefully 2025-12-22 02:21:29 +00:00
Jake Hillion
1bae8ebbf6 ci: add build-app workflow 2025-12-22 02:12:30 +00:00
Alex Cheema
abaeb0323d Update README.md. (#956)
## Motivation

<!-- Why is this change needed? What problem does it solve? -->
Made a mistake on the merge of the last PR.
<!-- If it fixes an open issue, please link to the issue here -->

## Changes

<!-- Describe what you changed in detail -->

## Why It Works

<!-- Explain why your approach solves the problem -->

## Test Plan

### Manual Testing
<!-- Hardware: (e.g., MacBook Pro M1 Max 32GB, Mac Mini M2 16GB,
connected via Thunderbolt 4) -->
<!-- What you did: -->
<!-- - -->

### Automated Testing
<!-- Describe changes to automated tests, or how existing tests cover
this change -->
<!-- - -->
2025-12-21 23:09:44 +00:00
Alex Cheema
7d15fbdaab readme tweaks5 (#954)
## Motivation

<!-- Why is this change needed? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here -->

## Changes

<!-- Describe what you changed in detail -->

## Why It Works

<!-- Explain why your approach solves the problem -->

## Test Plan

### Manual Testing
<!-- Hardware: (e.g., MacBook Pro M1 Max 32GB, Mac Mini M2 16GB,
connected via Thunderbolt 4) -->
<!-- What you did: -->
<!-- - -->

### Automated Testing
<!-- Describe changes to automated tests, or how existing tests cover
this change -->
<!-- - -->
2025-12-21 22:48:35 +00:00
Alex Cheema
4a6e0fe171 Update README.md. (#949)
## Motivation

<!-- Why is this change needed? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here -->

## Changes

<!-- Describe what you changed in detail -->

## Why It Works

<!-- Explain why your approach solves the problem -->

## Test Plan

### Manual Testing
<!-- Hardware: (e.g., MacBook Pro M1 Max 32GB, Mac Mini M2 16GB,
connected via Thunderbolt 4) -->
<!-- What you did: -->
<!-- - -->

### Automated Testing
<!-- Describe changes to automated tests, or how existing tests cover
this change -->
<!-- - -->
2025-12-21 18:31:23 +00:00
Olimbek Nizomov
f4792dce14 fix(downloads): use certifi for robust SSL certificate verification (#941)
fix(downloads): use certifi for robust SSL certificate verification

## Description
This change updates the SSL context creation in \`download_utils.py\` to
explicitly use the \`certifi\` CA bundle. This ensures that the
application has access to a reliable, up-to-date set of root
certificates, which is critical for verifying SSL connections to
external services like Hugging Face.

## Problem
On macOS environments (and potentially others), Python's default SSL
context often fails to locate the system's root certificates. This leads
to \`aiohttp.client_exceptions.ClientConnectorCertificateError\` errors
when attempting to download models.

## Solution
By passing \`cafile=certifi.where()\` to
\`ssl.create_default_context()\`, we force the application to use the
trusted certificate store provided by the \`certifi\` package. This is a
standard best practice for cross-platform Python applications and
resolves the verification failure.
2025-12-21 12:03:52 +00:00
rltakashige
a1b14a272e Extend eos_token_id fix for other models (#938)
## Motivation

<!-- Why is this change needed? What problem does it solve? -->
We currently use mlx_lm's load_tokenizer instead of load. This means
that some models are missing some configurations, such as eos_token_id.
This is clear for a model like GLM, which does not finish token
generation.

## Changes

<!-- Describe what you changed in detail -->
A small stopgap, to allow eos_token_ids to be added, and a TODO for us
to migrate to load. The reason we don't want to do this now is that a
solid testing framework is not configured in this repo yet.

## Why It Works

<!-- Explain why your approach solves the problem -->
It just uses the eos_token_ids I obtained from loading a tokenizer in
mlx_lm and calling `tokenizer.eos_token_ids` .

## Test Plan

### Manual Testing
Tested on several Macs.

### Automated Testing
None yet, as described.

---------

Co-authored-by: Evan <evanev7@gmail.com>
2025-12-20 20:18:17 +00:00
Alex Cheema
f8483cfc18 Update README.md. (#932)
## Motivation

<!-- Why is this change needed? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here -->

## Changes

<!-- Describe what you changed in detail -->

## Why It Works

<!-- Explain why your approach solves the problem -->

## Test Plan

### Manual Testing
<!-- Hardware: (e.g., MacBook Pro M1 Max 32GB, Mac Mini M2 16GB,
connected via Thunderbolt 4) -->
<!-- What you did: -->
<!-- - -->

### Automated Testing
<!-- Describe changes to automated tests, or how existing tests cover
this change -->
<!-- - -->
2025-12-19 21:23:25 +00:00
Alex Cheema
8bafd6fe68 Update README.md (#925)
## Motivation

<!-- Why is this change needed? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here -->

## Changes

<!-- Describe what you changed in detail -->

## Why It Works

<!-- Explain why your approach solves the problem -->

## Test Plan

### Manual Testing
<!-- Hardware: (e.g., MacBook Pro M1 Max 32GB, Mac Mini M2 16GB,
connected via Thunderbolt 4) -->
<!-- What you did: -->
<!-- - -->

### Automated Testing
<!-- Describe changes to automated tests, or how existing tests cover
this change -->
<!-- - -->
2025-12-19 14:38:40 +00:00
Jake Hillion
f16afd723d nix: get rust build working on linux 2025-12-19 13:51:15 +00:00
Alex Cheema
4da0043253 Update README.md (#917) 2025-12-18 20:38:00 +00:00
Jake Hillion
9e2bdeef92 LICENSE: Fix company name/year 2025-12-18 20:24:44 +00:00
Jake Hillion
379744fe5c exo: open source mac app and build process 2025-12-18 20:06:03 +00:00
Jake Hillion
74bae3ba6d Update README.md 2025-12-18 19:18:59 +00:00
Evan Quiney
9815283a82 8000 -> 52415 (#915)
* 8000 -> 52415

* dont grab the api port for placement

---------

Co-authored-by: rltakashige <rl.takashige@gmail.com>
2025-12-18 18:39:44 +00:00
Evan Quiney
5bd39e84d9 Merge pull request #914 from exo-explore/remove-old-cli-flag
remove old tb_only flag from master
2025-12-18 18:30:45 +00:00
Evan
658cf5ccf9 remove tb_only from master 2025-12-18 17:39:02 +00:00
rltakashige
170d2dcbaf Add Windows as a potential planned platform 2025-12-18 17:33:25 +00:00
Evan Quiney
ba66f14299 Merge pull request #912 from exo-explore/update-dashboard-error-message 2025-12-18 17:12:28 +00:00
Evan
274e35f926 update readme 2025-12-18 17:05:35 +00:00
Evan
3fe7bd250f update error message 2025-12-18 17:02:52 +00:00
Evan
004fea6935 clarify platform support 2025-12-18 16:27:43 +00:00
Evan
5c2d254fd1 add platform support information 2025-12-18 15:45:53 +00:00
Jake Hillion
19ca48c4f1 more readme fixups 2025-12-18 14:47:04 +00:00
Jake Hillion
57d3813692 re-add LICENSE 2025-12-18 14:35:40 +00:00
Evan
7cd1527ce3 update CONTRIBUTING 2025-12-18 14:35:20 +00:00
Evan Quiney
423c066ecc Merge pull request #906 from exo-explore/jj/sluxkvlmwons
re-add logos
2025-12-18 14:29:29 +00:00
Jake Hillion
ebf0e18c0e re-add logos 2025-12-18 14:26:27 +00:00
Evan
28a6151b8e remove discord link from README 2025-12-18 14:02:38 +00:00
Jake Hillion
2c16e00be9 github docs 2025-12-18 13:49:07 +00:00
Jake Hillion
f64d17fac0 exo v1 2025-12-18 13:46:40 +00:00
Jake Hillion
0fcee70833 prep repo for v1 2025-12-17 15:31:02 +00:00
Evan Quiney
09593c5e85 backport the dashboard to staging 2025-12-17 12:22:22 +00:00
Evan Quiney
880a18d205 fix disconnects
Co-authored-by: Ryuichi Leo Takashige <leo@exolabs.net>
2025-12-15 15:23:13 +00:00
rltakashige
70298ce0a9 Negative index nack request 2025-12-09 07:57:28 -08:00
Jake Hillion
ac3a0a6b47 ci: enable ruff check in CI through nix 2025-12-09 12:26:56 +00:00
rltakashige
859233a279 Reduce RequestEventLog spam 2025-12-09 11:43:54 +00:00
Evan Quiney
c9e2062f6e switch from uvicorn to hypercorn 2025-12-05 17:29:06 +00:00
Jake Hillion
e8566a3f95 placement: pass different ibv_coordinator per node 2025-12-05 17:23:22 +00:00
Jake Hillion
39d76aa0a5 nix: move formatting checks to nix and enable in ci 2025-12-05 17:00:33 +00:00
Jake Hillion
5629983809 fmt: format all python/rust/nix files 2025-12-05 16:58:55 +00:00
Evan Quiney
7312a7e000 plan fix 2025-12-05 16:43:11 +00:00
Evan Quiney
9e0a1c23ef rename ibv to jaccl inline with mlx 2025-12-05 16:42:43 +00:00
Evan Quiney
f5783d6455 proper collection of rdma ports in placement 2025-12-05 16:42:20 +00:00
Evan Quiney
e702313b32 pingers
Co-authored-by: Jake Hillion <jake@hillion.co.uk>
2025-12-05 16:41:19 +00:00
Evan
a3f8ecba9e prioritise LL4 2025-12-05 15:08:18 +00:00
Jake Hillion
5ef1df1e10 rust: move Cargo.toml to the root 2025-12-05 12:01:44 +00:00
Evan
40a0d47de8 jaccl 2025-12-03 13:53:12 +00:00
rltakashige
2b243bd80e Consolidate!!! Fixes 2025-12-03 12:19:25 +00:00
Evan Quiney
10c905c8dd worker no longer gets stuck after shutdown 2025-12-02 11:35:02 +00:00
Evan
93f699b660 add aarch64-linux for the spark 2025-11-28 11:08:18 +00:00
Alex Cheema
b43d30563d todo for layer-independent parameters in get_allow_patterns 2025-11-27 19:26:02 +00:00
Alex Cheema
20d73e90cd fix dashboard case sensitive model id 2025-11-26 18:16:32 +00:00
Alex Cheema
e56daa7c23 render download progress properly 2025-11-26 11:48:30 +00:00
Alex Cheema
63c85e1298 get rid of spammy Finished tokenizing log 2025-11-25 13:02:06 +00:00
Evan
7088988a65 bump pyo3 stub-gen 2025-11-25 12:13:53 +00:00
rltakashige
7b3e3fd66c Worker tests 2 2025-11-21 16:42:52 +00:00
rltakashige
de50811313 Worker tests on staging 1
Test plan
2025-11-21 15:22:40 +00:00
rltakashige
b45cbdeecd Consolidate cleanup 2025-11-21 14:54:02 +00:00
rltakashige
28a91787e8 Demo
Co-authored-by: Evan <evanev7@gmail.com>
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
2025-11-20 20:03:51 +00:00
Alex Cheema
d793f5f96c fix kimi eos token ids 2025-11-13 18:39:14 +00:00
Evan Quiney
b62f68474a improved master error handling
Co-authored-by: Ryuichi Leo Takashige <rl.takashige@gmail.com>
2025-11-11 18:04:40 +00:00
Alex Cheema
631cb81009 kimi k2 thinking 2025-11-11 18:03:39 +00:00
Evan Quiney
364087b91f five billion percent better shutdown handling 2025-11-11 17:43:53 +00:00
Evan Quiney
aa519b8c03 Worker refactor
Co-authored-by: rltakashige <rl.takashige@gmail.com>
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
2025-11-10 23:31:53 +00:00
Alex Cheema
9058b117c0 pipeline parallel fix 2025-11-08 02:19:19 +00:00
rltakashige
612f58c78d Revert dumb merge mistake 2025-11-07 02:39:08 +00:00
Evan
6bcac37d98 stop benching on all pushes 2025-11-06 22:26:30 +00:00
rltakashige
ff00b165c5 MLX LM type stubs 2025-11-06 21:59:29 +00:00
Alex Cheema
19e90572e6 set max_transmit_size on gossipsub to 1MB. Fixes large message erorr 2025-11-06 19:18:48 +00:00
Alex Cheema
e60681963f show ips on dashboard 2025-11-06 19:18:07 +00:00
rltakashige
0bb621b653 Add mlx nn stubs 2025-11-06 11:59:37 +00:00
Alex Cheema
699fd9591e fix exo scripts 2025-11-05 21:47:08 -08:00
rltakashige
6bbb6344b6 mlx.distributed.Group type stubs 2025-11-06 05:26:04 +00:00
rltakashige
16f724e24c Update staging 14
Co-authored-by: Evan <evanev7@gmail.com>
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
Co-authored-by: David Munha Canas Correia <dmunha@MacBook-David.local>
Co-authored-by: github-actions bot <github-actions@users.noreply.github.com>
2025-11-05 01:44:24 +00:00
Evan Quiney
3b409647ba Squash merge merging_clusters into tensor_parallel94 2025-10-31 17:41:57 +00:00
Alex Cheema
d46c7e6a76 fix race condition with downloads where it cancels the download before renaming 2025-10-30 19:03:23 -07:00
rltakashige
91c635ca7a Update mlx and mlx-lm packages
Co-authored-by: Evan <evanev7@gmail.com>
2025-10-31 01:34:43 +00:00
Alex Cheema
5f18faec17 Update. 2025-10-30 11:59:59 -07:00
Alex Cheema
a346af3477 download fixes 2025-10-22 11:56:52 +01:00
Alex Cheema
56f783b38d Update. 2025-10-21 17:29:48 +01:00
Evan Quiney
363c98a872 leaf placement
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
2025-10-15 12:47:26 +01:00
Evan Quiney
f25689d9c2 fix a race condition 2025-10-15 10:49:53 +01:00
Evan Quiney
1c6b5ce911 new tagged union
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
Sorry Andrei!
2025-10-10 16:22:09 +01:00
Alex Cheema
76ed8a516b typecheck on ubuntu with install-nix-action
Co-authored-by: Evan <evanev7@gmail.com>
2025-10-10 16:15:39 +01:00
Evan Quiney
e8a6efe281 add kimi k2 2025-10-07 17:17:06 +01:00
Evan Quiney
a4e8335241 add just clean 2025-10-07 16:29:51 +01:00
Alex Cheema
84dfc8a738 Fast memory profiling
Co-authored-by: Evan <evanev7@gmail.com>
2025-10-07 16:23:51 +01:00
Alex Cheema
e01f9cf739 Disable build macos app 2025-10-07 15:39:15 +01:00
Alex Cheema
35ab6b376e fix: master tests
Co-authored-by: Evan <evanev7@gmail.com>
2025-10-07 15:36:05 +01:00
Evan Quiney
962e5ef40d version bump for brew consistency 2025-10-07 15:18:54 +01:00
Evan Quiney
b1721e941b nix cleanup 2025-10-01 09:47:00 +01:00
Evan Quiney
22f0ca2a59 FIX: OpenWebUI compat 2025-09-30 16:28:38 +01:00
Evan Quiney
57486a4305 kill go
Fairwell Gelu, Chief Lunch Officer
2025-09-30 11:10:55 +01:00
Evan Quiney
38ff949bf4 big refactor
Fix. Everything.

Co-authored-by: Andrei Cravtov <the.andrei.cravtov@gmail.com>
Co-authored-by: Matt Beton <matthew.beton@gmail.com>
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
Co-authored-by: Seth Howes <sethshowes@gmail.com>
2025-09-30 11:03:04 +01:00
Matt Beton
7040c9508f Multiprocessing Runner 2025-09-17 09:31:49 +01:00
Matt Beton
35c4311587 Dashboard Status & Bugfixes 2025-08-29 17:34:17 +01:00
Matt Beton
a33787f5fd Prompt length 2025-08-29 16:07:36 +01:00
Matt Beton
1b8b456ced full mlx caching implementation 2025-08-26 17:15:08 +01:00
Matt Beton
84c90a6d35 feat: mlx memory cache for faster ttft
Co-authored-by: Evan <evanev7@gmail.com>
Co-authored-by: s17 <s17@s17s-Mac-Studio.local>
2025-08-26 13:05:42 +01:00
Evan Quiney
5efe5562d7 feat: single entrypoint and logging rework 2025-08-26 11:08:09 +01:00
Andrei Cravtov
ef5c5b9654 changes include: ipc, general utilities, flakes stuff w/ just, autopull script 2025-08-25 17:33:40 +01:00
Alex Cheema
5bfc99b415 add EXO logo to dashboard 2025-08-25 16:41:13 +01:00
Evan Quiney
11f8b4ef33 tidy: fix justfile, run.sh, run formatter 2025-08-21 18:44:53 +01:00
Evan Quiney
be6f5ae7f1 feat: build system and homebrew compatibility 2025-08-21 16:07:37 +01:00
Evan Quiney
40efed4436 unvendored macmon 2025-08-20 13:04:46 +01:00
Gelu Vrabie
ea9e573409 Refactor runner supervisor
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-08-18 18:37:52 +01:00
Gelu Vrabie
345fafd80d Forwarder versioning
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-08-18 15:08:50 +01:00
Evan Quiney
ea3eeea826 improved go caching with nix
Co-authored-by: Gelu Vrabie <gelu.vrabie.univ@gmail.com>
2025-08-15 15:24:58 +01:00
Gelu Vrabie
a2a37c0ebe discovery fixed
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-08-15 15:23:20 +01:00
Gelu Vrabie
57073f35c3 collection of fixes for Shanghai demo
Co-authored-by: Matt Beton <matthew.beton@gmail.com>
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-08-15 15:21:51 +01:00
Andrei Cravtov
7e19804aa5 Integrate flake parts 2025-08-13 09:55:22 +01:00
Matt Beton
dbcd09aa53 No 70b 2025-08-12 18:42:27 +01:00
Matt Beton
c1d5b381f4 70B model unit test only runs if its downloaded 2025-08-07 10:41:56 +01:00
Alex Cheema
473512ddd0 r1 size 2025-08-04 22:57:31 +08:00
Alex Cheema
817c5993f0 fix dem model cards yo 2025-08-04 22:56:06 +08:00
Gelu Vrabie
75ecda55a9 fix gitignore
Co-authored-by: Matt Beton <matthew.beton@gmail.com>
2025-08-04 13:49:49 +01:00
Alex Cheema
c560c55c4e build and release on staging 2025-08-04 07:41:09 +08:00
Sami Khan
f51f8f72f8 app launches python modules 2025-08-04 06:18:31 +08:00
Seth Howes
407796d18f Minor dashboard fixes 2025-08-04 06:15:01 +08:00
Alex Cheema
6daf7f31f7 clean model cards 2025-08-04 05:31:30 +08:00
Alex Cheema
f352ddfc5f run configure_mlx.sh in run.sh 2025-08-04 03:59:42 +08:00
Alex Cheema
6855a7727d set a 15 sec timeout for getting initial download progress 2025-08-03 20:37:20 +08:00
Matt Beton
1fe4ed3442 Worker Exception & Timeout Refactor
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
Co-authored-by: Seth Howes <sethshowes@gmail.com>
2025-08-02 08:28:37 -07:00
Alex Cheema
92c9688bf0 Remove rust 2025-08-02 08:16:39 -07:00
Sami Khan
a46f8c3cd1 app
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
2025-08-01 19:14:27 -07:00
Seth Howes
71bafabc63 Dashboard with instances 2025-08-01 14:38:07 +01:00
Gelu Vrabie
0e32599e71 fix libp2p + other prs that were wrongly overwritten before (111,112,117,118,1119 + misc commits from Alex)
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
Co-authored-by: Alex Cheema <41707476+AlexCheema@users.noreply.github.com>
Co-authored-by: Seth Howes <71157822+sethhowes@users.noreply.github.com>
Co-authored-by: Matt Beton <matthew.beton@gmail.com>
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
2025-07-31 20:36:47 +01:00
Alex Cheema
2031d9481d fix api get_state 2025-07-30 07:15:15 -07:00
Matt Beton
b350ededb2 Test Supervisor Errors. 2025-07-30 13:30:54 +01:00
Gelu Vrabie
ff3d11c748 just run
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-29 16:58:27 +01:00
Gelu Vrabie
25fa46c6f6 Update CODEOWNERS 2025-07-29 13:08:29 +01:00
Seth Howes
3f192f20cc Reinstate dashboard 2025-07-28 23:18:23 +01:00
Alex Cheema
a2b4093d25 add metrics: gpu_usage, temp, sys_power, pcpu_usage, ecpu_usage, ane_… 2025-07-28 23:02:33 +01:00
Alex Cheema
12566865d5 better profiling 2025-07-28 22:15:04 +01:00
Gelu Vrabie
b88abf1cc2 fix topology disconnects and add heartbeat
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-28 22:00:05 +01:00
Alex Cheema
dbd0bdc34b fix ci linter 2025-07-28 20:12:48 +01:00
Alex Cheema
20241e3290 some finishing touches to get this working e2e 2025-07-28 13:07:29 +01:00
Seth Howes
176d077c87 Fix IPv4 serialisation for topology 2025-07-28 13:07:10 +01:00
Gelu Vrabie
c3c8ddbce8 fix forwarder supervisor tests
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-28 13:03:43 +01:00
Matt Beton
36a5d75efd Fix download tests 2025-07-28 12:51:10 +01:00
Seth Howes
e9b803604b Add Multiaddr type and refactor Hosts type for creating shard placement 2025-07-28 11:39:46 +01:00
Alex Cheema
b285a9f0b7 fix placement tests 2025-07-28 11:18:32 +01:00
Alex Cheema
57ca487fde Fixes for running this end to end
Co-authored-by: Gelu Vrabie <gelu.vrabie.univ@gmail.com>
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-28 10:51:03 +01:00
Andrei Cravtov
b687dec6b2 Discovery integration master
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
2025-07-27 13:43:59 +01:00
Alex Cheema
98f204d14a Fix placement single node 2025-07-26 20:08:37 +01:00
Matt Beton
93330f0283 Inference Integration Test
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
2025-07-26 20:08:25 +01:00
Gelu Vrabie
2e4635a8f5 add node started event
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-26 19:12:26 +01:00
Gelu Vrabie
261e575262 Serialize topology
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-25 15:09:03 +01:00
Alex Cheema
a97fb27c64 Glue TWO 2025-07-25 14:32:34 +01:00
Gelu Vrabie
9be08ec7dd add resource monitor
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-25 13:10:53 +01:00
Alex Cheema
a241c92dd1 Glue 2025-07-25 13:10:29 +01:00
Seth Howes
6f8e3419d5 Placement strategy
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
2025-07-24 20:22:40 +01:00
Gelu Vrabie
4c0e4ef853 Go build
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-24 19:45:45 +01:00
Matt Beton
f41531d945 Worker Loop
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
2025-07-24 18:44:31 +01:00
Alex Cheema
67c70b22e4 Best master 2025-07-24 17:12:52 +01:00
Andrei Cravtov
3730160477 Fix the node-ID test
Co-authored-by: Matt Beton <matthew.beton@gmail.com>
2025-07-24 17:09:12 +01:00
Gelu Vrabie
df1fe3af26 Topology apply
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-24 14:27:09 +01:00
Matt Beton
5097493a42 Fix tests 2025-07-24 13:22:58 +01:00
Alex Cheema
a6b3ab6332 Worker plan
Co-authored-by: Matt Beton <matthew.beton@gmail.com>
Co-authored-by: Seth Howes <71157822+sethhowes@users.noreply.github.com>
Co-authored-by: Gelu Vrabie <gelu.vrabie.univ@gmail.com>
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
Co-authored-by: Andrei Cravtov <the.andrei.cravtov@gmail.com>
Co-authored-by: Seth Howes <sethshowes@gmail.com>
2025-07-24 12:45:27 +01:00
Gelu Vrabie
56d3565781 Add apply functions
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-24 11:02:20 +01:00
Andrei Cravtov
3ab5609289 wrote race-condition-free persistent NodeID-getting function 2025-07-23 20:18:56 +01:00
Matt Beton
7a452c3351 Fix tests 2025-07-23 18:25:50 +01:00
Seth Howes
7ac23ce96b Refactor tasks / commands / api 2025-07-23 15:52:29 +01:00
Andrei Cravtov
81060b7062 Made basedpyright work with Jetbrains environment
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
Co-authored-by: Seth Howes <sethshowes@gmail.com>
Co-authored-by: Matt Beton <matthew.beton@gmail.com>
2025-07-23 14:12:11 +01:00
Andrei Cravtov
8d2536d926 Implemented basic discovery library in Rust + python bindings
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
Co-authored-by: Seth Howes <sethshowes@gmail.com>
Co-authored-by: Matt Beton <matthew.beton@gmail.com>
2025-07-23 13:11:29 +01:00
Gelu Vrabie
76f903504c fix
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-22 22:29:35 +01:00
Seth Howes
cd9a1a9192 Topology update 2025-07-22 22:29:17 +01:00
Matt Beton
14b3c4a6be New API! 2025-07-22 21:21:12 +01:00
Gelu Vrabie
596d9fc9d0 add forwarder service
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-22 20:53:26 +01:00
Matt Beton
53c652c307 Fix tests! 2025-07-22 15:20:32 +01:00
Matt Beton
5adad08e09 New events 2025-07-22 15:16:06 +01:00
Gelu Vrabie
108128b620 fix sqlite connector
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-21 22:43:09 +01:00
Alex Cheema
449fdac27a Downloads 2025-07-21 22:42:37 +01:00
Seth Howes
cb101e3d24 Refactor model types 2025-07-21 20:35:27 +01:00
Gelu Vrabie
54efd01d77 add forwarder supervisor
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-21 20:21:43 +01:00
Seth Howes
bae58dd368 Refactor worker + master state into single state 2025-07-21 19:36:54 +01:00
Seth Howes
d19aa4f95a Simplify Task type + merge control & data plane types into single type 2025-07-21 17:10:09 +01:00
Gelu Vrabie
2f64e30dd1 Add sqlite connector
Co-authored-by: Gelu Vrabie <gelu@exolabs.net>
2025-07-21 14:10:29 +01:00
Alex Cheema
bb7f1ae994 New worker
Co-authored-by: Matt Beton <matthew.beton@gmail.com>
2025-07-18 10:08:56 +01:00
Matt Beton
cc45c7e9b9 Fixed events issue. 2025-07-17 12:21:01 +01:00
Arbion Halili
038cc4cdfa fix: Normalize Naming 2025-07-16 16:11:51 +01:00
Arbion Halili
e2a7935019 fix: Fix incorrect logic 2025-07-16 14:39:20 +01:00
Arbion Halili
6a671908a3 fix: FrozenSet Related Bits 2025-07-16 13:45:57 +01:00
Arbion Halili
520b1122a3 fix: Many Fixes 2025-07-16 13:35:31 +01:00
Arbion Halili
d9b9aa7ad2 Merge branch 'master-node' into staging 2025-07-15 16:32:08 +01:00
Arbion Halili
7fa7de8e83 more incomplete trash 2025-07-15 13:42:17 +01:00
Arbion Halili
9f96b6791f fix: Some, still broken 2025-07-15 13:11:21 +01:00
Arbion Halili
9b3c105bea fix: Save Andrei's sanity 2025-07-15 13:11:20 +01:00
Arbion Halili
8060120136 tweak 2025-07-14 22:37:53 +01:00
Arbion Halili
df6626fa31 fix: Event definitions, state definitions 2025-07-14 21:41:14 +01:00
Arbion Halili
70f0f09c05 Tweaked, Still Broken tho 2025-07-14 21:19:39 +01:00
Arbion Halili
8799c288b0 BROKEN: work thus far 2025-07-14 21:09:08 +01:00
Arbion Halili
4e4dbf52ec fix: Use Nix-compatible LSP set-up 2025-07-14 21:08:43 +01:00
Matt Beton
21acd3794a New Runner! 2025-07-10 16:34:35 +01:00
Arbion Halili
b0bd951005 Merge Basic Interfaces
Co-authored-by: Alex Cheema <alexcheema123@gmail.com>
Co-authored-by: Seth Howes <sethshowes@gmail.com>
Co-authored-by: Matt Beton <matthew.beton@gmail.com>
Co-authored-by: Andrei Cravtov <the.andrei.cravtov@gmail.com>
2025-07-09 19:04:21 +01:00
Arbion Halili
74d56e52ff fix: Improve naming 2025-07-07 20:22:27 +01:00
Arbion Halili
fe17aaf9f8 fix: Make master hold a queue of task data 2025-07-07 20:22:00 +01:00
Arbion Halili
e1894bc106 refactor: A Lot 2025-07-07 20:19:08 +01:00
Arbion Halili
81cf6bce64 refactor: Simplify networking 2025-07-07 19:33:14 +01:00
Andrei Cravtov
6c8b8b30ae added rust to flake 2025-07-07 18:11:40 +01:00
Matt Beton
0425422f55 Simple fix 2025-07-07 17:18:43 +01:00
Matt Beton
03a1cf59a6 Matt's interfaces
Added interfaces for chunks, worker, runner, supervisor, resourcemonitor, etc.
2025-07-07 16:42:52 +01:00
Arbion Halili
367e76c8fa fix: Fix validation over Task types 2025-07-04 17:25:14 +01:00
Arbion Halili
cda3de2a28 fix: Use state for tasks 2025-07-04 15:08:54 +01:00
Arbion Halili
10224d09de refactor: Distinguish the topology of the control plane from that of the data plane 2025-07-03 15:45:54 +01:00
Arbion Halili
c456934342 refactor: Remove timestamp from Wrapped Events 2025-07-03 13:05:35 +01:00
Arbion Halili
0b6aadf576 refactor: Add safe state mutation method .apply() 2025-07-03 12:33:29 +01:00
Arbion Halili
f8039e20e0 feature: Add pretty_name to ModelMetadata 2025-07-03 12:32:32 +01:00
Arbion Halili
4bb3a995a4 feature: Interfaces for graph interfaces 2025-07-02 22:44:55 +01:00
Arbion Halili
7dd8a979d2 feature: Simplest utilities for logging 2025-07-02 22:13:42 +01:00
Arbion Halili
40793f1d86 refactor: Refactor most things 2025-07-02 21:11:49 +01:00
Arbion Halili
8596d5c5b1 refactor: Fix UUID implementation 2025-07-02 11:04:52 +01:00
Arbion Halili
6de1f2883f feat: Update Interfaces 2025-07-01 18:41:37 +01:00
Arbion Halili
73ac8969bc feat: Add ResourceGraph, runner types, etc. 2025-07-01 13:14:26 +01:00
Arbion Halili
df824e2e87 fix: Ensure MasterState inherits from SharedState 2025-07-01 12:18:54 +01:00
Seth Howes
d5033e658c refactor: Replace Literal with Enum in sources.py 2025-07-01 12:15:28 +01:00
Arbion Halili
c0df8e5463 feat: Implement Many Interfaces 2025-07-01 01:37:00 +01:00
Arbion Halili
899d8820dd Merge Seth's Control Plane API Work into Alex's Events Branch
Co-authored-by: Seth Howes <sethshowes@gmail.com>
2025-06-30 23:54:41 +01:00
Arbion Halili
53d5d23898 refactor: Use enums 2025-06-30 23:45:27 +01:00
Arbion Halili
b758df83cf Chore: Tweak CI 2025-06-30 22:41:33 +01:00
Alex Cheema
133ab70d67 chore: Run formatter 2025-06-30 09:48:03 +01:00
Alex Cheema
aae3e4a82d refactor: Put type defs on one line 2025-06-30 09:46:44 +01:00
Alex Cheema
596b069f84 chore: Fail pipeline if working tree changes instead of committing them in CI 2025-06-30 09:40:47 +01:00
Alex Cheema
c0b8bb9c98 chore: Rename conditional-commit.yml to action.yml 2025-06-29 22:34:04 +01:00
Alex Cheema
0c46adc298 refactor: Use official OpenAI types 2025-06-29 22:30:18 +01:00
Alex Cheema
4b3e60f899 refactor: Add types for model downloading 2025-06-29 21:59:06 +01:00
Alex Cheema
784f0ec423 chore: Skip protobuf generation if no .proto files exist 2025-06-29 21:52:46 +01:00
Alex Cheema
38dcf698eb chore: Fix typecheck job in GitHub workflow 2025-06-29 21:47:23 +01:00
Alex Cheema
c9d44a1658 chore: Fix typecheck job in GitHub workflow 2025-06-29 21:45:41 +01:00
Alex Cheema
bbdfdac7be refactor: Remove redundant comment 2025-06-29 21:42:00 +01:00
Alex Cheema
5ba230ed16 refactor: Add all event types with Event implementations 2025-06-29 21:41:00 +01:00
Arbion Halili
5abf03e31b Scaffold Event Sourcing 2025-06-29 19:44:58 +01:00
Arbion Halili
d8459358cf Refactor CI 2025-06-28 14:42:53 +01:00
Arbion Halili
c977ce9419 Ensure exo-shared is a Dependency of exo-master and exo-worker 2025-06-28 14:34:49 +01:00
Arbion Halili
74adbc4280 Remove PoeThePoet 2025-06-28 14:33:01 +01:00
Arbion Halili
587a52a944 Remove Bad UUID Implementation 2025-06-28 14:08:18 +01:00
Arbion Halili
885c7d5cd8 Add RULES.md and .cursorrules 2025-06-28 14:03:01 +01:00
Arbion Halili
e4c4b3e95a Overhaul CI Design 2025-06-28 12:29:01 +01:00
Arbion Halili
f7f779da19 Fix Type Checker; Improve Protobuf Generation 2025-06-28 12:28:26 +01:00
Arbion Halili
38bc8ea7e4 Keep Protobuf Directories 2025-06-28 01:32:10 +01:00
Arbion Halili
b53c1ba999 Use Hatch Build System 2025-06-28 01:28:52 +01:00
Arbion Halili
423efe10b8 Add Protobuf Support 2025-06-28 01:27:25 +01:00
Arbion Halili
61b8b1cb18 Add Protobuf Support 2025-06-28 01:26:49 +01:00
Arbion Halili
7f0f71b9eb Add .gitignore 2025-06-28 01:25:51 +01:00
Arbion Halili
da50da2b43 Add Simple env.py 2025-06-27 11:57:03 +01:00
Arbion Halili
3564d77e58 Add Sync to Runner 2025-06-27 11:56:02 +01:00
Arbion Halili
77546b951e Update pyproject.toml 2025-06-17 22:28:48 +01:00
Arbion Halili
c15e402f3b Add Simple Groundwork 2025-06-17 22:23:01 +01:00
Arbion Halili
c57ed32fc5 Add Initial Contribution Rules 2025-06-17 16:11:15 +01:00
Arbion Halili
41085eef7b Prepare Environment Parser 2025-06-17 16:10:58 +01:00
Arbion Halili
685c8eff58 Configure Runner Tasks to Cover "engines/" 2025-06-17 07:37:08 +01:00
Arbion Halili
13b6043c09 Add Linter 2025-06-17 07:32:33 +01:00
Arbion Halili
180748ee83 Update Workspace Configuration, Configure Build Backend 2025-06-17 06:45:25 +01:00
Arbion Halili
043253a55d Add ML Engines (Backend) 2025-06-17 05:55:43 +01:00
Arbion Halili
090265a374 Add Formatter To CI 2025-06-17 05:46:33 +01:00
Arbion Halili
e2508f3419 Add Type Checker In CI 2025-06-17 05:46:08 +01:00
Arbion Halili
ac2dfa6565 Initial Structure 2025-06-17 03:55:41 +01:00
Alex Cheema
db1a5252a2 Add CODEOWNERS. 2025-06-14 23:32:30 -07:00
Alex Cheema
e4238f9ef3 Merge pull request #800 from exo-explore/grpcio1.71.0
downgrade grpcio, grpcio-tools to 1.70.0
2025-03-21 15:23:32 -07:00
Alex Cheema
ad3bc6ceaa downgrade grpcio, grpcio-tools to 1.70.0 2025-03-21 15:23:11 -07:00
Alex Cheema
04d5dca18f Merge pull request #778 from exo-explore/grpcio1.71.0
upgrade grpcio and grpcio-tools to 1.71.0
2025-03-12 06:24:57 +00:00
Alex Cheema
50b6800a61 m3 ultra flops estimates based on some quick profiling 2025-03-11 22:51:23 -07:00
Alex Cheema
2857975bf3 upgrade grpcio and grpcio-tools to 1.71.0 2025-03-11 17:23:37 -07:00
Alex Cheema
854f515cf5 Merge pull request #763 from deftdawg/amdgpu
AMD/ROCm: Changes required to detect and inference on AMD GPUs
2025-03-06 16:07:05 +00:00
DeftDawg
f98d9bac53 Changes required to detect AMD GPUs 2025-03-05 22:49:29 -05:00
Alex Cheema
017bf93cf5 Merge pull request #753 from mags0ft/patch-1
remove dead links in README
2025-03-03 23:01:34 +00:00
mags0ft
013d2573e7 remove dead links in README 2025-03-02 18:37:59 +01:00
Alex Cheema
2702975762 Merge pull request #746 from exo-explore/grpcio1.70.0
downgrade grpc to 1.67.0. waiting for fix
2025-02-28 21:26:11 +00:00
Alex Cheema
30c3f58a00 downgrade grpc to 1.67.0. waiting for fix bd8f8a86e0 2025-02-28 21:25:11 +00:00
Alex Cheema
1bbbb1e1d8 Merge pull request #745 from exo-explore/grpcio1.70.0
Grpcio1.70.0
2025-02-28 21:05:41 +00:00
Alex Cheema
4081305e60 adjust grpc settings, ensure connected before sending any grpc commands 2025-02-28 20:52:12 +00:00
Alex Cheema
52a21645c6 Merge pull request #742 from samiamjidkhan/main
build fix
2025-02-28 12:29:58 +00:00
Sami Khan
63570c7b8b Merge pull request #1 from samiamjidkhan/build-fix
build fix
2025-02-28 15:47:36 +05:00
Sami Khan
971f5240bf build fix 2025-02-28 15:45:57 +05:00
Alex Cheema
36a6389af0 bump grpcio and grpcio-tools to 1.70.0 2025-02-27 01:40:04 +00:00
Alex Cheema
af734f1bf6 Merge pull request #737 from exo-explore/handlegzipdownload
handle -gzip suffix in etag for integrity check fixes #633
2025-02-25 22:10:05 +00:00
Alex Cheema
ee095766d9 handle -gzip suffix in etag for integrity check fixes #633 2025-02-25 22:08:15 +00:00
Alex Cheema
a605e233ad Merge pull request #709 from exo-explore/notice
update notice in README
2025-02-18 11:43:14 +00:00
Alex Cheema
f9a1e5342b update notice in README 2025-02-18 11:41:09 +00:00
Alex Cheema
7a374a74cd Merge pull request #708 from exo-explore/notice
add notice to README
2025-02-17 22:55:44 +00:00
Alex Cheema
5a00899d73 Merge pull request #705 from cadenmackenzie/addingModelNameInputContainer
adding current model name to input container information
2025-02-17 22:55:29 +00:00
Alex Cheema
cb4bee2694 add notice to README 2025-02-17 22:54:56 +00:00
Caden MacKenzie
9078d094b9 adding current model name to input container information 2025-02-16 18:34:38 -08:00
Alex Cheema
ed70d47cfd Merge pull request #702 from exo-explore/alwayslogdownloaderror
make max_parallel_downloads configurable, increase download chunk size to 8MB
2025-02-14 21:27:12 +00:00
Alex Cheema
477e3a5e4c make max_parallel_downloads configurable, increase download chunk size to 8MB 2025-02-14 21:26:41 +00:00
Alex Cheema
be3b9ee973 Merge pull request #698 from exo-explore/alwayslogdownloaderror
always log download errors. some people e.g cant access huggingface
2025-02-13 22:56:33 +00:00
Alex Cheema
b4e6f8acad always log download errors. some people eg cant access huggingface which causes confusion 2025-02-13 22:55:09 +00:00
Alex Cheema
de99da7c75 Merge pull request #684 from divinity76/patch-1
workaround f16 cast ambiguity
2025-02-08 12:45:10 +00:00
Alex Cheema
76d1bd95f5 Merge pull request #688 from exo-explore/readmeupdate
apt-get debian noninteractive in circleci
2025-02-08 02:41:19 +00:00
Alex Cheema
928214d479 apt-get debian noninteractive in circleci 2025-02-08 02:40:51 +00:00
Alex Cheema
ce34a886c2 Merge pull request #687 from exo-explore/readmeupdate
README updates
2025-02-08 02:15:50 +00:00
Alex Cheema
d8c3aed0cc update discovery / peer networking modules 2025-02-08 02:15:13 +00:00
Alex Cheema
2c982d9295 update README to better reflect support for other devices like NVIDIA and Pi's 2025-02-08 02:13:04 +00:00
divinity76
5fe241ec61 code-breaking typo
oops
2025-02-06 19:02:02 +01:00
divinity76
05ff20fa89 workaround f16 cast ambiguity
for unknown reasons, without this, when trying to execute "Llama 3.2 1B", I get the error below. Fwiw I do not know the performance impact for this change. I can't even get exo running, but this change allows me to /get further/ (before running into a second issue with vram allocation? story for another day i suppose)


error: 
Failed to fetch completions: Error processing prompt (see logs with DEBUG>=2): Nvrtc Error 6, NVRTC_ERROR_COMPILATION
<null>(18): error: more than one user-defined conversion from "nv_bfloat16" to "half" applies:
            function "__half::__half(float)" (declared at line 214 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(short)" (declared at line 227 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned short)" (declared at line 228 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(int)" (declared at line 229 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned int)" (declared at line 230 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(long long)" (declared at line 231 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned long long)" (declared at line 232 of /usr/include/cuda_fp16.hpp)
    *((half4*)((data0+(alu0+(gidx1<<14)+(lidx0<<11)+alu1)))) = make_half4(((half)(val0)),((half)(val1)),((half)(val2)),((half)(val3)));
                                                                                 ^

<null>(18): error: more than one user-defined conversion from "nv_bfloat16" to "half" applies:
            function "__half::__half(float)" (declared at line 214 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(short)" (declared at line 227 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned short)" (declared at line 228 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(int)" (declared at line 229 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned int)" (declared at line 230 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(long long)" (declared at line 231 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned long long)" (declared at line 232 of /usr/include/cuda_fp16.hpp)
    *((half4*)((data0+(alu0+(gidx1<<14)+(lidx0<<11)+alu1)))) = make_half4(((half)(val0)),((half)(val1)),((half)(val2)),((half)(val3)));
                                                                                                ^

<null>(18): error: more than one user-defined conversion from "nv_bfloat16" to "half" applies:
            function "__half::__half(float)" (declared at line 214 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(short)" (declared at line 227 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned short)" (declared at line 228 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(int)" (declared at line 229 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned int)" (declared at line 230 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(long long)" (declared at line 231 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned long long)" (declared at line 232 of /usr/include/cuda_fp16.hpp)
    *((half4*)((data0+(alu0+(gidx1<<14)+(lidx0<<11)+alu1)))) = make_half4(((half)(val0)),((half)(val1)),((half)(val2)),((half)(val3)));
                                                                                                               ^

<null>(18): error: more than one user-defined conversion from "nv_bfloat16" to "half" applies:
            function "__half::__half(float)" (declared at line 214 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(short)" (declared at line 227 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned short)" (declared at line 228 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(int)" (declared at line 229 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned int)" (declared at line 230 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(long long)" (declared at line 231 of /usr/include/cuda_fp16.hpp)
            function "__half::__half(unsigned long long)" (declared at line 232 of /usr/include/cuda_fp16.hpp)
    *((half4*)((data0+(alu0+(gidx1<<14)+(lidx0<<11)+alu1)))) = make_half4(((half)(val0)),((half)(val1)),((half)(val2)),((half)(val3)));
                                                                                                                              ^

4 errors detected in the compilation of "<null>".
2025-02-06 18:54:15 +01:00
Alex Cheema
b5fc4bc288 Merge pull request #675 from exo-explore/rmtenacity
remove tenacity dependency, implement simple retry logic instead
2025-02-03 21:58:08 +00:00
Alex Cheema
5157d80a46 remove tenacity dependency, implement simple retry logic instead 2025-02-03 21:56:38 +00:00
Alex Cheema
75914b4de8 Merge pull request #669 from pavel-rodionov/feature-local-models
Add toggle to show only models downloaded locally
2025-02-03 21:45:27 +00:00
Rodionov Pavel
d084dbe574 Add toggle to show only models downloaded locally 2025-02-01 23:45:19 -08:00
Alex Cheema
1a77a52d71 Merge pull request #666 from exo-explore/patchmanualdiscovery
patch for manual discovery, set known_peers
2025-02-01 23:07:21 +00:00
Alex Cheema
72329ba984 patch for manual discovery, set known_peers 2025-02-01 23:06:57 +00:00
Alex Cheema
f663b0afa2 Merge pull request #665 from exo-explore/resumedownload
add model downloading section to README
2025-02-01 20:23:58 +00:00
Alex Cheema
51b5c2ca9b add model downloading section to README 2025-02-01 20:23:05 +00:00
Alex Cheema
9a1f0a85e6 Merge pull request #664 from exo-explore/resumedownload
resumable downloads with integrity checks
2025-02-01 18:34:36 +00:00
Alex Cheema
2c0d17c336 beautiful download 2025-02-01 17:29:19 +00:00
Alex Cheema
7034ee0fcb resumable downloads with integrity checks 2025-02-01 13:22:51 +00:00
Alex Cheema
7a75fb09b2 Merge pull request #660 from exo-explore/robustdownload
cleanup tmp files on failed download
2025-01-30 20:25:15 +00:00
Alex Cheema
0bebf8dfde fix indent 2025-01-30 20:21:28 +00:00
Alex Cheema
55c4385db5 cleanup tmp files on failed download 2025-01-30 20:11:06 +00:00
Alex Cheema
90690a7d10 Merge pull request #647 from deftdawg/patch-1
Add 4-bit to the end of DeepSeek V3/R1 model descriptions
2025-01-30 19:49:38 +00:00
Alex Cheema
130d998d36 Merge pull request #659 from exo-explore/robustdownload
ensure exo dir on start, retry with exp backoff on file downloads
2025-01-30 19:49:00 +00:00
Alex Cheema
788c49784c retry fetch_file_list also 2025-01-30 19:45:12 +00:00
Alex Cheema
6b1c8635fc ensure exo dir on start, retry with exp backoff on file downloads 2025-01-30 19:40:35 +00:00
Alex Cheema
24c410c19c Merge pull request #653 from exo-explore/tinyfixes
Tiny fixes
2025-01-29 19:08:05 +00:00
Alex Cheema
f6ed830ba6 Merge pull request #651 from exo-explore/parallelise_model_loadin
parallelise model loading
2025-01-29 19:07:25 +00:00
Alex Cheema
e6b4f2993c fix prompt output spacing in tui 2025-01-29 19:01:30 +00:00
DeftDawg
a25e02c913 Add 4-bit to the end of DeepSeek V3/R1 model descriptions 2025-01-29 14:00:13 -05:00
Alex Cheema
3675804f4d throttle repo progress events and only send them out if something changed 2025-01-29 18:55:54 +00:00
Alex Cheema
96f1aecb05 only in_progress if any given file is in_progress 2025-01-29 18:43:43 +00:00
Alex Cheema
23a5030604 even if part of a file is downloaded it may not be in_progress 2025-01-29 18:39:23 +00:00
Alex Cheema
31b56e862f make a singleton thread pool executor for tinygrad since we always want it to run on the same thread 2025-01-29 18:37:09 +00:00
Alex Cheema
9f6c688d62 update tinygrad 2025-01-29 18:06:38 +00:00
Alex Cheema
4887be5103 parallelise model loading 2025-01-29 02:32:59 +00:00
Alex Cheema
75091e206b Merge pull request #650 from exo-explore/chatgpttimeout
increase chatgpt api response timeout to 900 seconds
2025-01-29 02:03:52 +00:00
Alex Cheema
141de0d011 increase chatgpt api response timeout to 900 seconds 2025-01-29 02:03:00 +00:00
Alex Cheema
263b18a31e Merge pull request #649 from eclecticc/amd_fix
Fix AMD device capabilities fields
2025-01-29 02:01:06 +00:00
Nirav Patel
9cf6818f10 Fix AMD device capabilities fields 2025-01-28 16:58:58 -08:00
Alex Cheema
837ed5d980 Merge pull request #648 from exo-explore/modelasyncload
Fixes
2025-01-28 23:39:11 +00:00
Alex Cheema
9c1bea97e8 fix embed_tokens for last layer in qwen models 2025-01-28 23:09:45 +00:00
Alex Cheema
af171f06fa propagate prompts to other nodes so they can display them, cleaner prompt/output output 2025-01-28 21:50:49 +00:00
Alex Cheema
edfa53a4c2 Merge pull request #646 from exo-explore/modelasyncload
make sure mlx stuff is on separate thread non blocking
2025-01-28 18:56:19 +00:00
Alex Cheema
4a5b80a958 make sure mlx stuff is on separate thread non blocking 2025-01-28 18:56:00 +00:00
Alex Cheema
92d1bc01de Merge pull request #645 from exo-explore/modelasyncload
load mlx model shard on mlx thread so it doesnt block
2025-01-28 18:49:47 +00:00
Alex Cheema
6662d5668c load mlx model shard on mlx thread so it doesnt block 2025-01-28 18:49:19 +00:00
Alex Cheema
a0d673fa3a Merge pull request #640 from exo-explore/simpledownload
Simple download
2025-01-27 19:38:11 +00:00
Alex Cheema
7c649085a1 fix eta/speed for resuming an existing download, using the session downloaded bytes 2025-01-27 19:23:18 +00:00
Alex Cheema
90e0e2761f ignore not_started progress updates 2025-01-27 06:05:59 +00:00
Alex Cheema
265586f7b4 set timeout on get too 2025-01-27 06:05:40 +00:00
Alex Cheema
4748bb7dc7 increase file download timeout to 30min 2025-01-27 05:49:17 +00:00
Alex Cheema
ae770db4f3 increase download chunks to 1MB 2025-01-27 05:37:50 +00:00
Alex Cheema
82f75d0ccf increase hf download http timeout 15 mins for large downloads 2025-01-27 05:20:30 +00:00
Alex Cheema
295f41c5cc increase bench job timeout to give enough time to download 2025-01-27 05:03:35 +00:00
Alex Cheema
19a27c5bfd HF_HOME -> EXO_HOME 2025-01-27 02:59:23 +00:00
Alex Cheema
d7ca9b7732 show each node id in the tinychat topology viz 2025-01-27 02:20:22 +00:00
Alex Cheema
b349e48b0d fix visual bug where frontend would show the full hf repo size, but in some cases that includes redundant files so we should use the model index in those cases too 2025-01-27 02:13:05 +00:00
Alex Cheema
21586063f6 use llama-3.2-1b in tinygrad test 2025-01-27 01:35:33 +00:00
Alex Cheema
277d63d860 special case when a model doesnt have a model index file, then use wildcard for allow_patterns 2025-01-27 01:26:15 +00:00
Alex Cheema
74379ef671 log download logs with DEBUG>=6 very verbose 2025-01-27 01:11:54 +00:00
Alex Cheema
3c7bd48aa3 get rid of some more hf bloat 2025-01-27 01:08:46 +00:00
Alex Cheema
1df023023e remove a lot of hf bloat 2025-01-27 01:06:47 +00:00
Alex Cheema
b89495f444 rewrite ShardDownloader, simplify significantly 2025-01-27 00:37:57 +00:00
Alex Cheema
903950f64e Merge pull request #638 from exo-explore/deepseekv3fix
add exception for mlx-community/DeepSeek-R1-3bit and mlx-community/DeepSeek-V3-3bit in tokenizers test
2025-01-26 20:33:22 +00:00
Alex Cheema
a3766f538a add exception for mlx-community/DeepSeek-R1-3bit and mlx-community/DeepSeek-V3-3bit in tokenizers test 2025-01-26 20:32:48 +00:00
Alex Cheema
9711d632e0 Merge pull request #637 from exo-explore/deepseekv3fix
fix post_init deepseek v3
2025-01-26 20:31:53 +00:00
Alex Cheema
82ef086010 add deepseek-v3-3bit and deepseek-r1-3bit 2025-01-26 20:31:28 +00:00
Alex Cheema
55ea366932 fix post_init deepseek v3 2025-01-26 20:27:31 +00:00
Alex Cheema
63318983de Merge pull request #631 from sigseg5/main
Some adaptivity fixes in tinychat
2025-01-26 19:20:58 +00:00
sigseg5
fb841a1f50 Adjust truncate size in history list for text without any spaces 2025-01-26 00:38:58 +03:00
sigseg5
4512366580 Fix bubble behavior when user passes long text without any spaces 2025-01-26 00:02:17 +03:00
sigseg5
9525c0e7a7 Add adaptive padding for user and assistant messages on width <= 1480px 2025-01-26 00:01:54 +03:00
Alex Cheema
66f73768cc Merge pull request #627 from exo-explore/deepseek
Deepseek, tinychat group models, latex formatting, thinking boxes
2025-01-24 18:14:57 +00:00
Alex Cheema
fdd05baddb fix tokenizer tests 2025-01-24 18:13:36 +00:00
Alex Cheema
59174bdc62 we have a lot of models so group them nicely 2025-01-24 18:02:00 +00:00
Alex Cheema
cfdaaef8e6 handle thinking outputs nicely, format latex beautifully 2025-01-24 17:49:25 +00:00
Alex Cheema
d8ffa59dba add deepseek v1, v3 and all the distills 2025-01-24 16:39:38 +00:00
Alex Cheema
aa1ce21f82 Merge pull request #625 from eltociear/patch-1
chore: update manual_discovery.py
2025-01-23 16:51:32 +00:00
Ikko Eltociear Ashimine
4fb01f516d chore: update manual_discovery.py
occured -> occurred
2025-01-24 00:18:42 +09:00
Alex Cheema
a635b23044 Merge pull request #619 from exo-explore/runners2
fix readme images
2025-01-23 02:18:33 +00:00
Alex Cheema
ad0e0d02d8 fix readme images 2025-01-23 02:17:58 +00:00
Alex Cheema
2644fd02c8 Merge pull request #617 from exo-explore/runners2
Lots of fixes and QoL improvements.
2025-01-23 02:05:17 +00:00
Alex Cheema
88ac12df6c install clang test 2025-01-23 01:55:14 +00:00
Alex Cheema
dfd9d3eb48 linux install 2025-01-23 01:44:57 +00:00
Alex Cheema
200ff4d713 linux install 2025-01-23 01:43:00 +00:00
Alex Cheema
b2764f177f linux install 2025-01-23 01:40:59 +00:00
Alex Cheema
e57fa1dfa0 xlarge 2025-01-23 01:40:13 +00:00
Alex Cheema
209163c595 add linux tinygrad test 2025-01-23 01:38:10 +00:00
Alex Cheema
495987b50b beef up the instance 2025-01-23 01:37:38 +00:00
Alex Cheema
8484eb4165 fix config 2025-01-23 01:37:01 +00:00
Alex Cheema
790c08afd4 add linux tinygrad test 2025-01-23 01:31:44 +00:00
Alex Cheema
a8a9e3ffa1 explicitly enable TOKENIZERS_PARALLELISM=true 2025-01-23 01:26:27 +00:00
Alex Cheema
5c9bcb8620 set GRPC_VERBOSITY=error; TRANSFORMERS_VERBOSITY=error 2025-01-23 01:22:19 +00:00
Alex Cheema
d54e19c20a runners back 2025-01-23 00:55:52 +00:00
Alex Cheema
cc78738e24 remove kern scan intervals 2025-01-23 00:49:32 +00:00
Alex Cheema
2391051c11 remove kern.timer.scan_interval from bootstrap.sh 2025-01-23 00:41:40 +00:00
Alex Cheema
112dea1582 add back the benchmarks baby 2025-01-23 00:15:54 +00:00
Alex Cheema
dc5cdc4d78 add back opaque 2025-01-22 23:59:39 +00:00
Alex Cheema
f8db4e131e fix check for sd2.1 2025-01-22 23:53:42 +00:00
Alex Cheema
bbb6856988 fix check for sd2.1 2025-01-22 23:51:09 +00:00
Alex Cheema
9ba8bbbcf8 fix filter to include 169.254.* since thats what mac uses for ethernet 2025-01-22 23:47:43 +00:00
Alex Cheema
8ab9977f01 fix stable diffusion case for tui, make mlx run on its own thread again and non-blocking 2025-01-22 23:22:53 +00:00
Alex Cheema
3a4bae0dab fix issue with eos_token_id 2025-01-22 22:58:09 +00:00
Alex Cheema
87d1271d33 fix stream: false completion 2025-01-22 22:46:04 +00:00
Alex Cheema
55d1846f5e clean up DEBUG=2 logs, a few fixes for token 2025-01-22 22:27:02 +00:00
Alex Cheema
9954ce8e4d fix treating token as a list 2025-01-22 22:13:13 +00:00
Alex Cheema
09e12d8673 temporarily disable github runner benchmarks 2025-01-22 22:00:13 +00:00
Alex Cheema
98d6e986bd add back .circleci 2025-01-22 21:58:46 +00:00
Alex Cheema
d80324fe20 disable test-m3-single-node 2025-01-22 21:58:40 +00:00
Alex Cheema
97f3bad38f fix peer_handle 2025-01-22 21:07:49 +00:00
Alex Cheema
461e4f37cb Merge remote-tracking branch 'origin/main' into runners2 2025-01-22 21:06:12 +00:00
Alex Cheema
07ceb19f0a Merge pull request #614 from samiamjidkhan/main
animation fix
2025-01-22 14:59:54 +00:00
Sami Khan
27b4577f38 directory for images 2025-01-22 05:47:25 -05:00
Sami Khan
a70943f8d2 base images for animation 2025-01-22 05:46:38 -05:00
Alex Cheema
6b8cd0577e fix some issues with results 2025-01-20 16:30:16 +00:00
Alex Cheema
218c1e79d9 Merge branch 'main' into runners2 2025-01-20 16:12:55 +00:00
Alex Cheema
023ddc207e support different network interface tests 2024-12-17 21:03:00 +00:00
Alex Cheema
2f0b543a1e add peer connection info to tinychat 2024-12-17 17:37:40 +00:00
Alex Cheema
7ac4004392 change it back to collecting topology periodically even if peers dont change 2024-12-17 17:32:18 +00:00
Alex Cheema
198308b1eb more robust udp broadcast 2024-12-17 17:28:55 +00:00
Alex Cheema
1f108a06ff remove test sleep 2024-12-17 16:47:05 +00:00
Alex Cheema
3a58576f8c make sure this is actually doing something 2024-12-17 16:22:22 +00:00
Alex Cheema
0a07223074 switch to uvloop (faster asyncio event loop) and optimise grpc settings 2024-12-17 16:10:56 +00:00
Alex Cheema
58f0a0f547 optimise grpc parameters 2024-12-17 14:50:52 +00:00
Alex Cheema
e2474c3f15 fail if we never get the desired node count 2024-12-16 21:59:02 +00:00
Alex Cheema
1b14be6013 make device_capabilities async running on a thread pool 2024-12-16 21:17:30 +00:00
Alex Cheema
036224f877 add topology to tinychat ui 2024-12-16 21:17:12 +00:00
Alex Cheema
b17faa8199 dont broadcast every single process_tensor 2024-12-16 20:54:38 +00:00
Alex Cheema
35d90d947c Merge remote-tracking branch 'origin/main' into runners 2024-12-16 20:04:03 +00:00
Alex Cheema
8d94b8ae12 trigger test 2024-12-16 20:03:22 +00:00
Alex Cheema
99a70f1045 Merge commit: trigger test 2024-12-16 20:01:23 +00:00
Alex Cheema
bd0febe35f Merge commit: trigger test 2024-12-16 20:01:09 +00:00
Alex Cheema
34ecbbe01c Merge commit: trigger test 2024-12-16 20:00:50 +00:00
Alex Cheema
427d0718b3 Merge commit: trigger test 2024-12-16 20:00:39 +00:00
Alex Cheema
b49c4ca0e5 Merge commit: trigger test 2024-12-16 20:00:21 +00:00
Alex Cheema
41eaaec5a9 Merge commit: trigger test 2024-12-16 20:00:10 +00:00
Alex Cheema
bf1aafdea7 Merge commit: trigger test 2024-12-16 19:59:51 +00:00
Alex Cheema
bfa06ee9f3 Merge commit: trigger test 2024-12-16 19:59:39 +00:00
Alex Cheema
c0534b67c3 Merge commit: trigger test 2024-12-16 19:59:08 +00:00
Alex Cheema
063964aab3 remove redundant sample_logits, put back opaque status for process_prompt so we have a way of preemptively starting downloads 2024-12-16 19:50:36 +00:00
Alex Cheema
804ad4705a upgrade mlx 2024-12-16 19:50:33 +00:00
Alex Cheema
c9ded9ba96 optimise networking, remove bloat 2024-12-16 19:50:29 +00:00
Alex Cheema
64365d684f one two and three m4 pro clusters 2024-12-16 19:50:24 +00:00
Alex Cheema
9397464fad add commit to results 2024-12-16 19:50:19 +00:00
Nel Nibcord
08912d1b64 Only collect topology if peers changed 2024-12-16 19:50:18 +00:00
Alex Cheema
06c2e236b8 rip out stats bloat 2024-12-16 19:50:17 +00:00
Alex Cheema
cb4615c95d fix SendNewToken 2024-12-16 19:50:14 +00:00
Alex Cheema
f55a53ae7e one token at a time 2024-12-16 19:49:52 +00:00
Gary
25b4af70e0 Merge branch 'main' into runners 2024-12-14 20:48:58 +00:00
Alex Cheema
a93092105c set max-generate-tokens to 250 2024-12-14 19:10:03 +00:00
Alex Cheema
0c6ab35333 increase timeout of http request in bench.py up to 10 mins 2024-12-14 18:33:41 +00:00
Alex Cheema
e5d54c77a9 add llama-3.3-70b to 3 M4 Pro cluster 2024-12-12 18:51:26 +00:00
Alex Cheema
2ff4638122 Merge remote-tracking branch 'origin/main' into runners 2024-12-12 17:14:40 +00:00
Alex Cheema
b6f2385c41 run llama-3.1-8b on 3 m4 pro cluster 2024-12-12 15:13:10 +00:00
Alex Cheema
9472ab0d2c t 2024-12-12 15:05:55 +00:00
Alex Cheema
dbb7ad3c08 run with three m4 pro 2024-12-12 14:36:18 +00:00
Alex Cheema
2abe57be21 grasping at straws 2024-12-12 12:03:20 +00:00
Alex Cheema
eeecdcb409 try a different taskpolicy 2024-12-12 11:45:01 +00:00
Alex Cheema
f9f76129a1 better bench system info 2024-12-12 11:34:37 +00:00
Alex Cheema
8c6d37d9b8 m4 cluster test 2024-12-12 11:13:13 +00:00
Alex Cheema
1194db6e65 m3 2024-12-12 00:02:20 +00:00
Alex Cheema
8cb7327da2 re-enable m4 cluster run 2024-12-12 00:01:14 +00:00
Alex Cheema
bba0aa0877 single node test 20 2024-12-11 22:58:44 +00:00
Alex Cheema
279354a1fd single node test 19 2024-12-11 22:58:38 +00:00
Alex Cheema
92e2b74902 single node test 18 2024-12-11 22:58:33 +00:00
Alex Cheema
76196b8c2f single node test 17 2024-12-11 22:58:27 +00:00
Alex Cheema
8408c8499f single node test 16 2024-12-11 22:58:21 +00:00
Alex Cheema
c65d1d9141 single node test 15 2024-12-11 22:58:16 +00:00
Alex Cheema
0bd44c0f78 single node test 14 2024-12-11 22:58:10 +00:00
Alex Cheema
f22bc99f2c single node test 13 2024-12-11 22:58:04 +00:00
Alex Cheema
3fda05aa39 single node test 12 2024-12-11 22:57:58 +00:00
Alex Cheema
6c322ac070 single node test 11 2024-12-11 22:57:53 +00:00
Alex Cheema
c5c27a32af single node test 10 2024-12-11 22:57:47 +00:00
Alex Cheema
9f1393dc7f single node test 9 2024-12-11 22:57:42 +00:00
Alex Cheema
32ff3ef9af single node test 8 2024-12-11 22:57:36 +00:00
Alex Cheema
b23c3fdaad single node test 7 2024-12-11 22:57:31 +00:00
Alex Cheema
8b47a9d017 single node test 6 2024-12-11 22:57:25 +00:00
Alex Cheema
f89b85b3f2 single node test 5 2024-12-11 22:57:19 +00:00
Alex Cheema
6f097c9321 single node test 4 2024-12-11 22:57:14 +00:00
Alex Cheema
fb7a0defe1 single node test 3 2024-12-11 22:57:08 +00:00
Alex Cheema
fe506a53d9 single node test 2 2024-12-11 22:57:02 +00:00
Alex Cheema
3f6ef1c763 single node test 1 2024-12-11 22:56:56 +00:00
Alex Cheema
e63c224c71 testtt 2024-12-11 22:53:02 +00:00
Alex Cheema
20e3065e57 les goh 2024-12-11 22:49:29 +00:00
Alex Cheema
83892d5b7e t 2024-12-11 22:45:59 +00:00
Alex Cheema
83470a98b4 t 2024-12-11 22:42:02 +00:00
Alex Cheema
92edfa5efc t 2024-12-11 22:40:47 +00:00
Alex Cheema
225dcba788 t 2024-12-11 22:37:11 +00:00
Alex Cheema
6249bee793 tes 2024-12-11 22:35:30 +00:00
Alex Cheema
741c31836e test 2024-12-11 22:27:10 +00:00
Alex Cheema
d0b7f1b4bb t 2024-12-11 22:11:01 +00:00
Alex Cheema
90677415c7 t 2024-12-11 22:01:29 +00:00
Alex Cheema
6cf2af39e8 t 2024-12-11 21:55:24 +00:00
Alex Cheema
5a1a0f5fd2 t 2024-12-11 21:45:53 +00:00
Alex Cheema
dd3fd279dc t 2024-12-11 21:42:01 +00:00
Alex Cheema
61c09631c0 t 2024-12-11 21:40:47 +00:00
Alex Cheema
e698ef6ab1 t 2024-12-11 21:39:27 +00:00
Alex Cheema
26351e719d t 2024-12-11 21:36:59 +00:00
Alex Cheema
5dee5e55fe t 2024-12-11 21:33:03 +00:00
Alex Cheema
6acfb81860 t 2024-12-11 20:28:07 +00:00
Alex Cheema
b1142d4ff4 t 2024-12-11 19:39:58 +00:00
Alex Cheema
a932afc01c oi 2024-12-11 19:30:28 +00:00
Alex Cheema
cdae702673 t 2024-12-11 19:24:43 +00:00
Alex Cheema
d95f40b6c8 a 2024-12-11 19:07:36 +00:00
Alex Cheema
97ffb83e86 t 2024-12-11 19:01:24 +00:00
Alex Cheema
9a11e27c93 ttt 2024-12-11 18:54:51 +00:00
Alex Cheema
d6c2146dd9 t 2024-12-11 18:34:35 +00:00
Alex Cheema
63da9fc194 a 2024-12-11 18:30:02 +00:00
Alex Cheema
7c0c5ef7fc ttttttt 2024-12-11 18:23:59 +00:00
Alex Cheema
739b7d178e tttttt 2024-12-11 18:02:22 +00:00
Alex Cheema
cacf50cd57 tttt 2024-12-11 18:00:28 +00:00
Alex Cheema
0904cda3ac ttt 2024-12-11 17:58:59 +00:00
Alex Cheema
6bb38939ec tt 2024-12-11 17:56:22 +00:00
Alex Cheema
1dbe11caf9 t 2024-12-11 17:54:41 +00:00
Alex Cheema
8d9e3b88d3 t 2024-12-11 17:52:07 +00:00
Alex Cheema
9dd33d37f2 t 2024-12-11 17:44:14 +00:00
Alex Cheema
a4bb4bb6ac update bootstrap 2024-12-11 17:37:38 +00:00
Alex Cheema
7b99cb4a12 t 2024-12-11 17:30:50 +00:00
Alex Cheema
9848a45da5 TT 2024-12-11 17:27:53 +00:00
Alex Cheema
378975813c t 2024-12-11 17:15:39 +00:00
Alex Cheema
e680e8a1ed fix name 2024-12-11 17:07:45 +00:00
Alex Cheema
7b2282d300 run without debug flag 2024-12-11 17:07:19 +00:00
Alex Cheema
3b1ea1933b use .venv exo 2024-12-11 17:02:58 +00:00
Alex Cheema
668766fc4b t 2024-12-11 16:55:57 +00:00
Alex Cheema
e501eeaf91 tweak install 2024-12-11 16:52:07 +00:00
Alex Cheema
41902f716f tweaks 2024-12-11 16:40:21 +00:00
Alex Cheema
b7bab80ec8 test2 2024-12-11 16:36:50 +00:00
Alex Cheema
6169996c70 test 2024-12-11 16:35:26 +00:00
Alex Cheema
bbb58460f8 Test on m4 2024-12-11 16:29:52 +00:00
Alex Cheema
cff03fc6c5 perf diag 2024-12-11 16:19:47 +00:00
Alex Cheema
f7122d400d add system_status check to bench 2024-12-11 16:13:53 +00:00
Alex Cheema
c938efb531 t 2024-12-11 16:06:14 +00:00
Alex Cheema
e2d3a90832 runner-token typo 2024-12-11 15:47:10 +00:00
Alex Cheema
ba96413a63 bootstrap script tweaks 2024-12-11 15:45:05 +00:00
Alex Cheema
cb40eb23ce more robust configure_mlx.sh 2024-12-11 15:38:45 +00:00
Alex Cheema
afe71c01da check gpu usage 2024-12-11 15:28:57 +00:00
Alex Cheema
a84cba4e3a Merge remote-tracking branch 'origin/main' into runners 2024-12-11 15:22:35 +00:00
Alex Cheema
23158a42ad add branch name to results 2024-12-11 12:59:55 +00:00
Alex Cheema
18e7919971 test 30 2024-12-11 12:55:05 +00:00
Alex Cheema
0e32a625d7 test 29 2024-12-11 12:54:59 +00:00
Alex Cheema
04bc163fea test 28 2024-12-11 12:54:52 +00:00
Alex Cheema
949055dec0 test 27 2024-12-11 12:54:45 +00:00
Alex Cheema
070b163cc7 test 26 2024-12-11 12:54:38 +00:00
Alex Cheema
fc26ad4006 test 25 2024-12-11 12:54:27 +00:00
Alex Cheema
5d3be3c6ed test 24 2024-12-11 12:54:20 +00:00
Alex Cheema
23dd5de3ae test 23 2024-12-11 12:54:14 +00:00
Alex Cheema
6030b39964 test 22 2024-12-11 12:54:08 +00:00
Alex Cheema
4f4ac0fa52 test 21 2024-12-11 12:54:01 +00:00
Alex Cheema
16d9839071 test {i} 2024-12-11 12:53:55 +00:00
Alex Cheema
8269b4b190 t 2024-12-11 12:38:51 +00:00
Alex Cheema
1e869a0f15 trigger test 2024-12-10 02:04:52 +00:00
Alex Cheema
5a4d128db6 trigger test 2024-12-09 08:02:29 +00:00
Alex Cheema
8a5d212cfc test 20 2024-12-08 23:38:30 +00:00
Alex Cheema
53edb8508b test 19 2024-12-08 23:38:24 +00:00
Alex Cheema
29d9df04bf test 18 2024-12-08 23:38:18 +00:00
Alex Cheema
4d6af6e6ca test 17 2024-12-08 23:38:13 +00:00
Alex Cheema
8c7c156f57 test 16 2024-12-08 23:38:07 +00:00
Alex Cheema
310843487f test 15 2024-12-08 23:38:01 +00:00
Alex Cheema
a4b221d0a0 test 14 2024-12-08 23:37:55 +00:00
Alex Cheema
286db875de test 13 2024-12-08 23:37:49 +00:00
Alex Cheema
d714e40f62 test 12 2024-12-08 23:37:43 +00:00
Alex Cheema
e78ef75531 test 11 2024-12-08 23:37:37 +00:00
Alex Cheema
38eaecf087 test 10 2024-12-08 23:37:31 +00:00
Alex Cheema
3cf28f8452 test 9 2024-12-08 23:37:26 +00:00
Alex Cheema
9ba8bbdd70 test 8 2024-12-08 23:37:20 +00:00
Alex Cheema
af6048e373 test 7 2024-12-08 23:37:14 +00:00
Alex Cheema
d93b8e8948 test 6 2024-12-08 23:37:08 +00:00
Alex Cheema
b69cb49a46 test 5 2024-12-08 23:37:02 +00:00
Alex Cheema
cc74b1f9b3 test 4 2024-12-08 23:36:57 +00:00
Alex Cheema
e78a52de5f test 3 2024-12-08 23:36:51 +00:00
Alex Cheema
f6c2c37c4b test 2 2024-12-08 23:36:45 +00:00
Alex Cheema
314a5d9781 test 1 2024-12-08 23:36:22 +00:00
Alex Cheema
b4e885bbd2 test range 2024-12-08 23:36:14 +00:00
Alex Cheema
bd9d11861b sleep before bench 2024-12-08 23:24:46 +00:00
Alex Cheema
571b26c50e allowed interface types 2024-12-08 23:20:08 +00:00
Glen
b21681931d remove 2024-12-08 23:13:10 +00:00
Alex Cheema
f584e86d8e get rid of lfs stuff 2024-12-08 22:55:19 +00:00
Alex Cheema
fd05bca1c8 lfs 2024-12-08 22:46:49 +00:00
Alex Cheema
cbac4d6a3e git version 2024-12-08 22:44:32 +00:00
Alex Cheema
b0977f97ab t 2024-12-08 22:43:23 +00:00
Glen
1716f637f7 test 2024-12-08 22:32:03 +00:00
Glen
903a5aabf7 fix 2024-12-08 22:26:44 +00:00
Glen
b4f86496ea bootstrap 2024-12-08 22:23:28 +00:00
Alex Cheema
8e57f3385c trigger test 2024-12-08 22:14:23 +00:00
Alex Cheema
3ccbdf19de add DEBUG_DISCOVERY 2024-12-08 22:07:48 +00:00
Alex Cheema
3687ba18df bench logs 2024-12-08 22:02:39 +00:00
Alex Cheema
6bb7c11bbb enable debug 2024-12-08 21:54:24 +00:00
Glen
c8f93721c5 model matrix 2024-12-08 21:14:36 +00:00
Alex Cheema
fb8d87025f t 2024-12-08 21:02:42 +00:00
Alex Cheema
87865f0cd9 list exo processes before test, warmup req in bench 2024-12-08 20:58:44 +00:00
Glen
755dd477dd jobname 2024-12-08 20:37:50 +00:00
Alex Cheema
fb44eb086c simplify bench 2024-12-08 20:30:07 +00:00
Alex Cheema
be8cbc0f56 trigger test 2024-12-08 19:28:55 +00:00
Glen
fe8074929f fix 2024-12-08 19:08:47 +00:00
Glen
c3c80c61c9 name 2024-12-08 19:02:53 +00:00
Glen
c138de0875 job_name 2024-12-08 18:56:37 +00:00
Glen
38bd00390c fix 2024-12-08 18:32:38 +00:00
Glen
732ba915aa new_conf 2024-12-08 18:32:06 +00:00
Glen
785710355f aws 2024-12-07 19:28:54 +00:00
Glen
320892dccc maxtok 2024-12-07 19:28:54 +00:00
Glen
6dae3a4719 conf 2024-12-07 19:28:54 +00:00
Glen
7b77ef000e flush 2024-12-07 19:28:54 +00:00
Glen
6c08b32350 nodebug 2024-12-07 19:28:54 +00:00
Glen
4dd617ad37 shorter 2024-12-07 19:28:54 +00:00
Glen
acdee16aee debug 2024-12-07 19:28:54 +00:00
Glen
9fc33587da path 2024-12-07 19:28:54 +00:00
Glen
f087c0ac99 fix 2024-12-07 19:28:54 +00:00
Glen
16b126d890 fix 2024-12-07 19:28:54 +00:00
Glen
faf0aaedba jq 2024-12-07 19:28:54 +00:00
Glen
4cac1bb151 quotes 2024-12-07 19:28:54 +00:00
Glen
cb3c1477bb fix 2024-12-07 19:28:54 +00:00
Glen
19a7d5a5cf fix 2024-12-07 19:28:54 +00:00
Glen
f7e0348f62 activate 2024-12-07 19:28:54 +00:00
Glen
c3dfac60a6 debug 2024-12-07 19:28:54 +00:00
Glen
64954aacfe fixed 2024-12-07 19:28:54 +00:00
Glen
ccc5415cc6 try 2024-12-07 19:28:54 +00:00
Glen
1dcc731b43 fix 2024-12-07 19:28:54 +00:00
Glen
3662ec402a fix 2024-12-07 19:28:54 +00:00
Glen
0739dc9564 fix 2024-12-07 19:28:54 +00:00
Glen
d16280ddfc debug 2024-12-07 19:28:54 +00:00
Glen
f9c23617a7 fix3 2024-12-07 19:28:54 +00:00
Glen
ce2ccddc93 fix2 2024-12-07 19:28:54 +00:00
Glen
1af28cb5a1 fix 2024-12-07 19:28:54 +00:00
Glen
6b61fc6660 tweak python install 2024-12-07 19:28:54 +00:00
Glen
bdf417f25e tweak 2024-12-07 19:28:54 +00:00
Glen
d154d37ac4 add exo run 2024-12-07 19:28:54 +00:00
Glen
90fd5c13a4 matrix 2024-12-07 19:28:54 +00:00
Glen
7d223a0095 matrix 2024-12-07 19:28:54 +00:00
Glen
cb3d89eb48 test runner 2024-12-07 19:28:54 +00:00
Glen
8302fd0aae test runner 2024-12-07 19:28:54 +00:00
Alex Cheema
deb80d2577 clang for tinygrad 2024-12-07 19:28:54 +00:00
Alex Cheema
976e5f2fdb disable mlx test for now..plan to run this on a self-hosted runner 2024-12-07 19:28:54 +00:00
Alex Cheema
9dc76ef03b tooonygrad 2024-12-07 19:28:54 +00:00
Alex Cheema
32cd1f1d72 give this a goh 2024-12-07 19:28:54 +00:00
Alex Cheema
6b54188140 cond 2024-12-07 19:28:54 +00:00
Alex Cheema
58bcf5b429 check discovery on integration tests too 2024-12-07 19:28:54 +00:00
Alex Cheema
3c0297c3e9 more robust discovery log check 2024-12-07 19:28:54 +00:00
Alex Cheema
8d433e6579 run tinygrad and discovery integratrion tests on linux 2024-12-07 19:28:54 +00:00
Alex Cheema
676125bfe6 job 2024-12-07 19:28:54 +00:00
Alex Cheema
902e0d35e1 github env vars 2024-12-07 19:28:54 +00:00
Alex Cheema
972aea446c macos 15 2024-12-07 19:28:53 +00:00
Alex Cheema
0d0338f871 migrate from circleci to github actions 2024-12-07 19:28:53 +00:00
Alex Cheema
f94c9067e2 trigger test 2024-12-04 03:09:12 +00:00
Alex Cheema
f0bb515d1d trigger test 2024-12-02 11:20:21 +00:00
Alex Cheema
71db641fe4 trigger test 2024-12-02 04:11:43 +00:00
Alex Cheema
f339f74fe3 trigger test 2024-12-01 17:39:53 +00:00
Alex Cheema
7dc0a7467b trigger test 2024-12-01 14:31:23 +00:00
459 changed files with 54870 additions and 20775 deletions

View File

@@ -1,346 +0,0 @@
version: 2.1
orbs:
python: circleci/python@2
commands:
run_chatgpt_api_test:
parameters:
inference_engine:
type: string
model_id:
type: string
expected_output:
type: string
prompt:
type: string
steps:
- run:
name: Run chatgpt api integration test (<<parameters.inference_engine>>, <<parameters.model_id>>)
command: |
source env/bin/activate
# Set CLANG=1 for tinygrad only
if [ "<<parameters.inference_engine>>" = "tinygrad" ]; then
pip install llvmlite
export TOKENIZERS_PARALLELISM=true SUPPORT_BF16=0 CLANG=1
fi
# Start first instance
HF_HOME="$(pwd)/.hf_cache_node1" DEBUG_DISCOVERY=7 DEBUG=7 exo --inference-engine <<parameters.inference_engine>> \
--node-id "node1" --listen-port 5678 --broadcast-port 5679 --chatgpt-api-port 8000 \
--chatgpt-api-response-timeout 900 --disable-tui > output1.log &
PID1=$!
tail -f output1.log &
TAIL1=$!
# Start second instance
HF_HOME="$(pwd)/.hf_cache_node2" DEBUG_DISCOVERY=7 DEBUG=7 exo --inference-engine <<parameters.inference_engine>> \
--node-id "node2" --listen-port 5679 --broadcast-port 5678 --chatgpt-api-port 8001 \
--chatgpt-api-response-timeout 900 --disable-tui > output2.log &
PID2=$!
tail -f output2.log &
TAIL2=$!
# Remember to kill the tail processes at the end
trap 'kill $TAIL1 $TAIL2' EXIT
# Wait for discovery
sleep 10
# Function to check if processes are still running
check_processes() {
if ! kill -0 $PID1 2>/dev/null; then
echo "First instance (PID $PID1) died unexpectedly. Log output:"
cat output1.log
exit 1
fi
if ! kill -0 $PID2 2>/dev/null; then
echo "Second instance (PID $PID2) died unexpectedly. Log output:"
cat output2.log
exit 1
fi
}
# Check processes before proceeding
check_processes
echo "Sending request to first instance..."
response_1=$(curl -s http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "<<parameters.model_id>>",
"messages": [{"role": "user", "content": "<<parameters.prompt>>"}],
"temperature": 0.7
}')
echo "Response 1: $response_1"
# Check processes after first response
check_processes
echo "Sending request to second instance..."
response_2=$(curl -s http://localhost:8001/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "<<parameters.model_id>>",
"messages": [{"role": "user", "content": "<<parameters.prompt>>"}],
"temperature": 0.7
}')
echo "Response 2: $response_2"
# Check processes after second response
check_processes
# Stop both instances
kill $PID1 $PID2
echo ""
# Extract content using jq and check if it contains expected output
content1=$(echo "$response_1" | jq -r '.choices[0].message.content')
content2=$(echo "$response_2" | jq -r '.choices[0].message.content')
if [[ "$content1" != *"<<parameters.expected_output>>"* ]] || [[ "$content2" != *"<<parameters.expected_output>>"* ]]; then
echo "Test failed: Response does not match '<<parameters.expected_output>>'"
echo "Response 1 content: $content1"
echo ""
echo "Response 2 content: $content2"
echo "Output of first instance:"
cat output1.log
echo "Output of second instance:"
cat output2.log
exit 1
else
echo "Test passed: Response from both nodes matches '<<parameters.expected_output>>'"
fi
jobs:
unit_test:
macos:
xcode: "16.0.0"
resource_class: m2pro.large
steps:
- checkout
- run:
name: Set up Python
command: |
brew install python@3.12
python3.12 -m venv env
source env/bin/activate
- run:
name: Install dependencies
command: |
source env/bin/activate
pip install --upgrade pip
pip install .
- run:
name: Run tests
command: |
source env/bin/activate
# set TEMPERATURE to 0 for deterministic sampling
echo "Running inference engine tests..."
METAL_DEVICE_WRAPPER_TYPE=1 METAL_DEBUG_ERROR_MODE=0 METAL_XCODE=1 TEMPERATURE=0 python3 -m exo.inference.test_inference_engine
echo "Running tokenizer tests..."
python3 ./test/test_tokenizers.py
python3 ./test/test_model_helpers.py
discovery_integration_test:
macos:
xcode: "16.0.0"
steps:
- checkout
- run:
name: Set up Python
command: |
brew install python@3.12
python3.12 -m venv env
source env/bin/activate
- run:
name: Install dependencies
command: |
source env/bin/activate
pip install --upgrade pip
pip install .
- run:
name: Run discovery integration test
command: |
source env/bin/activate
DEBUG_DISCOVERY=7 DEBUG=7 exo --node-id "node1" --listen-port 5678 --broadcast-port 5679 --chatgpt-api-port 8000 --disable-tui > output1.log 2>&1 &
PID1=$!
DEBUG_DISCOVERY=7 DEBUG=7 exo --node-id "node2" --listen-port 5679 --broadcast-port 5678 --chatgpt-api-port 8001 --disable-tui > output2.log 2>&1 &
PID2=$!
sleep 10
kill $PID1 $PID2
if grep -q "Peer statuses: {\\'node2\\': \\'is_connected=True, health_check=True" output1.log && ! grep -q "Failed to connect peers:" output1.log && grep -q "Peer statuses: {\\'node1\\': \\'is_connected=True, health_check=True" output2.log && ! grep -q "Failed to connect peers:" output2.log; then
echo "Test passed: Both instances discovered each other"
exit 0
else
echo "Test failed: Devices did not discover each other"
echo "Output of first instance:"
cat output1.log
echo "Output of second instance:"
cat output2.log
exit 1
fi
chatgpt_api_integration_test_mlx:
macos:
xcode: "16.0.0"
resource_class: m2pro.large
steps:
- checkout
- run:
name: Set up Python
command: |
brew install python@3.12
python3.12 -m venv env
source env/bin/activate
- run:
name: Install dependencies
command: |
source env/bin/activate
pip install --upgrade pip
pip install .
- run_chatgpt_api_test:
inference_engine: mlx
model_id: llama-3.2-1b
prompt: "Keep responses concise. Who was the king of pop?"
expected_output: "Michael Jackson"
chatgpt_api_integration_test_dummy:
macos:
xcode: "16.0.0"
resource_class: m2pro.large
steps:
- checkout
- run:
name: Set up Python
command: |
brew install python@3.12
python3.12 -m venv env
source env/bin/activate
- run:
name: Install dependencies
command: |
source env/bin/activate
pip install --upgrade pip
pip install .
- run_chatgpt_api_test:
inference_engine: dummy
model_id: dummy
prompt: "Dummy prompt."
expected_output: "dummy"
chatgpt_api_integration_test_tinygrad:
macos:
xcode: "16.0.0"
resource_class: m2pro.large
steps:
- checkout
- run:
name: Set up Python
command: |
brew install python@3.12
python3.12 -m venv env
source env/bin/activate
- run:
name: Install dependencies
command: |
source env/bin/activate
pip install --upgrade pip
pip install .
- run_chatgpt_api_test:
inference_engine: tinygrad
model_id: llama-3.2-1b
prompt: "Keep responses concise. Who was the king of pop?"
expected_output: "Michael Jackson"
measure_pip_sizes:
macos:
xcode: "16.0.0"
steps:
- checkout
- run:
name: Set up Python
command: |
brew install python@3.12
python3.12 -m venv env
source env/bin/activate
- run:
name: Install dependencies and measure sizes
command: |
source env/bin/activate
pip install --upgrade pip
pip install .
python ./extra/pipsize.py --json ./pipsize.json
- store_artifacts:
path: ./pipsize.json
destination: pip-sizes.json
check_line_count:
docker:
- image: cimg/python:3.10
steps:
- checkout
- run:
name: Setup git for PR comparison
command: |
if [[ -n "$CIRCLE_PULL_REQUEST" ]]; then
PR_NUMBER=$(echo $CIRCLE_PULL_REQUEST | rev | cut -d'/' -f1 | rev)
BASE_BRANCH=$(curl -s -H "Circle-Token: $CIRCLE_TOKEN" \
"https://circleci.com/api/v2/project/github/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME/pipeline/$CIRCLE_WORKFLOW_ID" \
| jq -r '.target_branch')
git clone -b $BASE_BRANCH --single-branch \
https://github.com/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME.git \
base_branch
fi
- run:
name: Install dependencies
command: |
python -m pip install --upgrade pip
pip install tabulate
- run:
name: Run line count check
command: |
if [[ -n "$CIRCLE_PULL_REQUEST" ]]; then
python extra/line_counter.py base_branch .
else
python extra/line_counter.py .
fi
- store_artifacts:
path: line-count-snapshot.json
destination: line-count-snapshot.json
- store_artifacts:
path: line-count-diff.json
destination: line-count-diff.json
- run:
name: Create test results directory
command: |
mkdir -p test-results/line-count
cp line-count-*.json test-results/line-count/
- store_test_results:
path: test-results
workflows:
version: 2
build_and_test:
jobs:
- check_line_count:
filters:
branches:
only: /.*/
tags:
only: /.*/
- unit_test
- discovery_integration_test
- chatgpt_api_integration_test_mlx
- chatgpt_api_integration_test_tinygrad
- chatgpt_api_integration_test_dummy
- measure_pip_sizes

63
.clauderules Normal file
View File

@@ -0,0 +1,63 @@
# Claude Code Rules - Follow Every Rule Exactly
You must prioritize straightforward code semantics, well-named types, clear function signatures, and robust, carefully-chosen abstractions. Think about how your decisions might impact these aspects of code quality before proposing any changes.
You have access to all modern Python features from Python 3.13, 3.12, 3.11...
**When you're done making changes, remove any redundant comments; remaining comments should only apply to complex code segments, adding relevant context.**
## 1. Code Discipline
* Eliminate superfluous `try`/`catch` and `if` branches through strict typing and static analysis.
* Use pure functions unless you must mutate fixed state—then wrap that state in a class.
* Every function is **referentially transparent**: same inputs ⇒ same outputs, no hidden state, no unintended I/O.
* Put side-effects in injectable "effect handlers"; keep core logic pure.
## 2. Naming
* Choose descriptive, non-abbreviated names—no 3-letter acronyms or non-standard contractions.
* Anyone reading a function's type signature alone should grasp its purpose without extra context.
## 3. Typing
* Maintain **strict, exhaustive** typing; never bypass the type-checker.
* Default to `Literal[...]` when an enum-like set is needed.
* Prefer built-in types; when two values share structure but differ in meaning, enforce separation:
* Use `typing.NewType` for primitives (zero runtime cost).
* For serializable objects, add a `type: str` field that states the object's identity.
## 4. Pydantic
* Read, respect, and rely on Pydantic documentation.
* Centralize a common `ConfigDict` with `frozen=True` and `strict=True` (or stricter) and reuse it everywhere.
* For hierarchies of `BaseModel` variants, declare a discriminated union with `typing.Annotated[Base, Field(discriminator='variant')]`; publish a single `TypeAdapter[Base]` so all variants share one strict validator.
## 5. IDs & UUIDs
* Subclass Pydantic's `UUID4` for custom ID types.
* Generate fresh IDs with `uuid.uuid4()`.
* Create idempotency keys by hashing *persisted* state plus a **function-specific salt** to avoid collisions after crashes.
## 6. Error Handling
* Catch an exception **only** where you can handle or transform it meaningfully.
* State in the docstring **where** each exception is expected to be handled and **why**.
## 7. Dependencies
* Introduce new external dependencies only after approval.
* Request only libraries common in production environments.
## 8. Use of `@final` & Freezing
* Mark classes, methods, and variables as `@final` or otherwise immutable wherever applicable.
## 9. Repository Workflow
If you spot a rule violation within code that you've not been asked to work on directly, inform the user rather than patching it ad-hoc.
---
### One-Sentence Summary
Write strictly-typed, pure, self-describing Python that uses Pydantic, well-scoped side-effects, immutable state, approved dependencies, and explicit error handling.

64
.cursorrules Normal file
View File

@@ -0,0 +1,64 @@
# follow **every** rule exactly; report any violation instead of silently fixing it.
You must prioritize straightforward code semantics, well-named types, clear function signatures, and robust, carefully-chosen abstractions. Think about how your decisions might impact these aspects of code quality before proposing any changes.
You can use the advanced features of `typing`. You have access to all of the new features from Python 3.13, 3.12, 3.11...
**When you're done making your changes, remove any redundant comments that you may have left; the comments that remain should only apply to complex segments of code, adding relevant context.**
## 1. Code Discipline
* Eliminate superfluous `try` / `catch` and `if` branches through strict typing and static analysis.
* Use pure functions unless you must mutate fixed state—then wrap that state in a class.
* Every function is **referentially transparent**: same inputs ⇒ same outputs, no hidden state, no unintended I/O.
* Put side-effects in injectable “effect handlers”; keep core logic pure.
## 2. Naming
* Choose descriptive, non-abbreviated names—no 3-letter acronyms or non-standard contractions.
* Anyone reading a functions type signature alone should grasp its purpose without extra context.
## 3. Typing
* Maintain **strict, exhaustive** typing; never bypass the type-checker.
* Default to `Literal[...]` when an enum-like set is needed.
* Prefer built-in types; when two values share structure but differ in meaning, enforce separation:
* Use `typing.NewType` for primitives (zero runtime cost).
* For serialisable objects, add a `type: str` field that states the objects identity.
## 4. Pydantic
* Read, respect, and rely on Pydantic docs.
* Centralise a common `ConfigDict` with `frozen=True` and `strict=True` (or stricter) and reuse it everywhere.
* For hierarchies of `BaseModel` variants, declare a discriminated union with `typing.Annotated[Base, Field(discriminator='variant')]`; publish a single `TypeAdapter[Base]` so all variants share one strict validator.
## 5. IDs & UUIDs
* Subclass Pydantics `UUID4` for custom ID types.
* Generate fresh IDs with `uuid.uuid4()`.
* Create idempotency keys by hashing *persisted* state plus a **function-specific salt** to avoid collisions after crashes.
## 6. Error Handling
* Catch an exception **only** where you can handle or transform it meaningfully.
* State in the docstring **where** each exception is expected to be handled and **why**.
## 7. Dependencies
* Introduce new external dependencies only after approval.
* Request only libraries common in production environments.
## 8. Use of `@final` & Freezing
* Mark classes, methods, and variables as `@final` or otherwise immutable wherever applicable.
## 9. Repository Workflow
If you spot a rule violation within code that you've not been asked to work on directly, inform the user rather than patching it ad-hoc.
---
### One-Sentence Summary
Write strictly-typed, pure, self-describing Python that uses Pydantic, well-scoped side-effects, immutable state, approved dependencies, and explicit error handling

1
.envrc Normal file
View File

@@ -0,0 +1 @@
use flake

2
.gitattributes vendored
View File

@@ -1,2 +0,0 @@
*.mp3 filter=lfs diff=lfs merge=lfs -text
*.png filter=lfs diff=lfs merge=lfs -text

3
.githooks/post-checkout Executable file
View File

@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-checkout' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs post-checkout "$@"

3
.githooks/post-commit Executable file
View File

@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-commit' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs post-commit "$@"

3
.githooks/post-merge Executable file
View File

@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-merge' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs post-merge "$@"

3
.githooks/pre-push Executable file
View File

@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs pre-push "$@"

3
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1,3 @@
* @ToxicPine
* @AlexCheema
* @GeluVrabie

43
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,43 @@
---
name: Bug Report
about: Create a report to help us improve
title: '[BUG] '
labels: bug
assignees: ''
---
## Describe the bug
A clear and concise description of what the bug is.
## To Reproduce
Steps to reproduce the behavior:
1.
2.
3.
## Expected behavior
A clear and concise description of what you expected to happen.
## Actual behavior
A clear and concise description of what actually happened.
## Environment
- macOS Version:
- EXO Version:
- Hardware:
- Device 1: (e.g., MacBook Pro M1 Max, 32GB RAM)
- Device 2: (e.g., Mac Mini M2, 16GB RAM)
- Additional devices:
- Interconnection:
- (e.g., Thunderbolt 4 cable between Device 1 and 2)
- (e.g., WiFi 6 for Device 3)
- (e.g., 10GbE Ethernet between all devices)
## Additional context
Add any other context about the problem here.

View File

@@ -0,0 +1,11 @@
---
name: Feature Request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
<!-- Please use a clear, descriptive title above -->
Describe what you'd like to see added to EXO.

View File

@@ -0,0 +1,16 @@
name: Commit if changed
description: "Create a commit when the working tree is dirty"
inputs:
message:
description: "Commit message"
required: true
runs:
using: composite
steps:
- name: Commit changed files
shell: bash
run: |
git diff --quiet && exit 0
git commit -am "${{ inputs.message }}"

10
.github/actions/format/action.yml vendored Normal file
View File

@@ -0,0 +1,10 @@
name: Format Code
description: "Run code formatter"
runs:
using: "composite"
steps:
- name: Format code
run: nix --extra-experimental-features nix-command --extra-experimental-features flakes develop -c just fmt
shell: bash

10
.github/actions/lint-check/action.yml vendored Normal file
View File

@@ -0,0 +1,10 @@
name: Lint Check
description: "Check for lint errors"
runs:
using: "composite"
steps:
- name: Lint check
run: nix --extra-experimental-features nix-command --extra-experimental-features flakes develop -c just lint-check
shell: bash

10
.github/actions/lint/action.yml vendored Normal file
View File

@@ -0,0 +1,10 @@
name: Lint Code
description: "Run code linter"
runs:
using: "composite"
steps:
- name: Lint code
run: nix --extra-experimental-features nix-command --extra-experimental-features flakes develop -c just lint
shell: bash

View File

@@ -0,0 +1,10 @@
name: Regenerate Protobufs
description: "Regenerate protobuf files"
runs:
using: "composite"
steps:
- name: Regenerate protobufs
run: nix --extra-experimental-features nix-command --extra-experimental-features flakes develop -c just regenerate-protobufs
shell: bash

View File

@@ -0,0 +1,20 @@
name: Setup Python & uv
description: "Regenerate Python environment from uv.lock"
runs:
using: "composite"
steps:
- name: Install uv
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
cache-dependency-glob: uv.lock
- name: Install Python
run: uv python install
shell: bash
- name: Sync
run: uv sync --locked --all-extras --dev
shell: bash

12
.github/actions/typecheck/action.yml vendored Normal file
View File

@@ -0,0 +1,12 @@
name: Type Check
description: "Run type checker"
runs:
using: "composite"
steps:
- name: Run type checker
run: |
nix --extra-experimental-features nix-command --extra-experimental-features flakes develop -c just sync
nix --extra-experimental-features nix-command --extra-experimental-features flakes develop -c just check
shell: bash

12
.github/actions/unit-test/action.yml vendored Normal file
View File

@@ -0,0 +1,12 @@
name: Unit Test
description: "Run unit tests"
runs:
using: "composite"
steps:
- name: Run unit tests
run: |
nix --extra-experimental-features nix-command --extra-experimental-features flakes develop -c just sync-clean
nix --extra-experimental-features nix-command --extra-experimental-features flakes develop -c just test-fast
shell: bash

20
.github/actions/verify-clean/action.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
name: Verify Clean Working Tree
description: "Fail the job if the previous step left the working tree dirty"
inputs:
step:
description: "The name of the step that just executed"
required: true
runs:
using: composite
steps:
- name: Check git diff
shell: bash
run: |
if ! git diff --quiet; then
echo "Error: ${{ inputs.step }} left working tree dirty." >&2
git --no-pager diff >&2
exit 1
fi

159
.github/benchmark-dashboard/README.md vendored Normal file
View File

@@ -0,0 +1,159 @@
# EXO Benchmark Dashboard
A fully self-contained, browser-based dashboard for tracking EXO benchmark performance over time.
## Features
- 📊 **Success Rate Tracking**: Monitor cluster reliability across commits
-**Response Time Analysis**: Track average request completion times
- 🎯 **Throughput Metrics**: Tokens per second visualization
- 📈 **Request Distribution**: Success/failure breakdown over time
- 🔄 **Auto-Refresh**: Updates every 60 seconds
- 📺 **TV-Ready**: Large, clear visualizations perfect for display
- 🔐 **Secure**: Credentials stored in browser localStorage only
- 🌐 **No Backend**: Directly accesses S3 from the browser
## Quick Start
### Option 1: Direct File Access (Simplest)
Just open the HTML file directly in your browser:
```bash
open .github/benchmark-dashboard/index.html
```
Then click "Configure AWS Credentials" and enter your keys.
### Option 2: URL Parameters (For Quick Setup)
```bash
# Serve with credentials in URL (they'll be moved to localStorage)
open ".github/benchmark-dashboard/index.html?accessKey=YOUR_KEY&secretKey=YOUR_SECRET&region=us-east-1"
```
The credentials will be saved to localStorage and removed from the URL immediately.
### Option 3: Simple HTTP Server
```bash
# From repo root
python3 -m http.server 8080
# Then open: http://localhost:8080/.github/benchmark-dashboard/
```
## AWS Credentials
The dashboard needs read-only access to the `exo-benchmark-results` S3 bucket.
### Required IAM Permissions
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::exo-benchmark-results",
"arn:aws:s3:::exo-benchmark-results/*"
]
}
]
}
```
### Security Notes
- ✅ Credentials stored in browser `localStorage` only
- ✅ Never sent to any server (except AWS)
- ✅ All S3 access happens client-side
- ✅ Use read-only IAM credentials
- ⚠️ Don't commit credentials to git
- ⚠️ Use a dedicated read-only IAM user
## TV/Kiosk Mode
For permanent display on a TV:
### macOS
```bash
open -a "Google Chrome" --args --kiosk ".github/benchmark-dashboard/index.html"
```
### Linux
```bash
chromium-browser --kiosk --app="file://$(pwd)/.github/benchmark-dashboard/index.html"
```
### Auto-start on Boot
Create a simple startup script:
```bash
#!/bin/bash
# /usr/local/bin/start-benchmark-dashboard.sh
cd /path/to/exo
python3 -m http.server 8080 &
sleep 2
chromium-browser --kiosk http://localhost:8080/.github/benchmark-dashboard/
```
## Data Displayed
### Summary Cards
- **Latest Success Rate**: Most recent benchmark success percentage with trend
- **Avg Response Time**: Latest average response time in ms with trend
- **Total Benchmarks**: Count of all benchmarks run
- **Active Configurations**: Number of unique benchmark configs
### Charts
1. **Success Rate Over Time**: Line chart showing reliability trends
2. **Average Response Time**: Performance over time (lower is better)
3. **Throughput**: Tokens/second metric (higher is better)
4. **Request Distribution**: Stacked bar chart of successes/failures
## How It Works
1. **Loads AWS SDK**: Uses AWS SDK for JavaScript (browser version)
2. **Lists S3 Objects**: Fetches all files from `s3://exo-benchmark-results/bench/`
3. **Downloads Results**: Fetches each JSON result file
4. **Parses & Visualizes**: Uses Chart.js to create interactive charts
5. **Auto-Refreshes**: Polls S3 every 60 seconds for new results
## Customization
To modify the dashboard:
1. Edit `index.html`
2. Adjust `REFRESH_INTERVAL` for different polling frequency
3. Modify chart colors/styles in the Chart.js configuration
4. Add new metrics by extending the results parsing
## Troubleshooting
**"AWS credentials not configured"**
- Click "Configure AWS Credentials" and enter your keys
**"Error loading benchmark data"**
- Check AWS credentials are correct
- Verify S3 bucket name is `exo-benchmark-results`
- Ensure IAM user has read permissions
- Check browser console for detailed errors
**"No benchmark results found"**
- Wait for benchmark workflows to run
- Verify results are being uploaded to S3
- Check S3 bucket has files in `bench/` prefix
**Charts not updating**
- Check browser console for errors
- Verify network connectivity to S3
- Try refreshing the page manually

1641
.github/benchmark-dashboard/index.html vendored Normal file
View File

File diff suppressed because it is too large Load Diff

186
.github/configs/README.md vendored Normal file
View File

@@ -0,0 +1,186 @@
# EXO Benchmark Configurations
This directory contains configuration files for the EXO staged benchmark system.
## Overview
The staged benchmark system allows you to run complex, multi-stage load tests against EXO clusters. Each stage can have different characteristics:
- **Prompt Length**: Number of tokens in the input prompt
- **Generation Length**: Maximum tokens to generate in the response
- **Time Between Requests**: Delay (in seconds) between firing consecutive requests
- **Iterations**: Number of requests to send in this stage
Requests are **fire-and-forget** - they don't wait for the previous request to complete. This allows you to test overlapping request handling and measure success rates under load.
## Configuration Files
### `bench_simple.yaml`
A minimal configuration that replicates the behavior of the original `bench.py` script:
- Single stage with 1 iteration
- Short prompt (~20 tokens)
- Generates up to 100 tokens
This is useful for quick smoke tests.
### `bench_config.yaml`
A comprehensive multi-stage benchmark with:
1. **Warmup** (10 requests): Light load with short prompts
2. **Medium Load** (20 requests): Moderate load with medium prompts
3. **Stress Test** (30 requests): Heavy overlapping requests with long prompts
4. **Cooldown** (5 requests): Light load to wind down
This tests the cluster's behavior under varying load patterns.
## Configuration Schema
```yaml
# Hardware configuration - maps runner labels to instance counts
hardware_plan:
M3ULTRA_GPU80_512GB: 4
# Environment variables to set on each node (optional)
environment:
OVERRIDE_MEMORY_MB: 512
# Timeout for instance and runner readiness (seconds)
timeout_seconds: 600
# Model instances to run concurrently
model_ids:
- "mlx-community/Llama-3.2-1B-Instruct-4bit"
# Benchmark stages
stages:
- name: "stage_name" # Human-readable name for this stage
prompt_length: 100 # Target prompt length in tokens
generation_length: 200 # Max tokens to generate
time_between_requests: 2.0 # Seconds between firing requests
iterations: 10 # Number of requests in this stage
```
## Running Benchmarks
### Via GitHub Actions
**Automatic (every commit):**
- The **`bench`** workflow runs automatically on every push
- Uses `bench_simple.yaml` as the default configuration
- All settings (hardware plan, timeout, environment variables, models, stages) are defined in the config file
**Manual (on-demand):**
1. Go to **Actions****bench** workflow
2. Click **Run workflow**
3. Configure:
- **Config File**: Path to your YAML config (default: `.github/configs/bench_simple.yaml`)
- `.github/configs/bench_simple.yaml` for quick tests
- `.github/configs/bench_config.yaml` for complex multi-stage tests
All other settings (hardware plan, timeout, environment variables, models, stages) are read from the specified config file.
### Via Command Line
```bash
# Start EXO on localhost:8000
uv run exo --api-port 8000
# Run simple benchmark (1 stage, 1 iteration)
python3 .github/scripts/bench.py \
--api-port 8000 \
--config .github/configs/bench_simple.yaml \
--expected-nodes 1 \
--is-primary true \
--timeout-seconds 600
# Run complex staged benchmark (4 stages, multiple iterations)
python3 .github/scripts/bench.py \
--api-port 8000 \
--config .github/configs/bench_config.yaml \
--expected-nodes 1 \
--is-primary true \
--timeout-seconds 600
```
## Output Metrics
For each stage, the benchmark reports:
- **Total Requests**: Number of requests fired
- **Successful Requests**: Requests that completed successfully
- **Failed Requests**: Requests that encountered errors
- **Success Rate**: Percentage of successful requests
- **Total Tokens**: Sum of all tokens generated across successful requests
- **Avg Tokens/Request**: Average tokens per successful request
- **Avg Time/Request**: Average completion time per successful request
A JSON summary is also printed for easy parsing and storage.
## Creating Custom Benchmarks
To create a custom benchmark:
1. Copy an existing config file (e.g., `bench_config.yaml`)
2. Modify the stages to match your test scenario
3. Save it in this directory with a descriptive name
4. Run it using the workflow or command line
### Example: Sustained Load Test
```yaml
hardware_plan:
M3ULTRA_GPU80_512GB: 2
environment:
OVERRIDE_MEMORY_MB: 1024
timeout_seconds: 600
model_ids:
- "mlx-community/Llama-3.2-1B-Instruct-4bit"
stages:
- name: "sustained_load"
prompt_length: 200
generation_length: 150
time_between_requests: 0.5 # Very fast - 2 requests/second
iterations: 100 # Run for ~50 seconds
```
### Example: Varying Prompt Sizes
```yaml
hardware_plan:
M4PRO_GPU16_24GB: 3
timeout_seconds: 900
model_ids:
- "mlx-community/Llama-3.2-1B-Instruct-4bit"
stages:
- name: "tiny_prompts"
prompt_length: 10
generation_length: 100
time_between_requests: 1.0
iterations: 10
- name: "medium_prompts"
prompt_length: 200
generation_length: 100
time_between_requests: 1.0
iterations: 10
- name: "large_prompts"
prompt_length: 1000
generation_length: 100
time_between_requests: 1.0
iterations: 10
```
## Tips
- **Overlapping Requests**: Set `time_between_requests` < expected completion time to test concurrent request handling
- **Sequential Requests**: Set `time_between_requests` > expected completion time to ensure requests don't overlap
- **Realistic Load**: Model real usage patterns by varying prompt/generation lengths across stages
- **Success Rate**: A 100% success rate indicates the cluster handled the load well; lower rates suggest capacity limits

49
.github/configs/bench_config.yaml vendored Normal file
View File

@@ -0,0 +1,49 @@
# EXO Staged Benchmark Configuration
# This configuration defines a multi-stage load test for EXO clusters
# Hardware configuration - maps runner labels to instance counts
hardware_plan:
M3ULTRA_GPU80_512GB: 4
# Environment variables to set on each node (optional)
environment:
OVERRIDE_MEMORY_MB: 512
# Timeout for instance and runner readiness (seconds)
timeout_seconds: 600
# Multiple instances run concurrently on the cluster
model_ids:
- "mlx-community/Qwen3-0.6B-4bit"
- "mlx-community/Qwen3-0.6B-4bit"
# Stages run sequentially, each with its own characteristics
stages:
# Stage 1: Light load with short prompts
- name: "warmup"
prompt_length: 50 # Number of tokens in prompt
generation_length: 100 # Max tokens to generate
time_between_requests: 5.0 # Seconds between firing requests
iterations: 10 # Number of requests to send in this stage
# Stage 2: Medium load with medium prompts
- name: "medium_load"
prompt_length: 200
generation_length: 150
time_between_requests: 3.0
iterations: 20
# Stage 3: Heavy load with long prompts - requests will overlap
- name: "stress_test"
prompt_length: 500
generation_length: 200
time_between_requests: 1.0 # Fast firing - will definitely overlap
iterations: 30
# Stage 4: Cool down with simple prompts
- name: "cooldown"
prompt_length: 50
generation_length: 50
time_between_requests: 10.0
iterations: 5

125
.github/configs/bench_simple.yaml vendored Normal file
View File

@@ -0,0 +1,125 @@
# Simple single-shot benchmark
# Tests 2 instances concurrently on 2 nodes
# Hardware configuration - maps runner labels to instance counts
hardware_plan:
puffin4: 1
puffin8: 1
# Environment variables to set on each node
environment:
PLACEHOLDER: "placeholder"
# OVERRIDE_MEMORY_MB: 50000
MLX_METAL_FAST_SYNCH: 1
# Timeout for instance and runner readiness (seconds)
timeout_seconds: 1800
# Model instances to run concurrently
model_ids:
# - "mlx-community/DeepSeek-V3.1-8bit"
# - "mlx-community/Kimi-K2-Instruct-4bit"
- "mlx-community/Kimi-K2-Thinking"
# - "mlx-community/Qwen3-235B-A22B-4bit"
# - "mlx-community/Llama-3.3-70B-Instruct-4bit"
# - "mlx-community/Llama-3.3-70B-Instruct-8bit"
# - "mlx-community/Llama-3.2-1B-Instruct-4bit"
# Sharding strategy: "Pipeline" or "Tensor"
sharding: "Tensor"
# Instance type: "MlxRing" or "MlxIbv"
instance_meta: "MlxIbv"
# If true, run requests sequentially (no overlap); if false, fire-and-forget (default: false)
no_overlap: true
# Benchmark stages
# pp: 64, 256, 1024, 2048, 4096, 8192, 16384
# g: 64, 512
stages:
# - name: "simple"
# prompt_length: 512
# generation_length: 10
# time_between_requests: 2.0
# iterations: 5
# - name: "pp64_g64"
# prompt_length: 64
# generation_length: 64
# time_between_requests: 2.0
# iterations: 5
# - name: "pp64_g64"
# prompt_length: 64
# generation_length: 64
# time_between_requests: 2.0
# iterations: 5
# - name: "pp64_g512"
# prompt_length: 64
# generation_length: 512
# time_between_requests: 2.0
# iterations: 10
# - name: "pp256_g64"
# prompt_length: 256
# generation_length: 64
# time_between_requests: 2.0
# iterations: 5
- name: "pp256_g64"
prompt_length: 256
generation_length: 64
time_between_requests: 2.0
iterations: 5
# - name: "pp256_g512"
# prompt_length: 256
# generation_length: 512
# time_between_requests: 2.0
# iterations: 10
# - name: "pp1024_g64"
# prompt_length: 1024
# generation_length: 64
# time_between_requests: 2.0
# iterations: 5
# - name: "pp1024_g512"
# prompt_length: 1024
# generation_length: 512
# time_between_requests: 2.0
# iterations: 10
# - name: "pp2048_g64"
# prompt_length: 2048
# generation_length: 64
# time_between_requests: 2.0
# iterations: 5
# - name: "pp2048_g512"
# prompt_length: 2048
# generation_length: 512
# time_between_requests: 2.0
# iterations: 10
# - name: "pp4096_g64"
# prompt_length: 4096
# generation_length: 64
# time_between_requests: 2.0
# iterations: 4
# - name: "pp4096_g512"
# prompt_length: 4096
# generation_length: 512
# time_between_requests: 2.0
# iterations: 10
# - name: "pp8192_g64"
# prompt_length: 8192
# generation_length: 64
# time_between_requests: 2.0
# iterations: 5
# - name: "pp8192_g512"
# prompt_length: 8192
# generation_length: 512
# time_between_requests: 2.0
# iterations: 5
# - name: "pp16384_g64"
# prompt_length: 16384
# generation_length: 64
# time_between_requests: 2.0
# iterations: 10
# - name: "pp16384_g512"
# prompt_length: 16384
# generation_length: 512
# time_between_requests: 2.0
# iterations: 10

23
.github/pull_request_template.md vendored Normal file
View File

@@ -0,0 +1,23 @@
## Motivation
<!-- Why is this change needed? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here -->
## Changes
<!-- Describe what you changed in detail -->
## Why It Works
<!-- Explain why your approach solves the problem -->
## Test Plan
### Manual Testing
<!-- Hardware: (e.g., MacBook Pro M1 Max 32GB, Mac Mini M2 16GB, connected via Thunderbolt 4) -->
<!-- What you did: -->
<!-- - -->
### Automated Testing
<!-- Describe changes to automated tests, or how existing tests cover this change -->
<!-- - -->

1399
.github/scripts/bench.py vendored Normal file
View File

File diff suppressed because it is too large Load Diff

70
.github/scripts/build_matrix.py vendored Normal file
View File

@@ -0,0 +1,70 @@
#!/usr/bin/env python3
import json
import os
from typing import NotRequired, TypedDict, cast
import yaml
class MatrixEntry(TypedDict):
label: str
index: int
class MatrixInclude(TypedDict):
label: str
index: int
is_primary: bool
expected_nodes: int
class Config(TypedDict):
hardware_plan: dict[str, int]
timeout_seconds: NotRequired[int]
environment: NotRequired[dict[str, str]]
# Read the config file
config_file: str = os.environ["CONFIG_FILE"]
with open(config_file, "r") as f:
config: Config = cast(Config, yaml.safe_load(f))
# Extract hardware plan from config
plan: dict[str, int] = config["hardware_plan"]
if not plan:
raise ValueError(f"No hardware_plan found in {config_file}")
# Build matrix entries
entries: list[MatrixEntry] = []
for label, count in plan.items():
for idx in range(count):
entries.append({"label": label, "index": idx})
total_nodes: int = len(entries)
matrix: dict[str, list[MatrixInclude]] = {
"include": [
{
"label": e["label"],
"index": e["index"],
"is_primary": (i == 0),
"expected_nodes": total_nodes,
}
for i, e in enumerate(entries)
]
}
# Extract other config values
timeout_seconds: int = config.get("timeout_seconds", 600)
environment: dict[str, str] = config.get("environment", {})
# Output to GitHub Actions
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
f.write(f"matrix={json.dumps(matrix)}\n")
f.write(f"config_file={config_file}\n")
f.write(f"timeout_seconds={timeout_seconds}\n")
f.write(f"environment={json.dumps(environment)}\n")
print(f"Matrix: {json.dumps(matrix)}")
print(f"Config file: {config_file}")
print(f"Timeout: {timeout_seconds}")
print(f"Environment: {json.dumps(environment)}")

156
.github/workflows/BENCH_USAGE.md vendored Normal file
View File

@@ -0,0 +1,156 @@
# Benchmark Workflow Usage
## Overview
The `bench_matrix.yml` workflow enables distributed benchmarking of models across multiple self-hosted macOS runners with different hardware configurations.
## Workflow Inputs
| Input | Description | Default | Required |
|-------|-------------|---------|----------|
| `model_id` | Model ID to benchmark | `mlx-community/Llama-3.2-1B-Instruct-4bit` | Yes |
| `hardware_plan` | JSON mapping of runner labels to counts | `{"M4PRO_GPU16_24GB": 1}` | Yes |
| `prompt` | Benchmark prompt text | `What is the capital of France?` | No |
| `timeout_seconds` | Timeout for instance/runner readiness | `600` | No |
## Hardware Plan Format
The `hardware_plan` input is a JSON object mapping runner labels to the number of machines:
```json
{
"M4PRO_GPU16_24GB": 2,
"M3ULTRA_GPU80_512GB": 1
}
```
This example would:
- Start 2 runners with the `M4PRO_GPU16_24GB` label
- Start 1 runner with the `M3ULTRA_GPU80_512GB` label
- Total of 3 runners coordinating on a single distributed inference instance
## How It Works
1. **Planning Job** (`plan`)
- Runs on `ubuntu-latest`
- Parses the `hardware_plan` JSON
- Generates a dynamic matrix with one entry per runner
- Only the first runner (index 0) is marked as `is_primary`
2. **Benchmark Worker Jobs** (`bench_worker`)
- Each job runs on a self-hosted macOS runner with the specified label
- All runners start EXO in parallel
- The primary runner creates the model instance
- All runners wait for their assigned runner to be ready (Loaded/Running status)
- The primary runner executes the benchmark and prints results
- The primary runner deletes the instance
## Example Usage
### Single Machine Benchmark
```yaml
model_id: mlx-community/Llama-3.2-1B-Instruct-4bit
hardware_plan: '{"M4PRO_GPU16_24GB": 1}'
prompt: What is the capital of France?
timeout_seconds: 600
```
### Multi-Machine Distributed Benchmark
```yaml
model_id: mlx-community/Llama-3.2-3B-Instruct-4bit
hardware_plan: '{"M4PRO_GPU16_24GB": 2, "M3ULTRA_GPU80_512GB": 1}'
prompt: Explain quantum computing in simple terms.
timeout_seconds: 900
```
## Benchmark Output
The primary runner outputs a JSON object with benchmark results:
```json
{
"model_id": "mlx-community/Llama-3.2-1B-Instruct-4bit",
"instance_id": "abc-123-def",
"tokens": 42,
"elapsed_s": 2.451,
"tps": 17.136
}
```
Where:
- `tokens`: Number of chunks/tokens generated
- `elapsed_s`: Total elapsed time in seconds
- `tps`: Tokens per second (tokens / elapsed_s)
## Runner Requirements
Each self-hosted runner must:
- Be labeled with appropriate hardware tags (e.g., `M4PRO_GPU16_24GB`)
- Have the `self-hosted` and `macOS` labels
- Have Nix installed with flakes enabled
- Have network connectivity to other runners in the same job
## Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ GitHub Actions Workflow (bench_matrix.yml) │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌────────────────┐ │
│ │ Plan Job │ │
│ │ (ubuntu) │──┬─► Matrix: [{label, index, primary}] │
│ └────────────────┘ │ │
│ │ │
│ ┌───────────────────▼──────────────────────────────────┐ │
│ │ Bench Worker Jobs (Matrix) │ │
│ ├──────────────────────────────────────────────────────┤ │
│ │ │ │
│ │ Runner 0 (Primary) Runner 1 Runner 2 │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌──────────┐ │ │
│ │ │ Start EXO │ │ Start EXO │ │ Start EXO│ │ │
│ │ │ Create Inst │ │ Wait... │ │ Wait... │ │ │
│ │ │ Wait Ready │ │ Wait Ready │ │ Wait... │ │ │
│ │ │ Run Bench │ │ (idle) │ │ (idle) │ │ │
│ │ │ Print TPS │ │ │ │ │ │ │
│ │ │ Delete Inst │ │ │ │ │ │ │
│ │ └─────────────┘ └─────────────┘ └──────────┘ │ │
│ └───────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
## Implementation Details
### `scripts/bench.py`
A standalone Python script that:
- Creates instance (primary only)
- Polls `/state` endpoint until instance and all runners are ready
- Executes chat completion with timing (primary only)
- Parses SSE stream and counts tokens
- Computes TPS metrics
- Cleans up instance (primary only)
### Key Functions
- `wait_for_instance()`: Polls until instance with model_id appears
- `wait_for_runners_ready()`: Polls until expected number of runners reach Loaded/Running status
- `run_benchmark()`: Executes chat completion, measures time, counts tokens
## Troubleshooting
### Instance never becomes ready
- Check EXO logs in the workflow output
- Verify model_id is valid and accessible
- Increase `timeout_seconds`
### Runner mismatch
- Ensure hardware_plan counts match available labeled runners
- Check runner labels match exactly (case-sensitive)
### Network issues
- Verify runners can communicate on the network
- Check firewall rules between runner hosts

305
.github/workflows/bench.yml vendored Normal file
View File

@@ -0,0 +1,305 @@
name: bench
on: [push]
jobs:
plan:
if: contains(github.event.head_commit.message, '/bench')
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.build.outputs.matrix }}
config_file: ${{ steps.build.outputs.config_file }}
timeout_seconds: ${{ steps.build.outputs.timeout_seconds }}
environment: ${{ steps.build.outputs.environment }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Build matrix from config file
id: build
shell: bash
run: |
set -euo pipefail
CONFIG_FILE='.github/configs/bench_simple.yaml'
export CONFIG_FILE
echo "Config file: $CONFIG_FILE"
python3 .github/scripts/build_matrix.py
bench_worker:
needs: plan
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
name: "bench on ${{ matrix.label }} [${{ matrix.index }}]"
runs-on: [self-hosted, macOS, "${{ matrix.label }}"]
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
lfs: false
- name: Configure git user
run: |
git config --local user.email "github-actions@users.noreply.github.com"
git config --local user.name "github-actions bot"
shell: bash
# TODO: this is mega hacky and I'd like a simpler solution.
- name: Setup Nix Environment
run: |
echo "Checking for nix installation..."
# Check if nix is already available
if command -v nix >/dev/null 2>&1; then
echo "Nix already in PATH"
# Try sourcing profile scripts to set up environment properly
elif [ -f /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh ]; then
echo "Sourcing multi-user nix-daemon profile script"
source /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
elif [ -f "$HOME/.nix-profile/etc/profile.d/nix.sh" ]; then
echo "Sourcing single-user nix profile script"
source "$HOME/.nix-profile/etc/profile.d/nix.sh"
elif [ -f /nix/var/nix/profiles/per-user/$USER/profile/etc/profile.d/nix.sh ]; then
echo "Sourcing per-user nix profile script"
source /nix/var/nix/profiles/per-user/$USER/profile/etc/profile.d/nix.sh
elif [ -f /etc/profile.d/nix.sh ]; then
echo "Sourcing system-wide nix profile script"
source /etc/profile.d/nix.sh
# Fallback: manually add nix to PATH if binary exists
elif [ -f /nix/var/nix/profiles/default/bin/nix ]; then
echo "Found nix binary, manually adding to PATH"
export PATH="/nix/var/nix/profiles/default/bin:$PATH"
elif [ -f "$HOME/.nix-profile/bin/nix" ]; then
echo "Found nix binary in user profile, manually adding to PATH"
export PATH="$HOME/.nix-profile/bin:$PATH"
else
echo "Nix not found. Debugging info:"
echo "USER: $USER"
echo "HOME: $HOME"
echo "Current PATH: $PATH"
echo ""
echo "Checking common Nix locations:"
echo " /nix/var/nix/profiles/default/bin/nix:"
ls -la /nix/var/nix/profiles/default/bin/nix 2>/dev/null || echo " Not found"
echo " /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh:"
ls -la /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh 2>/dev/null || echo " Not found"
echo " ~/.nix-profile/etc/profile.d/nix.sh:"
ls -la "$HOME/.nix-profile/etc/profile.d/nix.sh" 2>/dev/null || echo " Not found"
echo " /nix/var/nix/profiles/per-user/$USER/profile/etc/profile.d/nix.sh:"
ls -la "/nix/var/nix/profiles/per-user/$USER/profile/etc/profile.d/nix.sh" 2>/dev/null || echo " Not found"
echo ""
echo "/nix directory structure:"
ls -la /nix 2>/dev/null || echo " /nix directory not found"
echo ""
echo "/nix/var:"
ls -la /nix/var 2>/dev/null || echo " /nix/var not found"
echo ""
echo "/nix/store:"
ls -la /nix/store 2>/dev/null | head -20 || echo " /nix/store not found"
echo ""
echo "GitHub Actions runner is running as user '$USER'."
echo "If Nix is installed for a different user, either:"
echo " 1. Install Nix for user '$USER' (multi-user install recommended)"
echo " 2. Configure the runner service to run as the user with Nix installed"
echo " 3. Ensure Nix is installed system-wide with proper daemon setup"
exit 1
fi
# Verify nix is available and persist to GITHUB_ENV
if command -v nix >/dev/null 2>&1; then
echo "✓ Nix is available"
nix --version
echo "PATH=$PATH" >> $GITHUB_ENV
if [ -n "$NIX_PATH" ]; then
echo "NIX_PATH=$NIX_PATH" >> $GITHUB_ENV
fi
else
echo "ERROR: Failed to set up Nix"
echo "PATH after setup attempt: $PATH"
exit 1
fi
shell: bash
- name: Setup EXO_HOME and API_PORT
run: |
EXO_HOME=$(mktemp -d -t exo-e2e-XXXXXXXX)
API_PORT=$((49152 + RANDOM % (65535 - 49152 + 1)))
EXO_MODELS_DIR="$HOME/.exo/models"
EXO_LIBP2P_NAMESPACE="bench-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
echo "EXO_HOME=$EXO_HOME" >> "$GITHUB_ENV"
echo "API_PORT=$API_PORT" >> "$GITHUB_ENV"
echo "EXO_MODELS_DIR=$EXO_MODELS_DIR" >> "$GITHUB_ENV"
echo "EXO_LIBP2P_NAMESPACE=$EXO_LIBP2P_NAMESPACE" >> "$GITHUB_ENV"
echo "Created EXO_HOME: $EXO_HOME"
echo "Generated API_PORT: $API_PORT"
echo "Using models from: $EXO_MODELS_DIR"
echo "Using libp2p namespace: $EXO_LIBP2P_NAMESPACE"
shell: bash
- name: Configure local MLX if available
run: |
echo "=== DEBUG: Checking for local MLX configuration ==="
MODIFIED=false
echo "Checking for /Users/Shared/mlx directory..."
if [ -d "/Users/Shared/mlx" ]; then
echo "✓ Found /Users/Shared/mlx"
ls -la /Users/Shared/mlx | head -5
echo "Enabling local mlx path in pyproject.toml"
sed -i.bak 's|^# mlx = { path = "/Users/Shared/mlx", editable=true }$|mlx = { path = "/Users/Shared/mlx", editable=true }|' pyproject.toml
MODIFIED=true
else
echo "✗ /Users/Shared/mlx not found, will use PyPI version"
fi
echo "Checking for /Users/Shared/mlx-lm directory..."
if [ -d "/Users/Shared/mlx-lm" ]; then
echo "✓ Found /Users/Shared/mlx-lm"
ls -la /Users/Shared/mlx-lm | head -5
echo "Enabling local mlx-lm path in pyproject.toml"
sed -i.bak 's|^# mlx-lm = { path = "/Users/Shared/mlx-lm", editable=true }$|mlx-lm = { path = "/Users/Shared/mlx-lm", editable=true }|' pyproject.toml
MODIFIED=true
else
echo "✗ /Users/Shared/mlx-lm not found, will use PyPI version"
fi
if [ "$MODIFIED" = true ]; then
echo "=== Modified pyproject.toml [tool.uv.sources] section: ==="
sed -n '/\[tool\.uv\.sources\]/,/^\[/{/^\[tool\.uv\.sources\]/p; /^\[/!p;}' pyproject.toml
echo "=== Regenerating uv.lock with local MLX paths... ==="
nix --extra-experimental-features nix-command --extra-experimental-features flakes develop --command uv lock --upgrade-package mlx --upgrade-package mlx-lm
echo "✓ Lock file regenerated"
else
echo "⚠ No local MLX directories found, using PyPI packages"
fi
echo "=== DEBUG: Local MLX configuration complete ==="
shell: bash
- name: Sync dependencies
run: |
if [ -d "/Users/Shared/test" ]; then
pushd /Users/Shared/test
uv sync --reinstall
popd
fi
echo "Running just sync to ensure clean dependencies..."
nix --extra-experimental-features nix-command --extra-experimental-features flakes develop --command just sync
shell: bash
- name: Start EXO and run bench script
shell: bash
env:
IS_PRIMARY: ${{ matrix.is_primary }}
EXPECTED_NODES: ${{ matrix.expected_nodes }}
HARDWARE_LABEL: ${{ matrix.label }}
CONFIG_FILE: ${{ needs.plan.outputs.config_file }}
TIMEOUT_SECONDS: ${{ needs.plan.outputs.timeout_seconds }}
ENVIRONMENT_JSON: ${{ needs.plan.outputs.environment }}
run: |
set -euo pipefail
# Parse environment variables from config
ENV_VARS=""
if [ -n "$ENVIRONMENT_JSON" ] && [ "$ENVIRONMENT_JSON" != "{}" ]; then
ENV_VARS=$(echo "$ENVIRONMENT_JSON" | python3 -c "import sys, json; env = json.load(sys.stdin); print(' '.join([f'{k}={v}' for k, v in env.items()]))")
fi
echo "Starting EXO with API_PORT=${API_PORT} EXO_HOME=${EXO_HOME} EXO_LIBP2P_NAMESPACE=${EXO_LIBP2P_NAMESPACE}"
echo "Environment variables from config: $ENV_VARS"
LOG_FILE=/tmp/exo.log
: > "$LOG_FILE"
MASTER_FLAG=""
if [ "$IS_PRIMARY" = "true" ]; then
MASTER_FLAG="-m"
fi
nix --extra-experimental-features nix-command --extra-experimental-features flakes develop --command bash -c \
"EXO_HOME=$EXO_HOME EXO_MODELS_DIR=$EXO_MODELS_DIR EXO_LIBP2P_NAMESPACE=$EXO_LIBP2P_NAMESPACE $ENV_VARS PYTHONUNBUFFERED=1 PYTHONDEBUG=1 PYTHONPATH=. uv run exo $MASTER_FLAG --api-port $API_PORT" \
>> "$LOG_FILE" 2>&1 &
EXO_PID=$!
echo "Started EXO in background with PID: $EXO_PID"
echo "Log file: $LOG_FILE"
cleanup() {
echo '=== EXO log (tail) ==='
tail -n 300 "$LOG_FILE" || true
if ps -p "$EXO_PID" >/dev/null 2>&1; then
echo "Killing EXO (PID $EXO_PID)"
kill "$EXO_PID" || true
fi
}
trap cleanup EXIT
for i in $(seq 1 60); do
if curl -s "http://localhost:${API_PORT}/state" >/dev/null 2>&1; then
echo "EXO API ready"
break
fi
if ! ps -p "$EXO_PID" >/dev/null 2>&1; then
echo "EXO terminated early"; sed -n '1,200p' "$LOG_FILE" || true; exit 1
fi
sleep 1
done
RESULTS_FILE="/tmp/bench_results_${GITHUB_RUN_ID}_${GITHUB_RUN_ATTEMPT}_$(date +%s).json"
echo "Results will be saved to: $RESULTS_FILE"
echo "RESULTS_FILE=$RESULTS_FILE" >> "$GITHUB_ENV"
echo "Running bench script with config: $CONFIG_FILE, timeout: $TIMEOUT_SECONDS"
nix --extra-experimental-features nix-command --extra-experimental-features flakes develop --command bash -c \
"PYTHONUNBUFFERED=1 uv run --no-project --with pyyaml --with pydantic python .github/scripts/bench.py \
--api-port $API_PORT \
--config $CONFIG_FILE \
--expected-nodes ${EXPECTED_NODES} \
--is-primary ${IS_PRIMARY} \
--timeout-seconds ${TIMEOUT_SECONDS} \
--output $RESULTS_FILE \
--git-commit ${GITHUB_SHA} \
--hardware-labels ${HARDWARE_LABEL}"
- name: Install AWS CLI
if: always() && env.RESULTS_FILE && matrix.is_primary
run: |
if ! command -v aws &> /dev/null; then
echo "AWS CLI not found, installing..."
brew install awscli
else
echo "AWS CLI already installed"
fi
shell: bash
- name: Upload results to S3
if: always() && env.RESULTS_FILE && matrix.is_primary
env:
AWS_ACCESS_KEY_ID: ${{ secrets.S3_BENCHMARKS_AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.S3_BENCHMARKS_AWS_SECRET_ACCESS_KEY }}
AWS_DEFAULT_REGION: us-east-1
run: |
echo "Checking for results file: $RESULTS_FILE"
echo "Is primary: ${{ matrix.is_primary }}"
if [ -f "$RESULTS_FILE" ]; then
TIMESTAMP=$(date -u +%Y/%m/%d/%H%M%S)
S3_KEY="bench/${TIMESTAMP}_${GITHUB_SHA:0:8}_${GITHUB_RUN_ID}.json"
echo "Uploading results to s3://exo-benchmark-results/$S3_KEY"
aws s3 cp "$RESULTS_FILE" "s3://exo-benchmark-results/$S3_KEY" \
--content-type application/json \
--metadata "commit=${GITHUB_SHA},run_id=${GITHUB_RUN_ID},branch=${GITHUB_REF_NAME}"
echo "Results uploaded successfully"
echo "View at: https://exo-benchmark-results.s3.amazonaws.com/$S3_KEY"
else
echo "Results file not found at: $RESULTS_FILE"
echo "Skipping upload"
fi
shell: bash
- name: Cleanup EXO_HOME
run: |
echo "Cleaning up EXO_HOME: $EXO_HOME"
rm -rf "$EXO_HOME"
shell: bash
if: always()

298
.github/workflows/build-app.yml vendored Normal file
View File

@@ -0,0 +1,298 @@
name: Build EXO macOS DMG
on:
push:
tags:
- "v*"
branches:
- "test-app"
jobs:
build-macos-app:
runs-on: "macos-26"
env:
SPARKLE_VERSION: 2.8.1
SPARKLE_DOWNLOAD_PREFIX: ${{ secrets.SPARKLE_DOWNLOAD_PREFIX }}
SPARKLE_FEED_URL: ${{ secrets.SPARKLE_FEED_URL }}
SPARKLE_ED25519_PUBLIC: ${{ secrets.SPARKLE_ED25519_PUBLIC }}
SPARKLE_ED25519_PRIVATE: ${{ secrets.SPARKLE_ED25519_PRIVATE }}
SPARKLE_S3_BUCKET: ${{ secrets.SPARKLE_S3_BUCKET }}
SPARKLE_S3_PREFIX: ${{ secrets.SPARKLE_S3_PREFIX }}
AWS_REGION: ${{ secrets.AWS_REGION }}
EXO_BUILD_NUMBER: ${{ github.run_number }}
EXO_LIBP2P_NAMESPACE: ${{ github.ref_name }}
steps:
# ============================================================
# Checkout and tag validation
# ============================================================
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Derive release version from tag
run: |
if [[ "$GITHUB_REF_NAME" == "test-app" ]]; then
VERSION="0.0.0-alpha.0"
echo "IS_ALPHA=true" >> $GITHUB_ENV
else
VERSION="${GITHUB_REF_NAME#v}"
if [[ "$VERSION" == *-alpha* ]]; then
echo "IS_ALPHA=true" >> $GITHUB_ENV
else
echo "IS_ALPHA=false" >> $GITHUB_ENV
fi
fi
echo "RELEASE_VERSION=$VERSION" >> $GITHUB_ENV
- name: Ensure tag commit is on main
if: github.ref_type == 'tag'
run: |
git fetch origin main
# Alpha tags can be on any branch, production tags must be on main
if [[ "$IS_ALPHA" == "true" ]]; then
echo "Alpha tag detected, skipping main branch check"
elif ! git merge-base --is-ancestor origin/main HEAD; then
echo "Production tag must point to a commit on main"
exit 1
fi
# ============================================================
# Install dependencies
# ============================================================
- name: Select Xcode 26.2
run: |
sudo xcode-select -s /Applications/Xcode_26.2.app
if ! xcrun -f metal >/dev/null 2>&1; then
echo "Metal toolchain is not installed."
exit 1
fi
- name: Install Homebrew packages
run: brew install just awscli macmon
- name: Install UV
uses: astral-sh/setup-uv@v6
with:
enable-cache: true
cache-dependency-glob: uv.lock
- name: Setup Python
run: |
uv python install
uv sync --locked
- name: Build dashboard
run: |
cd dashboard
npm ci
npm run build
- name: Install Sparkle CLI
run: |
CLI_URL="${SPARKLE_CLI_URL:-https://github.com/sparkle-project/Sparkle/releases/download/${SPARKLE_VERSION}/Sparkle-${SPARKLE_VERSION}.tar.xz}"
echo "Downloading Sparkle CLI from: $CLI_URL"
mkdir -p /tmp/sparkle
curl --fail --location --output /tmp/sparkle.tar.xz "$CLI_URL"
tar -xJf /tmp/sparkle.tar.xz -C /tmp/sparkle --strip-components=1
echo "SPARKLE_BIN=/tmp/sparkle/bin" >> $GITHUB_ENV
- name: Prepare code-signing keychain
env:
MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }}
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
PROVISIONING_PROFILE: ${{ secrets.PROVISIONING_PROFILE }}
run: |
KEYCHAIN_PATH="$HOME/Library/Keychains/build.keychain-db"
# Create fresh keychain
security create-keychain -p "$MACOS_CERTIFICATE_PASSWORD" "$KEYCHAIN_PATH"
# Disable auto-lock (no timeout, no lock-on-sleep)
security set-keychain-settings "$KEYCHAIN_PATH"
# Add to search list while preserving existing keychains
security list-keychains -d user -s "$KEYCHAIN_PATH" $(security list-keychains -d user | tr -d '"')
# Set as default and unlock
security default-keychain -s "$KEYCHAIN_PATH"
security unlock-keychain -p "$MACOS_CERTIFICATE_PASSWORD" "$KEYCHAIN_PATH"
# Import certificate with full access for codesign
echo "$MACOS_CERTIFICATE" | base64 --decode > /tmp/cert.p12
security import /tmp/cert.p12 -k "$KEYCHAIN_PATH" -P "$MACOS_CERTIFICATE_PASSWORD" \
-T /usr/bin/codesign -T /usr/bin/security -T /usr/bin/productbuild
rm /tmp/cert.p12
# Allow codesign to access the key without prompting
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$MACOS_CERTIFICATE_PASSWORD" "$KEYCHAIN_PATH"
# Verify keychain is unlocked and identity is available
echo "Verifying signing identity..."
security find-identity -v -p codesigning "$KEYCHAIN_PATH"
# Setup provisioning profile
mkdir -p "$HOME/Library/Developer/Xcode/UserData/Provisioning Profiles"
echo "$PROVISIONING_PROFILE" | base64 --decode > "$HOME/Library/Developer/Xcode/UserData/Provisioning Profiles/EXO.provisionprofile"
# Export keychain path for other steps
echo "BUILD_KEYCHAIN_PATH=$KEYCHAIN_PATH" >> $GITHUB_ENV
# ============================================================
# Build the bundle
# ============================================================
- name: Build PyInstaller bundle
run: uv run pyinstaller packaging/pyinstaller/exo.spec
- name: Build Swift app
env:
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
SPARKLE_FEED_URL: ${{ secrets.SPARKLE_FEED_URL }}
SPARKLE_ED25519_PUBLIC: ${{ secrets.SPARKLE_ED25519_PUBLIC }}
run: |
cd app/EXO
security unlock-keychain -p "$MACOS_CERTIFICATE_PASSWORD" "$BUILD_KEYCHAIN_PATH"
SIGNING_IDENTITY=$(security find-identity -v -p codesigning "$BUILD_KEYCHAIN_PATH" | awk -F '"' '{print $2}')
xcodebuild clean build \
-scheme EXO \
-configuration Release \
-derivedDataPath build \
MARKETING_VERSION="$RELEASE_VERSION" \
CURRENT_PROJECT_VERSION="$EXO_BUILD_NUMBER" \
EXO_BUILD_TAG="$RELEASE_VERSION" \
EXO_BUILD_COMMIT="$GITHUB_SHA" \
SPARKLE_FEED_URL="$SPARKLE_FEED_URL" \
SPARKLE_ED25519_PUBLIC="$SPARKLE_ED25519_PUBLIC" \
CODE_SIGNING_IDENTITY="$SIGNING_IDENTITY" \
CODE_SIGN_INJECT_BASE_ENTITLEMENTS=YES
mkdir -p ../../output
cp -R build/Build/Products/Release/EXO.app ../../output/EXO.app
- name: Inject PyInstaller runtime
run: |
rm -rf output/EXO.app/Contents/Resources/exo
mkdir -p output/EXO.app/Contents/Resources
cp -R dist/exo output/EXO.app/Contents/Resources/exo
- name: Codesign PyInstaller runtime
env:
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
run: |
cd output
security unlock-keychain -p "$MACOS_CERTIFICATE_PASSWORD" "$BUILD_KEYCHAIN_PATH"
SIGNING_IDENTITY=$(security find-identity -v -p codesigning "$BUILD_KEYCHAIN_PATH" | awk -F '"' '{print $2}')
RUNTIME_DIR="EXO.app/Contents/Resources/exo"
find "$RUNTIME_DIR" -type f \( -perm -111 -o -name "*.dylib" -o -name "*.so" \) -print0 |
while IFS= read -r -d '' file; do
/usr/bin/codesign --force --timestamp --options runtime \
--sign "$SIGNING_IDENTITY" "$file"
done
- name: Sign, notarize, and create DMG
env:
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
APPLE_NOTARIZATION_USERNAME: ${{ secrets.APPLE_NOTARIZATION_USERNAME }}
APPLE_NOTARIZATION_PASSWORD: ${{ secrets.APPLE_NOTARIZATION_PASSWORD }}
APPLE_NOTARIZATION_TEAM: ${{ secrets.APPLE_NOTARIZATION_TEAM }}
run: |
cd output
security unlock-keychain -p "$MACOS_CERTIFICATE_PASSWORD" "$BUILD_KEYCHAIN_PATH"
SIGNING_IDENTITY=$(security find-identity -v -p codesigning "$BUILD_KEYCHAIN_PATH" | awk -F '"' '{print $2}')
/usr/bin/codesign --deep --force --timestamp --options runtime \
--sign "$SIGNING_IDENTITY" EXO.app
mkdir -p dmg-root
cp -R EXO.app dmg-root/
ln -s /Applications dmg-root/Applications
DMG_NAME="EXO-${RELEASE_VERSION}.dmg"
hdiutil create -volname "EXO" -srcfolder dmg-root -ov -format UDZO "$DMG_NAME"
/usr/bin/codesign --force --timestamp --options runtime \
--sign "$SIGNING_IDENTITY" "$DMG_NAME"
if [[ -n "$APPLE_NOTARIZATION_USERNAME" ]]; then
SUBMISSION_OUTPUT=$(xcrun notarytool submit "$DMG_NAME" \
--apple-id "$APPLE_NOTARIZATION_USERNAME" \
--password "$APPLE_NOTARIZATION_PASSWORD" \
--team-id "$APPLE_NOTARIZATION_TEAM" \
--wait --timeout 15m 2>&1)
echo "$SUBMISSION_OUTPUT"
SUBMISSION_ID=$(echo "$SUBMISSION_OUTPUT" | awk 'tolower($1)=="id:" && $2 ~ /^[0-9a-fA-F-]+$/ {print $2; exit}')
STATUS=$(echo "$SUBMISSION_OUTPUT" | awk 'tolower($1)=="status:" {print $2; exit}')
if [[ -n "$SUBMISSION_ID" ]]; then
xcrun notarytool log "$SUBMISSION_ID" \
--apple-id "$APPLE_NOTARIZATION_USERNAME" \
--password "$APPLE_NOTARIZATION_PASSWORD" \
--team-id "$APPLE_NOTARIZATION_TEAM" > notarization-log.txt || true
echo "===== Notarization Log ====="
cat notarization-log.txt
echo "============================"
fi
if [[ "$STATUS" != "Accepted" ]]; then
echo "Notarization failed with status: ${STATUS:-Unknown}"
exit 1
fi
xcrun stapler staple "$DMG_NAME"
fi
- name: Generate Sparkle appcast
env:
SPARKLE_DOWNLOAD_PREFIX: ${{ env.SPARKLE_DOWNLOAD_PREFIX }}
SPARKLE_ED25519_PRIVATE: ${{ secrets.SPARKLE_ED25519_PRIVATE }}
IS_ALPHA: ${{ env.IS_ALPHA }}
run: |
set -euo pipefail
cd output
DOWNLOAD_PREFIX="${SPARKLE_DOWNLOAD_PREFIX:-https://assets.exolabs.net}"
echo "$SPARKLE_ED25519_PRIVATE" > sparkle_ed25519.key
chmod 600 sparkle_ed25519.key
CHANNEL_FLAG=""
if [[ "$IS_ALPHA" == "true" ]]; then
CHANNEL_FLAG="--channel alpha"
echo "Generating appcast for alpha channel"
fi
$SPARKLE_BIN/generate_appcast \
--ed-key-file sparkle_ed25519.key \
--download-url-prefix "$DOWNLOAD_PREFIX" \
$CHANNEL_FLAG \
.
# ============================================================
# Upload artifacts
# ============================================================
- name: Upload DMG
uses: actions/upload-artifact@v4
with:
name: EXO-dmg-${{ env.RELEASE_VERSION }}
path: output/EXO-${{ env.RELEASE_VERSION }}.dmg
- name: Upload to S3
if: env.SPARKLE_S3_BUCKET != '' && github.ref_type == 'tag'
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
AWS_REGION: ${{ env.AWS_REGION }}
SPARKLE_S3_BUCKET: ${{ env.SPARKLE_S3_BUCKET }}
SPARKLE_S3_PREFIX: ${{ env.SPARKLE_S3_PREFIX }}
IS_ALPHA: ${{ env.IS_ALPHA }}
run: |
set -euo pipefail
cd output
PREFIX="${SPARKLE_S3_PREFIX:-}"
if [[ -n "$PREFIX" && "${PREFIX: -1}" != "/" ]]; then
PREFIX="${PREFIX}/"
fi
DMG_NAME="EXO-${RELEASE_VERSION}.dmg"
aws s3 cp "$DMG_NAME" "s3://${SPARKLE_S3_BUCKET}/${PREFIX}${DMG_NAME}"
if [[ "$IS_ALPHA" != "true" ]]; then
aws s3 cp "$DMG_NAME" "s3://${SPARKLE_S3_BUCKET}/${PREFIX}EXO-latest.dmg"
fi
aws s3 cp appcast.xml "s3://${SPARKLE_S3_BUCKET}/${PREFIX}appcast.xml" --content-type application/xml --cache-control no-cache

183
.github/workflows/pipeline.yml vendored Normal file
View File

@@ -0,0 +1,183 @@
name: ci-pipeline
on:
push:
pull_request:
branches:
- staging
- main
jobs:
typecheck:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
lfs: false
- uses: cachix/install-nix-action@v31
with:
nix_path: nixpkgs=channel:nixos-unstable
- name: Configure git user
run: |
git config --local user.email "github-actions@users.noreply.github.com"
git config --local user.name "github-actions bot"
shell: bash
- name: Pull LFS files
run: |
echo "Pulling Git LFS files..."
git lfs pull
shell: bash
- name: Setup Nix Environment
run: |
echo "Checking for nix installation..."
# Check if nix binary exists directly
if [ -f /nix/var/nix/profiles/default/bin/nix ]; then
echo "Found nix binary at /nix/var/nix/profiles/default/bin/nix"
export PATH="/nix/var/nix/profiles/default/bin:$PATH"
echo "PATH=$PATH" >> $GITHUB_ENV
nix --version
elif [ -f /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh ]; then
echo "Found nix profile script, sourcing..."
source /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
nix --version
elif command -v nix >/dev/null 2>&1; then
echo "Nix already in PATH"
nix --version
else
echo "Nix not found. Debugging info:"
echo "Contents of /nix/var/nix/profiles/default/:"
ls -la /nix/var/nix/profiles/default/ 2>/dev/null || echo "Directory not found"
echo "Contents of /nix/var/nix/profiles/default/bin/:"
ls -la /nix/var/nix/profiles/default/bin/ 2>/dev/null || echo "Directory not found"
exit 1
fi
shell: bash
- name: Configure basedpyright include for local MLX
run: |
RUNNER_LABELS='${{ toJSON(runner.labels) }}'
if echo "$RUNNER_LABELS" | grep -q "local_mlx"; then
if [ -d "/Users/Shared/mlx" ]; then
echo "Updating [tool.basedpyright].include to use /Users/Shared/mlx"
awk '
BEGIN { in=0 }
/^\[tool\.basedpyright\]/ { in=1; print; next }
in && /^\[/ { in=0 } # next section
in && /^[ \t]*include[ \t]*=/ {
print "include = [\"/Users/Shared/mlx\"]"
next
}
{ print }
' pyproject.toml > pyproject.toml.tmp && mv pyproject.toml.tmp pyproject.toml
echo "New [tool.basedpyright] section:"
sed -n '/^\[tool\.basedpyright\]/,/^\[/p' pyproject.toml | sed '$d' || true
else
echo "local_mlx tag present but /Users/Shared/mlx not found; leaving pyproject unchanged."
fi
else
echo "Runner does not have 'local_mlx' tag; leaving pyproject unchanged."
fi
shell: bash
- uses: ./.github/actions/typecheck
nix-flake-check:
name: Check Nix flake
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
lfs: false
- uses: cachix/install-nix-action@v31
with:
nix_path: nixpkgs=channel:nixos-unstable
- name: Run nix flake check
run: |
nix flake check
shell: bash
# ci:
# needs: typecheck
# runs-on: ubuntu-latest
# permissions:
# contents: read
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# steps:
# - name: Checkout repository
# uses: actions/checkout@v4
# with:
# fetch-depth: 0
# token: ${{ secrets.GITHUB_TOKEN }}
# lfs: true
#
# - name: Configure git user
# run: |
# git config --local user.email "github-actions@users.noreply.github.com"
# git config --local user.name "github-actions bot"
# shell: bash
#
# - name: Pull LFS files
# run: |
# echo "Pulling Git LFS files..."
# git lfs pull
# shell: bash
#
# - name: Setup EXO_HOME and API_PORT
# run: |
# EXO_HOME=$(mktemp -d -t exo-ci-XXXXXXXX)
# # Generate random port (macOS compatible method)
# API_PORT=$((49152 + RANDOM % (65535 - 49152 + 1)))
# echo "EXO_HOME=$EXO_HOME" >> $GITHUB_ENV
# echo "API_PORT=$API_PORT" >> $GITHUB_ENV
# echo "Created EXO_HOME: $EXO_HOME"
# echo "Generated API_PORT: $API_PORT"
# shell: bash
#
# - name: Setup Nix Environment
# run: |
# echo "Checking for nix installation..."
#
# # Check if nix binary exists directly
# if [ -f /nix/var/nix/profiles/default/bin/nix ]; then
# echo "Found nix binary at /nix/var/nix/profiles/default/bin/nix"
# export PATH="/nix/var/nix/profiles/default/bin:$PATH"
# echo "PATH=$PATH" >> $GITHUB_ENV
# nix --version
# elif [ -f /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh ]; then
# echo "Found nix profile script, sourcing..."
# source /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
# nix --version
# elif command -v nix >/dev/null 2>&1; then
# echo "Nix already in PATH"
# nix --version
# else
# echo "Nix not found. Debugging info:"
# echo "Contents of /nix/var/nix/profiles/default/:"
# ls -la /nix/var/nix/profiles/default/ 2>/dev/null || echo "Directory not found"
# echo "Contents of /nix/var/nix/profiles/default/bin/:"
# ls -la /nix/var/nix/profiles/default/bin/ 2>/dev/null || echo "Directory not found"
# exit 1
# fi
# shell: bash
#
# - uses: ./.github/actions/lint-check
#
# - uses: ./.github/actions/unit-test
#
# - name: Cleanup EXO_HOME
# run: |
# echo "Cleaning up EXO_HOME: $EXO_HOME"
# rm -rf "$EXO_HOME"
# shell: bash
# if: always()

186
.gitignore vendored
View File

@@ -1,175 +1,27 @@
__pycache__/
.venv*
test_weights.npz
.exo_used_ports
.exo_node_id
.idea
.DS_Store
# gitingest
digest.txt
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# python
**/__pycache__
# C extensions
*.so
# nix
.direnv/
# Distribution / packaging
/.Python
/develop-eggs/
/dist/
/downloads/
/eggs/
/.eggs/
/lib/
/lib64/
/parts/
/sdist/
/var/
/wheels/
/share/python-wheels/
/*.egg-info/
/.installed.cfg
/*.egg
/MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# xcode / macos
*.xcuserstate
*.xcuserdata
*.xcuserdatad/
**/.DS_Store
app/EXO/build/
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
# rust
target/
**/*.rs.bk
*.pdb
# Jupyter Notebook
.ipynb_checkpoints
Untitled.ipynb
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
**/*.xcodeproj/*
.aider*
exo/tinychat/images/*.png
# svelte
dashboard/build/
dashboard/node_modules/
dashboard/.svelte-kit/

9
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,9 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
workspace.xml

16
.idea/LanguageServersSettings.xml generated Normal file
View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="LanguageServerSettingsState">
<state>
<map>
<entry key="com.insyncwithfoo.pyright">
<value>
<LanguageServerDefinitionSettings>
<option name="errorReportingKind" value="in_log" />
</LanguageServerDefinitionSettings>
</value>
</entry>
</map>
</state>
</component>
</project>

31
.idea/exo-v2.iml generated Normal file
View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="EMPTY_MODULE" version="4">
<component name="FacetManager">
<facet type="Python" name="Python facet">
<configuration sdkName="Python 3.13 virtualenv at ~/Desktop/exo/.venv" />
</facet>
</component>
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/scripts/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/rust/exo_pyo3_bindings/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/rust/exo_pyo3_bindings/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/rust/util/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/rust/networking/examples" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/rust/networking/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/rust/networking/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/rust/system_custodian/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.venv" />
<excludeFolder url="file://$MODULE_DIR$/.direnv" />
<excludeFolder url="file://$MODULE_DIR$/build" />
<excludeFolder url="file://$MODULE_DIR$/dist" />
<excludeFolder url="file://$MODULE_DIR$/.go_cache" />
<excludeFolder url="file://$MODULE_DIR$/rust/target" />
</content>
<orderEntry type="jdk" jdkName="Python 3.13 (exo)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Python 3.13 virtualenv at ~/Desktop/exo/.venv interpreter library" level="application" />
</component>
</module>

6
.idea/externalDependencies.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalDependencies">
<plugin id="systems.fehn.intellijdirenv" />
</component>
</project>

View File

@@ -0,0 +1,14 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyCompatibilityInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ourVersions">
<value>
<list size="1">
<item index="0" class="java.lang.String" itemvalue="3.14" />
</list>
</value>
</option>
</inspection_tool>
</profile>
</component>

10
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.13 (exo)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.13 (exo)" project-jdk-type="Python SDK" />
<component name="PythonCompatibilityInspectionAdvertiser">
<option name="version" value="3" />
</component>
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/exo.iml" filepath="$PROJECT_DIR$/.idea/exo.iml" />
</modules>
</component>
</project>

18
.idea/pyright-overrides.xml generated Normal file
View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="com.insyncwithfoo.pyright.configurations.Override">
<option name="names">
<map>
<entry key="configurationFile" value="true" />
<entry key="diagnosticMode" value="true" />
<entry key="inlayHintsGenericTypes" value="true" />
<entry key="prefixTooltipMessages" value="true" />
<entry key="runningMode" value="true" />
<entry key="smartExecutableResolution" value="true" />
<entry key="smartLanguageServerExecutableResolution" value="true" />
<entry key="useEditorFontForTooltips" value="true" />
<entry key="useTypingExtensions" value="true" />
</map>
</option>
</component>
</project>

9
.idea/pyright.xml generated Normal file
View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="com.insyncwithfoo.pyright.configurations.Local">
<option name="diagnosticMode" value="WORKSPACE" />
<option name="inlayHintsGenericTypes" value="true" />
<option name="prefixTooltipMessages" value="true" />
<option name="useEditorFontForTooltips" value="true" />
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
def is_available() -> bool:
"""Check if the CUDA back-end is available."""

View File

@@ -0,0 +1,216 @@
from typing import Sequence
from mlx.core import Device, Dtype, Stream, array
class Group:
"""
An :class:`mlx.core.distributed.Group` represents a group of independent mlx
processes that can communicate.
"""
def rank(self) -> int:
"""Get the rank of this process"""
def size(self) -> int:
"""Get the size of the group"""
def split(self, color: int, key: int = ...) -> Group:
"""
Split the group to subgroups based on the provided color.
Processes that use the same color go to the same group. The ``key``
argument defines the rank in the new group. The smaller the key the
smaller the rank. If the key is negative then the rank in the
current group is used.
Args:
color (int): A value to group processes into subgroups.
key (int, optional): A key to optionally change the rank ordering
of the processes.
"""
def all_gather(
x: array, *, group: Group | None = ..., stream: Stream | Device | None = ...
) -> array:
"""
Gather arrays from all processes.
Gather the ``x`` arrays from all processes in the group and concatenate
them along the first axis. The arrays should all have the same shape.
Args:
x (array): Input array.
group (Group): The group of processes that will participate in the
gather. If set to ``None`` the global group is used. Default:
``None``.
stream (Stream, optional): Stream or device. Defaults to ``None``
in which case the default stream of the default device is used.
Returns:
array: The concatenation of all ``x`` arrays.
"""
def all_max(
x: array, *, group: Group | None = ..., stream: Stream | Device | None = ...
) -> array:
"""
All reduce max.
Find the maximum of the ``x`` arrays from all processes in the group.
Args:
x (array): Input array.
group (Group): The group of processes that will participate in the
reduction. If set to ``None`` the global group is used. Default:
``None``.
stream (Stream, optional): Stream or device. Defaults to ``None``
in which case the default stream of the default device is used.
Returns:
array: The maximum of all ``x`` arrays.
"""
def all_min(
x: array, *, group: Group | None = ..., stream: Stream | Device | None = ...
) -> array:
"""
All reduce min.
Find the minimum of the ``x`` arrays from all processes in the group.
Args:
x (array): Input array.
group (Group): The group of processes that will participate in the
reduction. If set to ``None`` the global group is used. Default:
``None``.
stream (Stream, optional): Stream or device. Defaults to ``None``
in which case the default stream of the default device is used.
Returns:
array: The minimum of all ``x`` arrays.
"""
def all_sum(
x: array, *, group: Group | None = ..., stream: Stream | Device | None = ...
) -> array:
"""
All reduce sum.
Sum the ``x`` arrays from all processes in the group.
Args:
x (array): Input array.
group (Group): The group of processes that will participate in the
reduction. If set to ``None`` the global group is used. Default:
``None``.
stream (Stream, optional): Stream or device. Defaults to ``None``
in which case the default stream of the default device is used.
Returns:
array: The sum of all ``x`` arrays.
"""
def init(strict: bool = ..., backend: str = ...) -> Group:
"""
Initialize the communication backend and create the global communication group.
Example:
.. code:: python
import mlx.core as mx
group = mx.distributed.init(backend="ring")
Args:
strict (bool, optional): If set to False it returns a singleton group
in case ``mx.distributed.is_available()`` returns False otherwise
it throws a runtime error. Default: ``False``
backend (str, optional): Which distributed backend to initialize.
Possible values ``mpi``, ``ring``, ``nccl``, ``any``. If set to ``any`` all
available backends are tried and the first one that succeeds
becomes the global group which will be returned in subsequent
calls. Default: ``any``
Returns:
Group: The group representing all the launched processes.
"""
def is_available() -> bool:
"""Check if a communication backend is available."""
def recv(
shape: Sequence[int],
dtype: Dtype,
src: int,
*,
group: Group | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Recv an array with shape ``shape`` and dtype ``dtype`` from process
with rank ``src``.
Args:
shape (tuple[int]): The shape of the array we are receiving.
dtype (Dtype): The data type of the array we are receiving.
src (int): Rank of the source process in the group.
group (Group): The group of processes that will participate in the
recv. If set to ``None`` the global group is used. Default:
``None``.
stream (Stream, optional): Stream or device. Defaults to ``None``
in which case the default stream of the default device is used.
Returns:
array: The array that was received from ``src``.
"""
def recv_like(
x: array,
src: int,
*,
group: Group | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Recv an array with shape and type like ``x`` from process with rank
``src``.
It is equivalent to calling ``mx.distributed.recv(x.shape, x.dtype, src)``.
Args:
x (array): An array defining the shape and dtype of the array we are
receiving.
src (int): Rank of the source process in the group.
group (Group): The group of processes that will participate in the
recv. If set to ``None`` the global group is used. Default:
``None``.
stream (Stream, optional): Stream or device. Defaults to ``None``
in which case the default stream of the default device is used.
Returns:
array: The array that was received from ``src``.
"""
def send(
x: array,
dst: int,
*,
group: Group | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Send an array from the current process to the process that has rank
``dst`` in the group.
Args:
x (array): Input array.
dst (int): Rank of the destination process in the group.
group (Group): The group of processes that will participate in the
sned. If set to ``None`` the global group is used. Default:
``None``.
stream (Stream, optional): Stream or device. Defaults to ``None``
in which case the default stream of the default device is used.
Returns:
array: An array identical to ``x`` which when evaluated the send is performed.
"""

View File

@@ -0,0 +1,38 @@
def clear_cache() -> None: ...
def device_info() -> dict[str, str | int]:
"""
Get information about the GPU device and system settings.
Currently returns:
* ``architecture``
* ``max_buffer_size``
* ``max_recommended_working_set_size``
* ``memory_size``
* ``resource_limit``
Returns:
dict: A dictionary with string keys and string or integer values.
"""
def get_active_memory() -> int: ...
def get_cache_memory() -> int: ...
def get_peak_memory() -> int: ...
def is_available() -> bool:
"""Check if the Metal back-end is available."""
def reset_peak_memory() -> None: ...
def set_cache_limit(limit: int) -> int: ...
def set_memory_limit(limit: int) -> int: ...
def set_wired_limit(limit: int) -> int: ...
def start_capture(path: str) -> None:
"""
Start a Metal capture.
Args:
path (str): The path to save the capture which should have
the extension ``.gputrace``.
"""
def stop_capture() -> None:
"""Stop a Metal capture."""

View File

@@ -0,0 +1,301 @@
from typing import Sequence
from mlx.core import Device, Dtype, Stream, array, scalar
from mlx.core.distributed import state as state
def bernoulli(
p: scalar | array = ...,
shape: Sequence[int] | None = ...,
key: array | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Generate Bernoulli random values.
The values are sampled from the bernoulli distribution with parameter
``p``. The parameter ``p`` can be a :obj:`float` or :obj:`array` and
must be broadcastable to ``shape``.
Args:
p (float or array, optional): Parameter of the Bernoulli
distribution. Default: ``0.5``.
shape (list(int), optional): Shape of the output.
Default: ``p.shape``.
key (array, optional): A PRNG key. Default: ``None``.
Returns:
array: The array of random integers.
"""
def categorical(
logits: array,
axis: int = ...,
shape: Sequence[int] | None = ...,
num_samples: int | None = ...,
key: array | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Sample from a categorical distribution.
The values are sampled from the categorical distribution specified by
the unnormalized values in ``logits``. Note, at most one of ``shape``
or ``num_samples`` can be specified. If both are ``None``, the output
has the same shape as ``logits`` with the ``axis`` dimension removed.
Args:
logits (array): The *unnormalized* categorical distribution(s).
axis (int, optional): The axis which specifies the distribution.
Default: ``-1``.
shape (list(int), optional): The shape of the output. This must
be broadcast compatible with ``logits.shape`` with the ``axis``
dimension removed. Default: ``None``
num_samples (int, optional): The number of samples to draw from each
of the categorical distributions in ``logits``. The output will have
``num_samples`` in the last dimension. Default: ``None``.
key (array, optional): A PRNG key. Default: ``None``.
Returns:
array: The ``shape``-sized output array with type ``uint32``.
"""
def gumbel(
shape: Sequence[int] = ...,
dtype: Dtype | None = ...,
key: Stream | Device | None = ...,
stream: array | None = ...,
) -> array:
"""
Sample from the standard Gumbel distribution.
The values are sampled from a standard Gumbel distribution
which CDF ``exp(-exp(-x))``.
Args:
shape (list(int)): The shape of the output.
dtype (Dtype, optional): The data type of the output.
Default: ``float32``.
key (array, optional): A PRNG key. Default: ``None``.
Returns:
array:
The :class:`array` with shape ``shape`` and distributed according
to the Gumbel distribution.
"""
def key(seed: int) -> array:
"""
Get a PRNG key from a seed.
Args:
seed (int): Seed for the PRNG.
Returns:
array: The PRNG key array.
"""
def laplace(
shape: Sequence[int] = ...,
dtype: Dtype | None = ...,
loc: float = ...,
scale: float = ...,
key: array | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Sample numbers from a Laplace distribution.
Args:
shape (list(int), optional): Shape of the output. Default: ``()``.
dtype (Dtype, optional): Type of the output. Default: ``float32``.
loc (float, optional): Mean of the distribution. Default: ``0.0``.
scale (float, optional): The scale "b" of the Laplace distribution.
Default:``1.0``.
key (array, optional): A PRNG key. Default: ``None``.
Returns:
array: The output array of random values.
"""
def multivariate_normal(
mean: array,
cov: array,
shape: Sequence[int] = ...,
dtype: Dtype | None = ...,
key: array | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Generate jointly-normal random samples given a mean and covariance.
The matrix ``cov`` must be positive semi-definite. The behavior is
undefined if it is not. The only supported ``dtype`` is ``float32``.
Args:
mean (array): array of shape ``(..., n)``, the mean of the
distribution.
cov (array): array of shape ``(..., n, n)``, the covariance
matrix of the distribution. The batch shape ``...`` must be
broadcast-compatible with that of ``mean``.
shape (list(int), optional): The output shape must be
broadcast-compatible with ``mean.shape[:-1]`` and ``cov.shape[:-2]``.
If empty, the result shape is determined by broadcasting the batch
shapes of ``mean`` and ``cov``. Default: ``[]``.
dtype (Dtype, optional): The output type. Default: ``float32``.
key (array, optional): A PRNG key. Default: ``None``.
Returns:
array: The output array of random values.
"""
def normal(
shape: Sequence[int] = ...,
dtype: Dtype | None = ...,
loc: scalar | array | None = ...,
scale: scalar | array | None = ...,
key: array | None = ...,
stream: Stream | Device | None = ...,
) -> array:
r"""
Generate normally distributed random numbers.
If ``loc`` and ``scale`` are not provided the "standard" normal
distribution is used. That means $x \sim \mathcal{N}(0, 1)$ for
real numbers and $\text{Re}(x),\text{Im}(x) \sim \mathcal{N}(0,
\frac{1}{2})$ for complex numbers.
Args:
shape (list(int), optional): Shape of the output. Default: ``()``.
dtype (Dtype, optional): Type of the output. Default: ``float32``.
loc (scalar or array, optional): Mean of the distribution.
Default: ``None``.
scale (scalar or array, optional): Standard deviation of the
distribution. Default: ``None``.
key (array, optional): A PRNG key. Default: ``None``.
Returns:
array: The output array of random values.
"""
def permutation(
x: int | array,
axis: int = ...,
key: array | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Generate a random permutation or permute the entries of an array.
Args:
x (int or array, optional): If an integer is provided a random
permtuation of ``mx.arange(x)`` is returned. Otherwise the entries
of ``x`` along the given axis are randomly permuted.
axis (int, optional): The axis to permute along. Default: ``0``.
key (array, optional): A PRNG key. Default: ``None``.
Returns:
array:
The generated random permutation or randomly permuted input array.
"""
def randint(
low: scalar | array,
high: scalar | array,
shape: Sequence[int] = ...,
dtype: Dtype | None = ...,
key: array | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Generate random integers from the given interval.
The values are sampled with equal probability from the integers in
half-open interval ``[low, high)``. The lower and upper bound can be
scalars or arrays and must be broadcastable to ``shape``.
Args:
low (scalar or array): Lower bound of the interval.
high (scalar or array): Upper bound of the interval.
shape (list(int), optional): Shape of the output. Default: ``()``.
dtype (Dtype, optional): Type of the output. Default: ``int32``.
key (array, optional): A PRNG key. Default: ``None``.
Returns:
array: The array of random integers.
"""
def seed(seed: int) -> None:
"""
Seed the global PRNG.
Args:
seed (int): Seed for the global PRNG.
"""
def split(key: array, num: int = ..., stream: Stream | Device | None = ...) -> array:
"""
Split a PRNG key into sub keys.
Args:
key (array): Input key to split.
num (int, optional): Number of sub keys. Default: ``2``.
Returns:
array: The array of sub keys with ``num`` as its first dimension.
"""
def truncated_normal(
lower: scalar | array,
upper: scalar | array,
shape: Sequence[int] | None = ...,
dtype: Dtype | None = ...,
key: array | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Generate values from a truncated normal distribution.
The values are sampled from the truncated normal distribution
on the domain ``(lower, upper)``. The bounds ``lower`` and ``upper``
can be scalars or arrays and must be broadcastable to ``shape``.
Args:
lower (scalar or array): Lower bound of the domain.
upper (scalar or array): Upper bound of the domain.
shape (list(int), optional): The shape of the output.
Default:``()``.
dtype (Dtype, optional): The data type of the output.
Default: ``float32``.
key (array, optional): A PRNG key. Default: ``None``.
Returns:
array: The output array of random values.
"""
def uniform(
low: scalar | array = ...,
high: scalar | array = ...,
shape: Sequence[int] = ...,
dtype: Dtype | None = ...,
key: array | None = ...,
stream: Stream | Device | None = ...,
) -> array:
"""
Generate uniformly distributed random numbers.
The values are sampled uniformly in the half-open interval ``[low, high)``.
The lower and upper bound can be scalars or arrays and must be
broadcastable to ``shape``.
Args:
low (scalar or array, optional): Lower bound of the distribution.
Default: ``0``.
high (scalar or array, optional): Upper bound of the distribution.
Default: ``1``.
shape (list(int), optional): Shape of the output. Default:``()``.
dtype (Dtype, optional): Type of the output. Default: ``float32``.
key (array, optional): A PRNG key. Default: ``None``.
Returns:
array: The output array random values.
"""

View File

@@ -0,0 +1,9 @@
"""
This type stub file was generated by pyright.
"""
from layers import *
from utils import *
from . import init as init
from . import losses as losses

View File

@@ -0,0 +1,284 @@
"""
This type stub file was generated by pyright.
"""
from typing import Callable, Literal
import mlx.core as mx
def constant(value: float, dtype: mx.Dtype = ...) -> Callable[[mx.array], mx.array]:
r"""An initializer that returns an array filled with ``value``.
Args:
value (float): The value to fill the array with.
dtype (Dtype, optional): The data type of the array. Default:
``float32``.
Returns:
Callable[[array], array]: An initializer that returns an array with the
same shape as the input, filled with ``value``.
Example:
>>> init_fn = nn.init.constant(0.5)
>>> init_fn(mx.zeros((2, 2)))
array([[0.5, 0.5],
[0.5, 0.5]], dtype=float32)
"""
def normal(
mean: float = ..., std: float = ..., dtype: mx.Dtype = ...
) -> Callable[[mx.array], mx.array]:
r"""An initializer that returns samples from a normal distribution.
Args:
mean (float, optional): Mean of the normal distribution. Default:
``0.0``.
std (float, optional): Standard deviation of the normal distribution.
Default: ``1.0``.
dtype (Dtype, optional): The data type of the array. Default:
``float32``.
Returns:
Callable[[array], array]: An initializer that returns an array with the
same shape as the input, filled with samples from a normal distribution.
Example:
>>> init_fn = nn.init.normal()
>>> init_fn(mx.zeros((2, 2)))
array([[-0.982273, -0.534422],
[0.380709, 0.0645099]], dtype=float32)
"""
def uniform(
low: float = ..., high: float = ..., dtype: mx.Dtype = ...
) -> Callable[[mx.array], mx.array]:
r"""An initializer that returns samples from a uniform distribution.
Args:
low (float, optional): The lower bound of the uniform distribution.
Default: ``0.0``.
high (float, optional): The upper bound of the uniform distribution.
Default: ``1.0``
dtype (Dtype, optional): The data type of the array. Default: ``float32``.
Returns:
Callable[[array], array]: An initializer that returns an array
with the same shape as the input, filled with samples from a uniform
distribution
Example:
>>> init_fn = nn.init.uniform(low=0, high=1)
>>> init_fn(mx.zeros((2, 2)))
array([[0.883935, 0.863726],
[0.617261, 0.417497]], dtype=float32)
"""
def identity(dtype: mx.Dtype = ...) -> Callable[[mx.array], mx.array]:
r"""An initializer that returns an identity matrix.
Args:
dtype (Dtype, optional): The data type of the array. Defaults:
``float32``.
Returns:
Callable[[array], array]: An initializer that returns an identity
matrix with the same shape as the input.
Example:
>>> init_fn = nn.init.identity()
>>> init_fn(mx.zeros((2, 2)))
array([[1, 0],
[0, 1]], dtype=float32)
"""
def glorot_normal(dtype: mx.Dtype = ...) -> Callable[[mx.array, float], mx.array]:
r"""A Glorot normal initializer.
This initializer samples from a normal distribution with a standard
deviation computed from the number of input (``fan_in``) and output
(``fan_out``) units according to:
.. math::
\sigma = \gamma \sqrt{\frac{2.0}{\text{fan\_in} + \text{fan\_out}}}
For more details see the original reference: `Understanding the difficulty
of training deep feedforward neural networks
<https://proceedings.mlr.press/v9/glorot10a.html>`_
Args:
dtype (Dtype, optional): The data type of the array. Default: ``float32``.
Returns:
Callable[[array, float], array]: An initializer that returns an array
with the same shape as the input, filled with samples from the Glorot
normal distribution.
Example:
>>> init_fn = nn.init.glorot_normal()
>>> init_fn(mx.zeros((2, 2)))
array([[0.191107, 1.61278],
[-0.150594, -0.363207]], dtype=float32)
>>> init_fn(mx.zeros((2, 2)), gain=4.0)
array([[1.89613, -4.53947],
[4.48095, 0.995016]], dtype=float32)
"""
def glorot_uniform(dtype: mx.Dtype = ...) -> Callable[[mx.array, float], mx.array]:
r"""A Glorot uniform initializer.
This initializer samples from a uniform distribution with a range
computed from the number of input (``fan_in``) and output (``fan_out``)
units according to:
.. math::
\sigma = \gamma \sqrt{\frac{6.0}{\text{fan\_in} + \text{fan\_out}}}
For more details see the original reference: `Understanding the difficulty
of training deep feedforward neural networks
<https://proceedings.mlr.press/v9/glorot10a.html>`_
Args:
dtype (Dtype, optional): The data type of the array. Default: ``float32``.
Returns:
Callable[[array, float], array]: An initializer that returns an array
with the same shape as the input, filled with samples from the Glorot
uniform distribution.
Example:
>>> init_fn = nn.init.glorot_uniform()
>>> init_fn(mx.zeros((2, 2)))
array([[0.223404, -0.890597],
[-0.379159, -0.776856]], dtype=float32)
>>> init_fn(mx.zeros((2, 2)), gain=4.0)
array([[-1.90041, 3.02264],
[-0.912766, 4.12451]], dtype=float32)
"""
def he_normal(
dtype: mx.Dtype = ...,
) -> Callable[[mx.array, Literal["fan_in", "fan_out"], float], mx.array]:
r"""Build a He normal initializer.
This initializer samples from a normal distribution with a standard
deviation computed from the number of input (``fan_in``) or output
(``fan_out``) units according to:
.. math::
\sigma = \gamma \frac{1}{\sqrt{\text{fan}}}
where :math:`\text{fan}` is either the number of input units when the
``mode`` is ``"fan_in"`` or output units when the ``mode`` is
``"fan_out"``.
For more details see the original reference: `Delving Deep into Rectifiers:
Surpassing Human-Level Performance on ImageNet Classification
<https://arxiv.org/abs/1502.01852>`_
Args:
dtype (Dtype, optional): The data type of the array. Defaults to mx.float32.
Returns:
Callable[[array, str, float], array]: An initializer that returns an
array with the same shape as the input, filled with samples from the He
normal distribution.
Example:
>>> init_fn = nn.init.he_normal()
>>> init_fn(mx.zeros((2, 2))) # uses fan_in
array([[-1.25211, 0.458835],
[-0.177208, -0.0137595]], dtype=float32)
>>> init_fn(mx.zeros((2, 2)), mode="fan_out", gain=5)
array([[5.6967, 4.02765],
[-4.15268, -2.75787]], dtype=float32)
"""
def he_uniform(
dtype: mx.Dtype = ...,
) -> Callable[[mx.array, Literal["fan_in", "fan_out"], float], mx.array]:
r"""A He uniform (Kaiming uniform) initializer.
This initializer samples from a uniform distribution with a range
computed from the number of input (``fan_in``) or output (``fan_out``)
units according to:
.. math::
\sigma = \gamma \sqrt{\frac{3.0}{\text{fan}}}
where :math:`\text{fan}` is either the number of input units when the
``mode`` is ``"fan_in"`` or output units when the ``mode`` is
``"fan_out"``.
For more details see the original reference: `Delving Deep into Rectifiers:
Surpassing Human-Level Performance on ImageNet Classification
<https://arxiv.org/abs/1502.01852>`_
Args:
dtype (Dtype, optional): The data type of the array. Default: ``float32``.
Returns:
Callable[[array, str, float], array]: An initializer that returns an
array with the same shape as the input, filled with samples from the
He uniform distribution.
Example:
>>> init_fn = nn.init.he_uniform()
>>> init_fn(mx.zeros((2, 2))) # uses fan_in
array([[0.0300242, -0.0184009],
[0.793615, 0.666329]], dtype=float32)
>>> init_fn(mx.zeros((2, 2)), mode="fan_out", gain=5)
array([[-1.64331, -2.16506],
[1.08619, 5.79854]], dtype=float32)
"""
def sparse(
sparsity: float, mean: float = ..., std: float = ..., dtype: mx.Dtype = ...
) -> Callable[[mx.array], mx.array]:
r"""An initializer that returns a sparse matrix.
Args:
sparsity (float): The fraction of elements in each column to be set to
zero.
mean (float, optional): Mean of the normal distribution. Default:
``0.0``.
std (float, optional): Standard deviation of the normal distribution.
Default: ``1.0``.
dtype (Dtype, optional): The data type of the array. Default:
``float32``.
Returns:
Callable[[array], array]: An initializer that returns an array with the
same shape as the input, filled with samples from a normal distribution.
Example:
>>> init_fn = nn.init.sparse(sparsity=0.5)
>>> init_fn(mx.zeros((2, 2)))
array([[-1.91187, -0.117483],
[0, 0]], dtype=float32)
"""
def orthogonal(
gain: float = ..., dtype: mx.Dtype = ...
) -> Callable[[mx.array], mx.array]:
r"""An initializer that returns an orthogonal matrix.
Args:
gain (float, optional): Scaling factor for the orthogonal matrix.
Default: ``1.0``.
dtype (Dtype, optional): Data type of the array. Default: ``float32``.
Returns:
Callable[[array], array]: An initializer that returns
an orthogonal matrix with the same shape as the input.
"""

View File

@@ -0,0 +1,20 @@
"""
This type stub file was generated by pyright.
"""
from activations import *
from base import *
from containers import *
from convolution import *
from convolution_transpose import *
from distributed import *
from dropout import *
from embedding import *
from linear import *
from normalization import *
from pooling import *
from positional_encoding import *
from quantized import *
from recurrent import *
from transformer import *
from upsample import *

View File

@@ -0,0 +1,523 @@
"""
This type stub file was generated by pyright.
"""
from functools import partial
from typing import Any
import mlx.core as mx
from base import Module
@partial(mx.compile, shapeless=True)
def sigmoid(x: mx.array) -> mx.array:
r"""Applies the sigmoid function.
.. math::
\text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)}
"""
@partial(mx.compile, shapeless=True)
def relu(x: mx.array) -> mx.array:
r"""Applies the Rectified Linear Unit.
Simply ``mx.maximum(x, 0)``.
"""
@partial(mx.compile, shapeless=True)
def relu2(x: mx.array) -> mx.array:
r"""Applies the ReLU² activation function.
Applies :math:`\max(0, x)^2` element wise.
"""
@partial(mx.compile, shapeless=True)
def relu6(x: mx.array) -> mx.array:
r"""Applies the Rectified Linear Unit 6.
Applies :math:`\min(\max(x, 0), 6)` element wise.
"""
@partial(mx.compile, shapeless=True)
def leaky_relu(x: mx.array, negative_slope=...) -> mx.array:
r"""Applies the Leaky Rectified Linear Unit.
Simply ``mx.maximum(negative_slope * x, x)``.
"""
@partial(mx.compile, shapeless=True)
def log_softmax(x: mx.array, axis=...):
r"""Applies the Log Softmax function.
Applies :math:`x + \log \sum_i e^{x_i}` element wise.
"""
@partial(mx.compile, shapeless=True)
def elu(x: mx.array, alpha=...) -> mx.array:
r"""Applies the Exponential Linear Unit.
Simply ``mx.where(x > 0, x, alpha * (mx.exp(x) - 1))``.
"""
@partial(mx.compile, shapeless=True)
def softmax(x: mx.array, axis=...) -> mx.array:
r"""Applies the Softmax function.
Applies :math:`\frac{e^{x_i}}{\sum_j e^{x_j}}` element wise.
"""
@partial(mx.compile, shapeless=True)
def softplus(x: mx.array) -> mx.array:
r"""Applies the Softplus function.
Applies :math:`\log(1 + \exp(x))` element wise.
"""
@partial(mx.compile, shapeless=True)
def softsign(x: mx.array) -> mx.array:
r"""Applies the Softsign function.
Applies :math:`\frac{x}{1 + |x|}` element wise.
"""
@partial(mx.compile, shapeless=True)
def softshrink(x: mx.array, lambd: float = ...) -> mx.array:
r"""Applies the Softshrink activation function.
.. math::
\text{softshrink}(x) = \begin{cases}
x - \lambda & \text{if } x > \lambda \\
x + \lambda & \text{if } x < -\lambda \\
0 & \text{otherwise}
\end{cases}
"""
@partial(mx.compile, shapeless=True)
def celu(x: mx.array, alpha=...) -> mx.array:
r"""Applies the Continuously Differentiable Exponential Linear Unit.
Applies :math:`\max(0, x) + \min(0, \alpha * (\exp(x / \alpha) - 1))`
element wise.
"""
@partial(mx.compile, shapeless=True)
def silu(x: mx.array) -> mx.array:
r"""Applies the Sigmoid Linear Unit. Also known as Swish.
Applies :math:`x \sigma(x)` element wise, where :math:`\sigma(\cdot)` is
the logistic sigmoid.
"""
@partial(mx.compile, shapeless=True)
def log_sigmoid(x: mx.array) -> mx.array:
r"""Applies the Log Sigmoid function.
Applies :math:`\log(\sigma(x)) = -\log(1 + e^{-x})` element wise.
"""
@partial(mx.compile, shapeless=True)
def gelu(x: mx.array) -> mx.array:
r"""Applies the Gaussian Error Linear Units function.
.. math::
\textrm{GELU}(x) = x * \Phi(x)
where :math:`\Phi(x)` is the Gaussian CDF.
See also :func:`gelu_approx` and :func:`gelu_fast_approx` for faster
approximations.
"""
@partial(mx.compile, shapeless=True)
def gelu_approx(x: mx.array) -> mx.array:
r"""An approximation to Gaussian Error Linear Unit.
See :func:`gelu` for the exact computation.
This function approximates ``gelu`` with a maximum absolute error :math:`<
0.0005` in the range :math:`[-6, 6]` using the following
.. math::
x = 0.5 * x * \left(1 + \text{Tanh}\left((\sqrt{2 / \pi} * \left(x + 0.044715 * x^3\right)\right)\right)
"""
@partial(mx.compile, shapeless=True)
def gelu_fast_approx(x: mx.array) -> mx.array:
r"""A fast approximation to Gaussian Error Linear Unit.
See :func:`gelu` for the exact computation.
This function approximates ``gelu`` with a maximum absolute error :math:`<
0.015` in the range :math:`[-6, 6]` using the following
.. math::
x = x \sigma\left(1.702 x\right)
where :math:`\sigma(\cdot)` is the logistic sigmoid.
References:
- https://github.com/hendrycks/GELUs
- https://arxiv.org/abs/1606.08415
"""
def glu(x: mx.array, axis: int = ...) -> mx.array:
r"""Applies the gated linear unit function.
This function splits the ``axis`` dimension of the input into two halves
(:math:`a` and :math:`b`) and applies :math:`a * \sigma(b)`.
.. math::
\textrm{GLU}(x) = a * \sigma(b)
Args:
axis (int): The dimension to split along. Default: ``-1``
"""
@partial(mx.compile, shapeless=True)
def step(x: mx.array, threshold: float = ...) -> mx.array:
r"""Applies the Step Activation Function.
This function implements a binary step activation, where the output is set
to 1 if the input is greater than a specified threshold, and 0 otherwise.
.. math::
\text{step}(x) = \begin{cases}
0 & \text{if } x < \text{threshold} \\
1 & \text{if } x \geq \text{threshold}
\end{cases}
Args:
threshold: The value to threshold at.
"""
@partial(mx.compile, shapeless=True)
def selu(x: mx.array) -> mx.array:
r"""Applies the Scaled Exponential Linear Unit.
.. math::
\text{selu}(x) = \begin{cases}
\lambda x & \text{if } x > 0 \\
\lambda \alpha (\exp(x) - 1) & \text{if } x \leq 0
\end{cases}
where :math:`\lambda = 1.0507` and :math:`\alpha = 1.67326`.
See also :func:`elu`.
"""
@partial(mx.compile, shapeless=True)
def prelu(x: mx.array, alpha: mx.array) -> mx.array:
r"""Applies the element-wise parametric ReLU.
.. math::
\text{PReLU}(x) = \max(0,x) + a * \min(0,x)
where :math:`a` is an array.
"""
@partial(mx.compile, shapeless=True)
def mish(x: mx.array) -> mx.array:
r"""Applies the Mish function, element-wise.
Mish: A Self Regularized Non-Monotonic Neural Activation Function.
Reference: https://arxiv.org/abs/1908.08681
.. math::
\text{Mish}(x) = x * \text{Tanh}(\text{Softplus}(x))
"""
@partial(mx.compile, shapeless=True)
def hardswish(x: mx.array) -> mx.array:
r"""Applies the hardswish function, element-wise.
.. math::
\text{Hardswish}(x) = x * \min(\max(x + 3, 0), 6) / 6
"""
@partial(mx.compile, shapeless=True)
def hard_tanh(x: mx.array, min_val=..., max_val=...) -> mx.array:
r"""Applies the HardTanh function.
Applies :math:`\max(\min(x, \text{max\_val}), \text{min\_val})` element-wise.
"""
@partial(mx.compile, shapeless=True)
def hard_shrink(x: mx.array, lambd=...) -> mx.array:
r"""Applies the HardShrink activation function.
.. math::
\text{hardshrink}(x) = \begin{cases}
x & \text{if } x > \lambda \\
x & \text{if } x < -\lambda \\
0 & \text{otherwise}
\end{cases}
"""
@partial(mx.compile, shapeless=True)
def softmin(x: mx.array, axis=...) -> mx.array:
r"""Applies the Softmin function.
Applies :math:`\frac{e^{-x_i}}{\sum_j e^{-x_j}}` element-wise.
"""
def tanh(x: mx.array) -> mx.array:
"""Applies the hyperbolic tangent function.
Simply ``mx.tanh(x)``.
"""
class GLU(Module):
r"""Applies the gated linear unit function.
This function splits the ``axis`` dimension of the input into two halves
(:math:`a` and :math:`b`) and applies :math:`a * \sigma(b)`.
.. math::
\textrm{GLU}(x) = a * \sigma(b)
Args:
axis (int): The dimension to split along. Default: ``-1``
"""
def __init__(self, axis: int = ...) -> None: ...
def __call__(self, x) -> Any: ...
@_make_activation_module(sigmoid)
class Sigmoid(Module):
r"""Applies the sigmoid function, element-wise.
.. math::
\text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)}
"""
@_make_activation_module(mish)
class Mish(Module):
r"""Applies the Mish function, element-wise.
Reference: https://arxiv.org/abs/1908.08681
.. math::
\text{Mish}(x) = x * \text{Tanh}(\text{Softplus}(x))
"""
@_make_activation_module(relu)
class ReLU(Module):
r"""Applies the Rectified Linear Unit.
Simply ``mx.maximum(x, 0)``.
See :func:`relu` for the functional equivalent.
"""
@_make_activation_module(relu2)
class ReLU2(Module):
r"""Applies the ReLU² activation function.
See :func:`relu2` for the functional equivalent.
"""
@_make_activation_module(relu6)
class ReLU6(Module):
r"""Applies the Rectified Linear Unit 6.
See :func:`relu6` for the functional equivalent.
"""
class LeakyReLU(Module):
r"""Applies the Leaky Rectified Linear Unit.
Simply ``mx.maximum(negative_slope * x, x)``.
Args:
negative_slope: Controls the angle of the negative slope. Default: ``1e-2``
"""
def __init__(self, negative_slope=...) -> None: ...
def __call__(self, x): ...
class ELU(Module):
r"""Applies the Exponential Linear Unit.
Simply ``mx.where(x > 0, x, alpha * (mx.exp(x) - 1))``.
See :func:`elu` for the functional equivalent.
Args:
alpha: the :math:`\alpha` value for the ELU formulation. Default: ``1.0``
"""
def __init__(self, alpha=...) -> None: ...
def __call__(self, x): ...
@_make_activation_module(softmax)
class Softmax(Module):
r"""Applies the Softmax function.
See :func:`softmax` for the functional equivalent.
"""
@_make_activation_module(softplus)
class Softplus(Module):
r"""Applies the Softplus function.
See :func:`softplus` for the functional equivalent.
"""
@_make_activation_module(softsign)
class Softsign(Module):
r"""Applies the Softsign function.
See :func:`softsign` for the functional equivalent.
"""
class Softshrink(Module):
r"""Applies the Softshrink function.
See :func:`softshrink` for the functional equivalent.
Args:
lambd: the :math:`\lambda` value for Softshrink. Default: ``0.5``
"""
def __init__(self, lambd=...) -> None: ...
def __call__(self, x): ...
class CELU(Module):
r"""Applies the Continuously Differentiable Exponential Linear Unit.
Applies :math:`\max(0, x) + \min(0, \alpha * (\exp(x / \alpha) - 1))`
element wise.
See :func:`celu` for the functional equivalent.
Args:
alpha: the :math:`\alpha` value for the CELU formulation. Default: ``1.0``
"""
def __init__(self, alpha=...) -> None: ...
def __call__(self, x): ...
@_make_activation_module(silu)
class SiLU(Module):
r"""Applies the Sigmoid Linear Unit. Also known as Swish.
See :func:`silu` for the functional equivalent.
"""
@_make_activation_module(log_softmax)
class LogSoftmax(Module):
r"""Applies the Log Softmax function.
See :func:`log_softmax` for the functional equivalent.
"""
@_make_activation_module(log_sigmoid)
class LogSigmoid(Module):
r"""Applies the Log Sigmoid function.
See :func:`log_sigmoid` for the functional equivalent.
"""
class PReLU(Module):
r"""Applies the element-wise parametric ReLU.
Applies :math:`\max(0, x) + a * \min(0, x)` element wise, where :math:`a`
is an array.
See :func:`prelu` for the functional equivalent.
Args:
num_parameters: number of :math:`a` to learn. Default: ``1``
init: the initial value of :math:`a`. Default: ``0.25``
"""
def __init__(self, num_parameters=..., init=...) -> None: ...
def __call__(self, x: mx.array): ...
class GELU(Module):
r"""Applies the Gaussian Error Linear Units.
.. math::
\textrm{GELU}(x) = x * \Phi(x)
where :math:`\Phi(x)` is the Gaussian CDF.
However, if ``approx`` is set to 'precise' or 'fast' it applies
.. math::
\textrm{GELUApprox}(x) &= 0.5 * x * \left(1 + \text{Tanh}\left((\sqrt{2 / \pi} * \left(x + 0.044715 * x^3\right)\right)\right) \\
\textrm{GELUFast}(x) &= x * \sigma\left(1.702 * x\right)
respectively.
.. note::
For compatibility with the PyTorch API, 'tanh' can be used as an alias
for 'precise'.
See :func:`gelu`, :func:`gelu_approx` and :func:`gelu_fast_approx` for the
functional equivalents and information regarding error bounds.
Args:
approx ('none' | 'precise' | 'fast'): Which approximation to gelu to use if any.
"""
def __init__(self, approx=...) -> None: ...
def __call__(self, x): ...
@_make_activation_module(tanh)
class Tanh(Module):
r"""Applies the hyperbolic tangent function.
See :func:`tanh` for the functional equivalent.
"""
@_make_activation_module(hardswish)
class Hardswish(Module):
r"""Applies the hardswish function, element-wise.
See :func:`hardswish` for the functional equivalent.
"""
class Step(Module):
r"""Applies the Step Activation Function.
This function implements a binary step activation, where the output is set
to 1 if the input is greater than a specified threshold, and 0 otherwise.
.. math::
\text{step}(x) = \begin{cases}
0 & \text{if } x < \text{threshold} \\
1 & \text{if } x \geq \text{threshold}
\end{cases}
Args:
threshold: The value to threshold at.
"""
def __init__(self, threshold: float = ...) -> None: ...
def __call__(self, x: mx.array): ...
@_make_activation_module(selu)
class SELU(Module):
r"""Applies the Scaled Exponential Linear Unit.
See :func:`selu` for the functional equivalent.
"""
@_make_activation_module(hard_tanh)
class HardTanh(Module):
r"""Applies the HardTanh function.
See :func:`hard_tanh` for the functional equivalent.
"""
@_make_activation_module(hard_shrink)
class HardShrink(Module):
r"""Applies the HardShrink function.
See :func:`hard_shrink` for the functional equivalent.
Args:
lambd: the :math:`\lambda` value for Hardshrink. Default: ``0.5``
"""
@_make_activation_module(softmin)
class Softmin(Module):
r"""Applies the Softmin function.
See :func:`softmin` for the functional equivalent.
"""

View File

@@ -0,0 +1,393 @@
"""
This type stub file was generated by pyright.
"""
from typing import Any, Callable, List, Optional, Tuple, Union
import mlx.core as mx
class Module(dict):
"""Base class for building neural networks with MLX.
All the layers provided in :mod:`layers` subclass this class and
your models should do the same.
A ``Module`` can contain other ``Module`` instances or :class:`mlx.core.array`
instances in arbitrary nesting of python lists or dicts. The ``Module``
then allows recursively extracting all the :class:`mlx.core.array` instances
using :meth:`Module.parameters`.
In addition, the ``Module`` has the concept of trainable and non trainable
parameters (called "frozen"). When using :func:`value_and_grad`
the gradients are returned only with respect to the trainable parameters.
All arrays in a module are trainable unless they are added in the "frozen"
set by calling :meth:`freeze`.
.. code-block:: python
import mlx.core as mx
import mlx.nn as nn
class MyMLP(nn.Module):
def __init__(self, in_dims: int, out_dims: int, hidden_dims: int = 16):
super().__init__()
self.in_proj = nn.Linear(in_dims, hidden_dims)
self.out_proj = nn.Linear(hidden_dims, out_dims)
def __call__(self, x):
x = self.in_proj(x)
x = mx.maximum(x, 0)
return self.out_proj(x)
model = MyMLP(2, 1)
# All the model parameters are created but since MLX is lazy by
# default, they are not evaluated yet. Calling `mx.eval` actually
# allocates memory and initializes the parameters.
mx.eval(model.parameters())
# Setting a parameter to a new value is as simply as accessing that
# parameter and assigning a new array to it.
model.in_proj.weight = model.in_proj.weight * 2
mx.eval(model.parameters())
"""
__call__: Callable
def __init__(self) -> None:
"""Should be called by the subclasses of ``Module``."""
@property
def training(self): # -> bool:
"""Boolean indicating if the model is in training mode."""
@property
def state(self): # -> Self:
"""The module's state dictionary
The module's state dictionary contains any attribute set on the
module including parameters in :meth:`Module.parameters`
Unlike :meth:`Module.parameters`, the :attr:`Module.state` property is
a reference to the module's state. Updates to it will be reflected in
the original module.
"""
def __repr__(self): # -> str:
...
def __getattr__(self, key: str): # -> None:
...
def __setattr__(self, key: str, val: Any): # -> None:
...
def __delattr__(self, name): # -> None:
...
def load_weights(
self,
file_or_weights: Union[str, List[Tuple[str, mx.array]]],
strict: bool = ...,
) -> Module:
"""
Update the model's weights from a ``.npz``, a ``.safetensors`` file, or a list.
Args:
file_or_weights (str or list(tuple(str, mx.array))): The path to
the weights ``.npz`` file (``.npz`` or ``.safetensors``) or a list
of pairs of parameter names and arrays.
strict (bool, optional): If ``True`` then checks that the provided
weights exactly match the parameters of the model. Otherwise,
only the weights actually contained in the model are loaded and
shapes are not checked. Default: ``True``.
Returns:
The module instance after updating the weights.
Example:
.. code-block:: python
import mlx.core as mx
import mlx.nn as nn
model = nn.Linear(10, 10)
# Load from file
model.load_weights("weights.npz")
# Load from .safetensors file
model.load_weights("weights.safetensors")
# Load from list
weights = [
("weight", mx.random.uniform(shape=(10, 10))),
("bias", mx.zeros((10,))),
]
model.load_weights(weights)
# Missing weight
weights = [
("weight", mx.random.uniform(shape=(10, 10))),
]
# Raises a ValueError exception
model.load_weights(weights)
# Ok, only updates the weight but not the bias
model.load_weights(weights, strict=False)
"""
def save_weights(self, file: str): # -> None:
"""
Save the model's weights to a file. The saving method is determined by the file extension:
- ``.npz`` will use :func:`mx.savez`
- ``.safetensors`` will use :func:`mx.save_safetensors`
"""
@staticmethod
def is_module(value): # -> bool:
...
@staticmethod
def valid_child_filter(module, key, value): # -> bool:
...
@staticmethod
def valid_parameter_filter(module, key, value): # -> bool:
...
@staticmethod
def trainable_parameter_filter(module, key, value): # -> bool:
...
def filter_and_map(
self,
filter_fn: Callable[[Module, str, Any], bool],
map_fn: Optional[Callable] = ...,
is_leaf_fn: Optional[Callable[[Module, str, Any], bool]] = ...,
): # -> dict[Any, Any | dict[Any, Any | dict[Any, Any] | list[Any]] | dict[Any, Any] | list[Any]]:
"""Recursively filter the contents of the module using ``filter_fn``,
namely only select keys and values where ``filter_fn`` returns true.
This is used to implement :meth:`parameters` and :meth:`trainable_parameters`
but it can also be used to extract any subset of the module's parameters.
Args:
filter_fn (Callable): Given a value, the key in which it is found
and the containing module, decide whether to keep the value or
drop it.
map_fn (Callable, optional): Optionally transform the value before
returning it.
is_leaf_fn (Callable, optional): Given a value, the key in which it
is found and the containing module decide if it is a leaf.
Returns:
A dictionary containing the contents of the module recursively filtered
"""
def parameters(
self,
) -> mx.MX_ARRAY_TREE:
"""Recursively return all the :class:`mlx.core.array` members of this Module
as a dict of dicts and lists."""
def trainable_parameters(
self,
) -> mx.MX_ARRAY_TREE: # -> dict[Any, Any | dict[Any, Any | dict[Any, Any] | list[Any]] | dict[Any, Any] | list[Any]]:
"""Recursively return all the non frozen :class:`mlx.core.array` members of
this Module as a dict of dicts and lists."""
def children(
self,
) -> mx.MX_ARRAY_TREE: # -> dict[Any, Any | dict[Any, Any | dict[Any, Any] | list[Any]] | dict[Any, Any] | list[Any]]:
"""Return the direct descendants of this Module instance."""
def leaf_modules(
self,
) -> mx.MX_ARRAY_TREE: # -> dict[Any, Any | dict[Any, Any | dict[Any, Any] | list[Any]] | dict[Any, Any] | list[Any]]:
"""Return the submodules that do not contain other modules."""
def update(self, parameters: dict, strict: bool = ...) -> Module:
"""Replace the parameters of this Module with the provided ones in the
dict of dicts and lists.
Commonly used by the optimizer to change the model to the updated
(optimized) parameters. Also used by the :meth:`value_and_grad` to set the
tracers in the model in order to compute gradients.
The passed in parameters dictionary need not be a full dictionary
similar to :meth:`parameters`. Only the provided locations will be
updated.
Args:
parameters (dict): A complete or partial dictionary of the modules
parameters.
strict (bool): If ``True`` checks that ``parameters`` is a
subset of the module's parameters. Default: ``True``.
Returns:
The module instance after updating the parameters.
"""
def apply(
self,
map_fn: Callable[[mx.array], mx.array],
filter_fn: Optional[Callable[[Module, str, Any], bool]] = ...,
) -> Module:
"""Map all the parameters using the provided ``map_fn`` and immediately
update the module with the mapped parameters.
For instance running ``model.apply(lambda x: x.astype(mx.float16))``
casts all parameters to 16 bit floats.
Args:
map_fn (Callable): Maps an array to another array
filter_fn (Callable, optional): Filter to select which arrays to
map (default: :meth:`Module.valid_parameter_filter`).
Returns:
The module instance after updating the parameters.
"""
def update_modules(self, modules: dict, strict: bool = ...) -> Module:
"""Replace the child modules of this :class:`Module` instance with the
provided ones in the dict of dicts and lists.
It is the equivalent of :meth:`Module.update` but for modules instead
of parameters and allows us to flexibly edit complex architectures by
programmatically swapping layers.
The passed in parameters dictionary need not be a full dictionary
similar to :meth:`modules`. Only the provided locations will be
updated.
Args:
modules (dict): A complete or partial dictionary of the module's
submodules.
strict (bool): If ``True`` checks that ``modules`` is a
subset of the child modules of this instance. Default: ``True``.
Returns:
The module instance after updating the submodules.
"""
def apply_to_modules(self, apply_fn: Callable[[str, Module], Any]) -> Module:
"""Apply a function to all the modules in this instance (including this
instance).
Args:
apply_fn (Callable): The function to apply to the modules.
Returns:
The module instance after updating submodules.
"""
def modules(self): # -> list[Any]:
"""Return a list with all the modules in this instance.
Returns:
A list of :class:`Module` instances.
"""
def named_modules(self): # -> list[Any]:
"""Return a list with all the modules in this instance and their name
with dot notation.
Returns:
A list of tuples (str, :class:`Module`).
"""
def freeze(
self,
*,
recurse: bool = ...,
keys: Optional[Union[str, List[str]]] = ...,
strict: bool = ...,
) -> Module:
"""Freeze the Module's parameters or some of them. Freezing a parameter means not
computing gradients for it.
This function is idempotent i.e. freezing a frozen model is a no-op.
Example:
For instance to only train the attention parameters from a Transformer:
.. code-block:: python
model = nn.Transformer()
model.freeze()
model.apply_to_modules(lambda k, v: v.unfreeze() if k.endswith("attention") else None)
Args:
recurse (bool, optional): If True then freeze the parameters of the
submodules as well. Default: ``True``.
keys (str or list[str], optional): If provided then only these
parameters will be frozen otherwise all the parameters of a
module. For instance freeze all biases by calling
``module.freeze(keys="bias")``.
strict (bool, optional): If set to ``True`` validate that the passed keys exist.
Default: ``False``.
Returns:
The module instance after freezing the parameters.
"""
def unfreeze(
self,
*,
recurse: bool = ...,
keys: Optional[Union[str, List[str]]] = ...,
strict: bool = ...,
) -> Module:
"""Unfreeze the Module's parameters or some of them.
This function is idempotent ie unfreezing a model that is not frozen is
a noop.
Example:
For instance to only train the biases of a Transformer one can do:
.. code-block:: python
model = nn.Transformer()
model.freeze()
model.unfreeze(keys="bias")
Args:
recurse (bool, optional): If True then unfreeze the parameters of the
submodules as well. Default: ``True``.
keys (str or list[str], optional): If provided then only these
parameters will be unfrozen otherwise all the parameters of a
module. For instance unfreeze all biases by calling
``module.unfreeze(keys="bias")``.
strict (bool, optional): If set to ``True`` validate that the passed keys exist.
Default: ``False``.
Returns:
The module instance after unfreezing the parameters.
"""
def train(self, mode: bool = ...) -> Module:
"""Set the model in or out of training mode.
Training mode only applies to certain layers. For example
:obj:`Dropout` applies a random mask in training mode, but is the
identity in evaluation mode.
Args:
mode (bool): Indicate if the model should be in training or
evaluation mode. Default: ``True``.
Returns:
The module instance after updating the training mode.
"""
def eval(self) -> Module:
"""Set the model to evaluation mode.
See :func:`train`.
"""
def set_dtype(
self, dtype: mx.Dtype, predicate: Optional[Callable[[mx.Dtype], bool]] = ...
): # -> None:
"""Set the dtype of the module's parameters.
Args:
dtype (Dtype): The new dtype.
predicate (typing.Callable, optional): A predicate to select
parameters to cast. By default, only parameters of type
:attr:`floating` will be updated to avoid casting integer
parameters to the new dtype.
"""

View File

@@ -0,0 +1,21 @@
"""
This type stub file was generated by pyright.
"""
from typing import Callable
import mlx.core as mx
from base import Module
class Sequential(Module):
"""A layer that calls the passed callables in order.
We can pass either modules or plain callables to the Sequential module. If
our functions have learnable parameters they should be implemented as
``nn.Module`` instances.
Args:
modules (tuple of Callables): The modules to call in order
"""
def __init__(self, *modules: Module | Callable[[mx.array], mx.array]) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...

View File

@@ -0,0 +1,116 @@
"""
This type stub file was generated by pyright.
"""
from typing import Union
import mlx.core as mx
from base import Module
class Conv1d(Module):
"""Applies a 1-dimensional convolution over the multi-channel input sequence.
The channels are expected to be last i.e. the input shape should be ``NLC`` where:
* ``N`` is the batch dimension
* ``L`` is the sequence length
* ``C`` is the number of input channels
Args:
in_channels (int): The number of input channels
out_channels (int): The number of output channels
kernel_size (int): The size of the convolution filters
stride (int, optional): The stride when applying the filter.
Default: ``1``.
padding (int, optional): How many positions to 0-pad the input with.
Default: ``0``.
dilation (int, optional): The dilation of the convolution.
groups (int, optional): The number of groups for the convolution.
Default: ``1``.
bias (bool, optional): If ``True`` add a learnable bias to the output.
Default: ``True``
"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = ...,
padding: int = ...,
dilation: int = ...,
groups: int = ...,
bias: bool = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
class Conv2d(Module):
"""Applies a 2-dimensional convolution over the multi-channel input image.
The channels are expected to be last i.e. the input shape should be ``NHWC`` where:
* ``N`` is the batch dimension
* ``H`` is the input image height
* ``W`` is the input image width
* ``C`` is the number of input channels
Args:
in_channels (int): The number of input channels.
out_channels (int): The number of output channels.
kernel_size (int or tuple): The size of the convolution filters.
stride (int or tuple, optional): The size of the stride when
applying the filter. Default: ``1``.
padding (int or tuple, optional): How many positions to 0-pad
the input with. Default: ``0``.
dilation (int or tuple, optional): The dilation of the convolution.
groups (int, optional): The number of groups for the convolution.
Default: ``1``.
bias (bool, optional): If ``True`` add a learnable bias to the
output. Default: ``True``
"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: Union[int, tuple],
stride: Union[int, tuple] = ...,
padding: Union[int, tuple] = ...,
dilation: Union[int, tuple] = ...,
groups: int = ...,
bias: bool = ...,
) -> None: ...
def __call__(self, x) -> mx.array: ...
class Conv3d(Module):
"""Applies a 3-dimensional convolution over the multi-channel input image.
The channels are expected to be last i.e. the input shape should be ``NDHWC`` where:
* ``N`` is the batch dimension
* ``D`` is the input image depth
* ``H`` is the input image height
* ``W`` is the input image width
* ``C`` is the number of input channels
Args:
in_channels (int): The number of input channels.
out_channels (int): The number of output channels.
kernel_size (int or tuple): The size of the convolution filters.
stride (int or tuple, optional): The size of the stride when
applying the filter. Default: ``1``.
dilation (int or tuple, optional): The dilation of the convolution.
padding (int or tuple, optional): How many positions to 0-pad
the input with. Default: ``0``.
bias (bool, optional): If ``True`` add a learnable bias to the
output. Default: ``True``
"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: Union[int, tuple],
stride: Union[int, tuple] = ...,
padding: Union[int, tuple] = ...,
dilation: Union[int, tuple] = ...,
bias: bool = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...

View File

@@ -0,0 +1,119 @@
"""
This type stub file was generated by pyright.
"""
from typing import Union
import mlx.core as mx
from base import Module
class ConvTranspose1d(Module):
"""Applies a 1-dimensional transposed convolution over the multi-channel input sequence.
The channels are expected to be last i.e. the input shape should be ``NLC`` where:
* ``N`` is the batch dimension
* ``L`` is the sequence length
* ``C`` is the number of input channels
Args:
in_channels (int): The number of input channels
out_channels (int): The number of output channels
kernel_size (int): The size of the convolution filters
stride (int, optional): The stride when applying the filter.
Default: ``1``.
padding (int, optional): How many positions to 0-pad the input with.
Default: ``0``.
dilation (int, optional): The dilation of the convolution.
output_padding(int, optional): Additional size added to one side of the
output shape. Default: ``0``.
bias (bool, optional): If ``True`` add a learnable bias to the output.
Default: ``True``
"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = ...,
padding: int = ...,
dilation: int = ...,
output_padding: int = ...,
bias: bool = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
class ConvTranspose2d(Module):
"""Applies a 2-dimensional transposed convolution over the multi-channel input image.
The channels are expected to be last i.e. the input shape should be ``NHWC`` where:
* ``N`` is the batch dimension
* ``H`` is the input image height
* ``W`` is the input image width
* ``C`` is the number of input channels
Args:
in_channels (int): The number of input channels.
out_channels (int): The number of output channels.
kernel_size (int or tuple): The size of the convolution filters.
stride (int or tuple, optional): The size of the stride when
applying the filter. Default: ``1``.
padding (int or tuple, optional): How many positions to 0-pad
the input with. Default: ``0``.
dilation (int or tuple, optional): The dilation of the convolution.
output_padding(int or tuple, optional): Additional size added to one
side of the output shape. Default: ``0``.
bias (bool, optional): If ``True`` add a learnable bias to the
output. Default: ``True``
"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: Union[int, tuple],
stride: Union[int, tuple] = ...,
padding: Union[int, tuple] = ...,
dilation: Union[int, tuple] = ...,
output_padding: Union[int, tuple] = ...,
bias: bool = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
class ConvTranspose3d(Module):
"""Applies a 3-dimensional transposed convolution over the multi-channel input image.
The channels are expected to be last i.e. the input shape should be ``NDHWC`` where:
* ``N`` is the batch dimension
* ``D`` is the input image depth
* ``H`` is the input image height
* ``W`` is the input image width
* ``C`` is the number of input channels
Args:
in_channels (int): The number of input channels.
out_channels (int): The number of output channels.
kernel_size (int or tuple): The size of the convolution filters.
stride (int or tuple, optional): The size of the stride when
applying the filter. Default: ``1``.
padding (int or tuple, optional): How many positions to 0-pad
the input with. Default: ``0``.
dilation (int or tuple, optional): The dilation of the convolution.
output_padding(int or tuple, optional): Additional size added to one
side of the output shape. Default: ``0``.
bias (bool, optional): If ``True`` add a learnable bias to the
output. Default: ``True``
"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: Union[int, tuple],
stride: Union[int, tuple] = ...,
padding: Union[int, tuple] = ...,
dilation: Union[int, tuple] = ...,
output_padding: Union[int, tuple] = ...,
bias: bool = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...

View File

@@ -0,0 +1,227 @@
"""
This type stub file was generated by pyright.
"""
from functools import lru_cache
from typing import Callable, Optional, Union
import mlx.core as mx
from base import Module
from mlx.nn.layers.linear import Linear
@lru_cache
def sum_gradients(
group: mx.distributed.Group,
) -> Callable[..., mx.array]: # -> Callable[..., Any] | Callable[..., array]:
...
def shard_inplace(
module: Module,
sharding: str,
*,
segments: Union[int, list[int]] = ...,
group: Optional[mx.distributed.Group] = ...,
) -> None:
"""Shard a module in-place by updating its parameter dictionary with the
sharded parameter dictionary.
The ``sharding`` argument can be any callable that given the path and the
weight returns the sharding axis and optionally also the segments that
comprise the unsharded weight. For instance if the weight is a fused QKV
matrix the segments should be 3.
.. note::
The module doesn't change so in order for distributed communication to
happen the module needs to natively support it and for it to be enabled.
Args:
module (Module): The parameters of this module will be sharded
in-place.
sharding (str or callable): One of "all-to-sharded" and
"sharded-to-all" or a callable that returns the sharding axis and
segments.
segments (int or list): The segments to use if ``sharding`` is a
string. Default: ``1``.
group (mlx.core.distributed.Group): The distributed group to shard
across. If not set, the global group will be used. Default: ``None``.
"""
def shard_linear(
module: Module,
sharding: str,
*,
segments: Union[int, list[int]] = ...,
group: Optional[mx.distributed.Group] = ...,
) -> Linear:
"""Create a new linear layer that has its parameters sharded and also
performs distributed communication either in the forward or backward
pass.
.. note::
Contrary to ``shard_inplace``, the original layer is not changed but a
new layer is returned.
Args:
module (Module): The linear layer to be sharded.
sharding (str): One of "all-to-sharded" and
"sharded-to-all" that defines the type of sharding to perform.
segments (int or list): The segments to use. Default: ``1``.
group (mlx.core.distributed.Group): The distributed group to shard
across. If not set, the global group will be used. Default: ``None``.
"""
class AllToShardedLinear(Module):
"""Each member of the group applies part of the affine transformation such
that the result is sharded across the group.
The gradients are automatically aggregated from each member of the group.
Args:
input_dims (int): The dimensionality of the input features
output_dims (int): The dimensionality of the output features
bias (bool, optional): If set to ``False`` the the layer will not use a
bias. Default is ``True``.
group (mx.distributed.Group, optional): The sharding will happen across
this group. If not set then the global group is used. Default is
``None``.
"""
def __init__(
self,
input_dims: int,
output_dims: int,
bias: bool = ...,
group: Optional[mx.distributed.Group] = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
@classmethod
def from_linear(
cls,
linear_layer: Module,
*,
segments: Union[int, list[int]] = ...,
group: Optional[mx.distributed.Group] = ...,
) -> AllToShardedLinear: ...
class ShardedToAllLinear(Module):
"""Each member of the group applies part of the affine transformation and
then aggregates the results.
All nodes will have the same exact result after this layer.
:class:`ShardedToAllLinear` provides a classmethod :meth:`from_linear` to
convert linear layers to sharded :obj:`ShardedToAllLinear` layers.
Args:
input_dims (int): The dimensionality of the input features
output_dims (int): The dimensionality of the output features
bias (bool, optional): If set to ``False`` the the layer will not use a
bias. Default is ``True``.
group (mx.distributed.Group, optional): The sharding will happen across
this group. If not set then the global group is used. Default is
``None``.
"""
def __init__(
self,
input_dims: int,
output_dims: int,
bias: bool = ...,
group: Optional[mx.distributed.Group] = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
@classmethod
def from_linear(
cls,
linear_layer: Module,
*,
segments: Union[int, list[int]] = ...,
group: Optional[mx.distributed.Group] = ...,
) -> ShardedToAllLinear: ...
class QuantizedAllToShardedLinear(Module):
"""Each member of the group applies part of the affine transformation with
a quantized matrix such that the result is sharded across the group.
It is the quantized equivalent of :class:`AllToShardedLinear`.
Similar to :class:`QuantizedLinear` its parameters are frozen and
will not be included in any gradient computation.
Args:
input_dims (int): The dimensionality of the input features.
output_dims (int): The dimensionality of the output features.
bias (bool, optional): If set to ``False`` then the layer will not use
a bias. Default: ``True``.
group_size (int, optional): The group size to use for the quantized
weight. See :func:`~mlx.core.quantize`. Default: ``64``.
bits (int, optional): The bit width to use for the quantized weight.
See :func:`~mlx.core.quantize`. Default: ``4``.
group (mx.distributed.Group, optional): The sharding will happen across
this group. If not set then the global group is used. Default is
``None``.
"""
def __init__(
self,
input_dims: int,
output_dims: int,
bias: bool = ...,
group_size: int = ...,
bits: int = ...,
group: Optional[mx.distributed.Group] = ...,
) -> None: ...
def unfreeze(self, *args, **kwargs) -> None:
"""Wrap unfreeze so that we unfreeze any layers we might contain but
our parameters will remain frozen."""
def __call__(self, x: mx.array) -> mx.array: ...
@classmethod
def from_quantized_linear(
cls,
quantized_linear_layer: Module,
*,
segments: Union[int, list[int]] = ...,
group: Optional[mx.distributed.Group] = ...,
) -> QuantizedAllToShardedLinear: ...
class QuantizedShardedToAllLinear(Module):
"""Each member of the group applies part of the affine transformation using
the quantized matrix and then aggregates the results.
All nodes will have the same exact result after this layer.
It is the quantized equivalent of :class:`ShardedToAllLinear`.
Similar to :class:`QuantizedLinear` its parameters are frozen and
will not be included in any gradient computation.
Args:
input_dims (int): The dimensionality of the input features.
output_dims (int): The dimensionality of the output features.
bias (bool, optional): If set to ``False`` then the layer will not use
a bias. Default: ``True``.
group_size (int, optional): The group size to use for the quantized
weight. See :func:`~mlx.core.quantize`. Default: ``64``.
bits (int, optional): The bit width to use for the quantized weight.
See :func:`~mlx.core.quantize`. Default: ``4``.
group (mx.distributed.Group, optional): The sharding will happen across
this group. If not set then the global group is used. Default is
``None``.
"""
def __init__(
self,
input_dims: int,
output_dims: int,
bias: bool = ...,
group_size: int = ...,
bits: int = ...,
group: Optional[mx.distributed.Group] = ...,
) -> None: ...
def unfreeze(self, *args, **kwargs): # -> None:
"""Wrap unfreeze so that we unfreeze any layers we might contain but
our parameters will remain frozen."""
def __call__(self, x: mx.array) -> mx.array: ...
@classmethod
def from_quantized_linear(
cls,
quantized_linear_layer: Module,
*,
segments: Union[int, list[int]] = ...,
group: Optional[mx.distributed.Group] = ...,
) -> QuantizedShardedToAllLinear: ...

View File

@@ -0,0 +1,65 @@
"""
This type stub file was generated by pyright.
"""
import mlx.core as mx
from base import Module
class Dropout(Module):
r"""Randomly zero a portion of the elements during training.
The remaining elements are multiplied with :math:`\frac{1}{1-p}` where
:math:`p` is the probability of zeroing an element. This is done so the
expected value of a given element will remain the same.
Args:
p (float): The probability to zero an element
"""
def __init__(self, p: float = ...) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
class Dropout2d(Module):
r"""Apply 2D channel-wise dropout during training.
Randomly zero out entire channels independently with probability :math:`p`.
This layer expects the channels to be last, i.e. the input shape should be
``NWHC`` or ``WHC`` where:``N`` is the batch dimension,``H`` is the input
image height,``W`` is the input image width, and``C`` is the number of
input channels
The remaining channels are scaled by :math:`\frac{1}{1-p}` to
maintain the expected value of each element. Unlike traditional dropout,
which zeros individual entries, this layer zeros entire channels. This is
beneficial for early convolution layers where adjacent pixels are
correlated. In such case, traditional dropout may not effectively
regularize activations. For more details, see [1].
[1]: Thompson, J., Goroshin, R., Jain, A., LeCun, Y. and Bregler C., 2015.
Efficient Object Localization Using Convolutional Networks. CVPR 2015.
Args:
p (float): Probability of zeroing a channel during training.
"""
def __init__(self, p: float = ...) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
class Dropout3d(Module):
r"""Apply 3D channel-wise dropout during training.
Randomly zero out entire channels independently with probability :math:`p`.
This layer expects the channels to be last, i.e., the input shape should be
`NDHWC` or `DHWC` where: `N` is the batch dimension, `D` is the depth,
`H` is the input image height, `W` is the input image width, and `C` is
the number of input channels.
The remaining channels are scaled by :math:`\frac{1}{1-p}` to
maintain the expected value of each element. Unlike traditional dropout,
which zeros individual entries, this layer zeros entire channels. This is
often beneficial for convolutional layers processing 3D data, like in
medical imaging or video processing.
Args:
p (float): Probability of zeroing a channel during training.
"""
def __init__(self, p: float = ...) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...

View File

@@ -0,0 +1,34 @@
"""
This type stub file was generated by pyright.
"""
import mlx.core as mx
from base import Module
from .quantized import QuantizedEmbedding
class Embedding(Module):
"""Implements a simple lookup table that maps each input integer to a
high-dimensional vector.
Typically used to embed discrete tokens for processing by neural networks.
Args:
num_embeddings (int): How many possible discrete tokens can we embed.
Usually called the vocabulary size.
dims (int): The dimensionality of the embeddings.
"""
def __init__(self, num_embeddings: int, dims: int) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
def as_linear(self, x: mx.array) -> mx.array:
"""
Call the embedding layer as a linear layer.
Use this for example when input embedding and output projection
weights are tied.
"""
def to_quantized(
self, group_size: int = ..., bits: int = ..., mode: str = ...
) -> QuantizedEmbedding:
"""Return a :obj:`QuantizedEmbedding` layer that approximates this embedding layer."""

View File

@@ -0,0 +1,76 @@
"""
This type stub file was generated by pyright.
"""
from typing import Any
import mlx.core as mx
from base import Module
from .quantized import QuantizedLinear
class Identity(Module):
r"""A placeholder identity operator that is argument-insensitive.
Args:
args: any argument (unused)
kwargs: any keyword argument (unused)
"""
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
class Linear(Module):
r"""Applies an affine transformation to the input.
Concretely:
.. math::
y = x W^\top + b
where:
where :math:`W` has shape ``[output_dims, input_dims]`` and :math:`b` has shape ``[output_dims]``.
The values are initialized from the uniform distribution :math:`\mathcal{U}(-{k}, {k})`,
where :math:`k = \frac{1}{\sqrt{D_i}}` and :math:`D_i` is equal to ``input_dims``.
Args:
input_dims (int): The dimensionality of the input features
output_dims (int): The dimensionality of the output features
bias (bool, optional): If set to ``False`` then the layer will
not use a bias. Default is ``True``.
"""
def __init__(self, input_dims: int, output_dims: int, bias: bool = ...) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
def to_quantized(
self, group_size: int = ..., bits: int = ..., mode: str = ...
) -> QuantizedLinear:
"""Return a :obj:`QuantizedLinear` layer that approximates this layer."""
class Bilinear(Module):
r"""Applies a bilinear transformation to the inputs.
Concretely:
.. math::
y_i = x_1^\top W_i x_2 + b_i
where:
:math:`W` has shape ``[output_dims, input1_dims, input2_dims]``, :math:`b` has shape ``[output_dims ]``,
and :math:`i` indexes the output dimension.
The values are initialized from the uniform distribution :math:`\mathcal{U}(-{k}, {k})`,
where :math:`k = \frac{1}{\sqrt{D_1}}` and :math:`D_1` is ``input1_dims``.
Args:
input1_dims (int): The dimensionality of the input1 features
input2_dims (int): The dimensionality of the input2 features
output_dims (int): The dimensionality of the output features
bias (bool, optional): If set to ``False`` then the layer will
not use a bias. Default is ``True``.
"""
def __init__(
self, input1_dims: int, input2_dims: int, output_dims: int, bias: bool = ...
) -> None: ...
def __call__(self, x1: mx.array, x2: mx.array) -> mx.array: ...

View File

@@ -0,0 +1,194 @@
"""
This type stub file was generated by pyright.
"""
import mlx.core as mx
from base import Module
class InstanceNorm(Module):
r"""Applies instance normalization [1] on the inputs.
Computes
.. math::
y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta,
where :math:`\gamma` and :math:`\beta` are learned per feature dimension
parameters initialized at 1 and 0 respectively. Both are of size :attr:`dims`,
if :attr:`affine` is ``True``.
Args:
dims (int): The number of features of the input.
eps (float): A value added to the denominator for numerical stability. Default: ``1e-5``.
affine (bool): Default: ``False``.
Shape:
- Input: :math:`(..., C)` where :math:`C` is equal to :attr:`dims`.
- Output: Same shape as the input.
Examples:
>>> import mlx.core as mx
>>> import mlx.nn as nn
>>> x = mx.random.normal((8, 4, 4, 16))
>>> inorm = nn.InstanceNorm(dims=16)
>>> output = inorm(x)
References:
[1]: https://arxiv.org/abs/1607.08022
"""
def __init__(self, dims: int, eps: float = ..., affine: bool = ...) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
class LayerNorm(Module):
r"""Applies layer normalization [1] on the inputs.
Computes
.. math::
y = \frac{x - E[x]}{\sqrt{Var[x]} + \epsilon} \gamma + \beta,
where :math:`\gamma` and :math:`\beta` are learned per feature dimension
parameters initialized at 1 and 0 respectively.
[1]: https://arxiv.org/abs/1607.06450
Args:
dims (int): The feature dimension of the input to normalize over
eps (float): A small additive constant for numerical stability
affine (bool): If True learn an affine transform to apply after the
normalization
bias (bool): If True include a translation to the affine
transformation. If set to False the transformation is not really affine
just scaling.
"""
def __init__(
self, dims: int, eps: float = ..., affine: bool = ..., bias: bool = ...
) -> None: ...
def __call__(self, x) -> mx.array: ...
class RMSNorm(Module):
r"""Applies Root Mean Square normalization [1] to the inputs.
Computes
.. math::
y = \frac{x}{\sqrt{E[x^2] + \epsilon}} \gamma
where :math:`\gamma` is a learned per feature dimension parameter initialized at
1.
Note the accumulation for the mean is done in 32-bit precision.
[1]: https://arxiv.org/abs/1910.07467
Args:
dims (int): The feature dimension of the input to normalize over
eps (float): A small additive constant for numerical stability
"""
def __init__(self, dims: int, eps: float = ...) -> None: ...
def __call__(self, x) -> mx.array: ...
class GroupNorm(Module):
r"""Applies Group Normalization [1] to the inputs.
Computes the same normalization as layer norm, namely
.. math::
y = \frac{x - E[x]}{\sqrt{Var[x]} + \epsilon} \gamma + \beta,
where :math:`\gamma` and :math:`\beta` are learned per feature dimension
parameters initialized at 1 and 0 respectively. However, the mean and
variance are computed over the spatial dimensions and each group of
features. In particular, the input is split into num_groups across the
feature dimension.
The feature dimension is assumed to be the last dimension and the dimensions
that precede it (except the first) are considered the spatial dimensions.
[1]: https://arxiv.org/abs/1803.08494
Args:
num_groups (int): Number of groups to separate the features into
dims (int): The feature dimensions of the input to normalize over
eps (float): A small additive constant for numerical stability
affine (bool): If True learn an affine transform to apply after the
normalization.
pytorch_compatible (bool): If True perform the group normalization in
the same order/grouping as PyTorch.
"""
def __init__(
self,
num_groups: int,
dims: int,
eps: float = ...,
affine: bool = ...,
pytorch_compatible: bool = ...,
) -> None: ...
def __call__(self, x) -> mx.array: ...
class BatchNorm(Module):
r"""Applies Batch Normalization over a 2D or 3D input.
Computes
.. math::
y = \frac{x - E[x]}{\sqrt{Var[x]} + \epsilon} \gamma + \beta,
where :math:`\gamma` and :math:`\beta` are learned per feature dimension
parameters initialized at 1 and 0 respectively.
The input shape is specified as ``NC`` or ``NLC``, where ``N`` is the
batch, ``C`` is the number of features or channels, and ``L`` is the
sequence length. The output has the same shape as the input. For
four-dimensional arrays, the shape is ``NHWC``, where ``H`` and ``W`` are
the height and width respectively.
For more information on Batch Normalization, see the original paper `Batch
Normalization: Accelerating Deep Network Training by Reducing Internal
Covariate Shift <https://arxiv.org/abs/1502.03167>`_.
Args:
num_features (int): The feature dimension to normalize over.
eps (float, optional): A small additive constant for numerical
stability. Default: ``1e-5``.
momentum (float, optional): The momentum for updating the running
mean and variance. Default: ``0.1``.
affine (bool, optional): If ``True``, apply a learned affine
transformation after the normalization. Default: ``True``.
track_running_stats (bool, optional): If ``True``, track the
running mean and variance. Default: ``True``.
Examples:
>>> import mlx.core as mx
>>> import mlx.nn as nn
>>> x = mx.random.normal((5, 4))
>>> bn = nn.BatchNorm(num_features=4, affine=True)
>>> output = bn(x)
"""
def __init__(
self,
num_features: int,
eps: float = ...,
momentum: float = ...,
affine: bool = ...,
track_running_stats: bool = ...,
) -> None: ...
def unfreeze(self, *args, **kwargs): # -> None:
"""Wrap unfreeze to make sure that running_mean and var are always
frozen parameters."""
def __call__(self, x: mx.array) -> mx.array:
"""
Forward pass of BatchNorm.
Args:
x (array): Input tensor.
Returns:
array: Normalized output tensor.
"""

View File

@@ -0,0 +1,242 @@
"""
This type stub file was generated by pyright.
"""
from typing import Optional, Tuple, Union
import mlx.core as mx
from base import Module
class _Pool(Module):
def __init__(
self, pooling_function, kernel_size, stride, padding, padding_value
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
class _Pool1d(_Pool):
def __init__(
self,
pooling_function,
padding_value,
kernel_size: Union[int, Tuple[int]],
stride: Optional[Union[int, Tuple[int]]] = ...,
padding: Union[int, Tuple[int]] = ...,
) -> None: ...
class _Pool2d(_Pool):
def __init__(
self,
pooling_function,
padding_value,
kernel_size: Union[int, Tuple[int, int]],
stride: Optional[Union[int, Tuple[int, int]]] = ...,
padding: Optional[Union[int, Tuple[int, int]]] = ...,
) -> None: ...
class _Pool3d(_Pool):
def __init__(
self,
pooling_function,
padding_value,
kernel_size: Union[int, Tuple[int, int, int]],
stride: Optional[Union[int, Tuple[int, int, int]]] = ...,
padding: Optional[Union[int, Tuple[int, int, int]]] = ...,
) -> None: ...
class MaxPool1d(_Pool1d):
r"""Applies 1-dimensional max pooling.
Spatially downsamples the input by taking the maximum of a sliding window
of size ``kernel_size`` and sliding stride ``stride``.
Args:
kernel_size (int or tuple(int)): The size of the pooling window kernel.
stride (int or tuple(int), optional): The stride of the pooling window.
Default: ``kernel_size``.
padding (int or tuple(int), optional): How much negative infinity
padding to apply to the input. The padding amount is applied to
both sides of the spatial axis. Default: ``0``.
Examples:
>>> import mlx.core as mx
>>> import layers as nn
>>> x = mx.random.normal(shape=(4, 16, 5))
>>> pool = nn.MaxPool1d(kernel_size=2, stride=2)
>>> pool(x)
"""
def __init__(
self,
kernel_size: Union[int, Tuple[int]],
stride: Optional[Union[int, Tuple[int]]] = ...,
padding: Union[int, Tuple[int]] = ...,
) -> None: ...
class AvgPool1d(_Pool1d):
r"""Applies 1-dimensional average pooling.
Spatially downsamples the input by taking the average of a sliding window
of size ``kernel_size`` and sliding stride ``stride``.
Args:
kernel_size (int or tuple(int)): The size of the pooling window kernel.
stride (int or tuple(int), optional): The stride of the pooling window.
Default: ``kernel_size``.
padding (int or tuple(int), optional): How much zero padding to apply to
the input. The padding amount is applied to both sides of the spatial
axis. Default: ``0``.
Examples:
>>> import mlx.core as mx
>>> import layers as nn
>>> x = mx.random.normal(shape=(4, 16, 5))
>>> pool = nn.AvgPool1d(kernel_size=2, stride=2)
>>> pool(x)
"""
def __init__(
self,
kernel_size: Union[int, Tuple[int]],
stride: Optional[Union[int, Tuple[int]]] = ...,
padding: Union[int, Tuple[int]] = ...,
) -> None: ...
class MaxPool2d(_Pool2d):
r"""Applies 2-dimensional max pooling.
Spatially downsamples the input by taking the maximum of a sliding window
of size ``kernel_size`` and sliding stride ``stride``.
The parameters ``kernel_size``, ``stride``, and ``padding`` can either be:
* a single ``int`` -- in which case the same value is used for both the
height and width axis.
* a ``tuple`` of two ``int`` s -- in which case, the first ``int`` is
used for the height axis, the second ``int`` for the width axis.
Args:
kernel_size (int or tuple(int, int)): The size of the pooling window.
stride (int or tuple(int, int), optional): The stride of the pooling
window. Default: ``kernel_size``.
padding (int or tuple(int, int), optional): How much negative infinity
padding to apply to the input. The padding is applied on both sides
of the height and width axis. Default: ``0``.
Examples:
>>> import mlx.core as mx
>>> import layers as nn
>>> x = mx.random.normal(shape=(8, 32, 32, 4))
>>> pool = nn.MaxPool2d(kernel_size=2, stride=2)
>>> pool(x)
"""
def __init__(
self,
kernel_size: Union[int, Tuple[int, int]],
stride: Optional[Union[int, Tuple[int, int]]] = ...,
padding: Optional[Union[int, Tuple[int, int]]] = ...,
) -> None: ...
class AvgPool2d(_Pool2d):
r"""Applies 2-dimensional average pooling.
Spatially downsamples the input by taking the average of a sliding window
of size ``kernel_size`` and sliding stride ``stride``.
The parameters ``kernel_size``, ``stride``, and ``padding`` can either be:
* a single ``int`` -- in which case the same value is used for both the
height and width axis.
* a ``tuple`` of two ``int`` s -- in which case, the first ``int`` is
used for the height axis, the second ``int`` for the width axis.
Args:
kernel_size (int or tuple(int, int)): The size of the pooling window.
stride (int or tuple(int, int), optional): The stride of the pooling
window. Default: ``kernel_size``.
padding (int or tuple(int, int), optional): How much zero
padding to apply to the input. The padding is applied on both sides
of the height and width axis. Default: ``0``.
Examples:
>>> import mlx.core as mx
>>> import layers as nn
>>> x = mx.random.normal(shape=(8, 32, 32, 4))
>>> pool = nn.AvgPool2d(kernel_size=2, stride=2)
>>> pool(x)
"""
def __init__(
self,
kernel_size: Union[int, Tuple[int, int]],
stride: Optional[Union[int, Tuple[int, int]]] = ...,
padding: Optional[Union[int, Tuple[int, int]]] = ...,
) -> None: ...
class MaxPool3d(_Pool3d):
r"""Applies 3-dimensional max pooling.
Spatially downsamples the input by taking the maximum of a sliding window
of size ``kernel_size`` and sliding stride ``stride``.
The parameters ``kernel_size``, ``stride``, and ``padding`` can either be:
* a single ``int`` -- in which case the same value is used for the depth,
height, and width axis.
* a ``tuple`` of three ``int`` s -- in which case, the first ``int`` is used
for the depth axis, the second ``int`` for the height axis, and the third
``int`` for the width axis.
Args:
kernel_size (int or tuple(int, int, int)): The size of the pooling window.
stride (int or tuple(int, int, int), optional): The stride of the pooling
window. Default: ``kernel_size``.
padding (int or tuple(int, int, int), optional): How much negative infinity
padding to apply to the input. The padding is applied on both sides
of the depth, height and width axis. Default: ``0``.
Examples:
>>> import mlx.core as mx
>>> import layers as nn
>>> x = mx.random.normal(shape=(8, 16, 32, 32, 4))
>>> pool = nn.MaxPool3d(kernel_size=2, stride=2)
>>> pool(x)
"""
def __init__(
self,
kernel_size: Union[int, Tuple[int, int, int]],
stride: Optional[Union[int, Tuple[int, int, int]]] = ...,
padding: Optional[Union[int, Tuple[int, int, int]]] = ...,
) -> None: ...
class AvgPool3d(_Pool3d):
r"""Applies 3-dimensional average pooling.
Spatially downsamples the input by taking the average of a sliding window
of size ``kernel_size`` and sliding stride ``stride``.
The parameters ``kernel_size``, ``stride``, and ``padding`` can either be:
* a single ``int`` -- in which case the same value is used for the depth,
height, and width axis.
* a ``tuple`` of three ``int`` s -- in which case, the first ``int`` is used
for the depth axis, the second ``int`` for the height axis, and the third
``int`` for the width axis.
Args:
kernel_size (int or tuple(int, int, int)): The size of the pooling window.
stride (int or tuple(int, int, int), optional): The stride of the pooling
window. Default: ``kernel_size``.
padding (int or tuple(int, int, int), optional): How much zero
padding to apply to the input. The padding is applied on both sides
of the depth, height and width axis. Default: ``0``.
Examples:
>>> import mlx.core as mx
>>> import layers as nn
>>> x = mx.random.normal(shape=(8, 16, 32, 32, 4))
>>> pool = nn.AvgPool3d(kernel_size=2, stride=2)
>>> pool(x)
"""
def __init__(
self,
kernel_size: Union[int, Tuple[int, int, int]],
stride: Optional[Union[int, Tuple[int, int, int]]] = ...,
padding: Optional[Union[int, Tuple[int, int, int]]] = ...,
) -> None: ...

View File

@@ -0,0 +1,80 @@
"""
This type stub file was generated by pyright.
"""
from typing import Optional
import mlx.core as mx
from base import Module
class RoPE(Module):
"""Implements the rotary positional encoding.
The traditional implementation rotates consecutive pairs of elements in the
feature dimension while the default implementation rotates pairs with
stride half the feature dimensions for efficiency.
For more details see `RoFormer: Enhanced Transformer with Rotary Position
Embedding <https://arxiv.org/abs/2104.09864>`_.
Args:
dims (int): The feature dimensions to be rotated. If the input feature
is larger than dims then the rest is left unchanged.
traditional (bool, optional): If set to ``True`` choose the traditional
implementation which is slightly less efficient. Default: ``False``.
base (float, optional): The base used to compute angular frequency for
each dimension in the positional encodings. Default: ``10000``.
scale (float, optional): The scale used to scale the positions. Default: ``1.0``.
"""
def __init__(
self, dims: int, traditional: bool = ..., base: float = ..., scale: float = ...
) -> None: ...
def __call__(self, x, offset: int = ...) -> mx.array: ...
class SinusoidalPositionalEncoding(Module):
r"""Implements sinusoidal positional encoding.
For more details see the paper `Attention Is All You Need
<https://arxiv.org/abs/1706.03762>`_.
Args:
dims (int): The dimensionality of the resulting positional embeddings.
min_freq (float, optional): The minimum frequency expected. Default:
``0.0001``.
max_freq (float, optional): The maximum frequency expected. Default:
``1``.
scale (float, optional): A multiplicative scale for the embeddings.
Default: ``sqrt(2/dims)``.
cos_first (bool, optional): If ``True`` embed using ``[cos(x); sin(x)]``
instead of the reverse. Default: ``False``.
full_turns (bool, optional): If ``True`` multiply the frequencies with
:math:`2\pi`. Default: ``False``.
"""
def __init__(
self,
dims: int,
min_freq: float = ...,
max_freq: float = ...,
scale: Optional[float] = ...,
cos_first: bool = ...,
full_turns: bool = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
class ALiBi(Module):
_alibi_mask_key = ...
_alibi_mask = ...
@classmethod
def create_alibi_matrix(
cls,
q_sequence_length: int,
k_sequence_length: int,
num_heads: int,
offset: int,
dtype=...,
) -> mx.array | None: ...
@staticmethod
def create_alibi_slope(num_heads: int) -> mx.array: ...
def __call__(
self, attention_scores: mx.array, offset=..., mask=...
) -> mx.array: ...

View File

@@ -0,0 +1,125 @@
"""
This type stub file was generated by pyright.
"""
from typing import Callable, Optional, Union
import mlx.core as mx
from base import Module
def quantize(
model: Module,
group_size: int = ...,
bits: int = ...,
*,
mode: str = ...,
class_predicate: Optional[Callable[[str, Module], Union[bool, dict]]] = ...,
): # -> None:
"""Quantize the sub-modules of a module according to a predicate.
By default all layers that define a ``to_quantized(group_size, bits)``
method will be quantized. Both :obj:`Linear` and :obj:`Embedding` layers
will be quantized. Note also, the module is updated in-place.
Args:
model (Module): The model whose leaf modules may be quantized.
group_size (int): The quantization group size (see
:func:`mlx.core.quantize`). Default: ``64``.
bits (int): The number of bits per parameter (see
:func:`mlx.core.quantize`). Default: ``4``.
mode (str): The quantization method to use (see
:func:`mlx.core.quantize`). Default: ``"affine"``.
class_predicate (Optional[Callable]): A callable which receives the
:obj:`Module` path and :obj:`Module` itself and returns ``True`` or a
dict of params for `to_quantized` if it should be quantized and
``False`` otherwise. If ``None``, then all layers that define a
``to_quantized(group_size, bits)`` method are quantized.
Default: ``None``.
"""
class QuantizedEmbedding(Module):
"""The same as :obj:`Embedding` but with a quantized weight matrix.
:obj:`QuantizedEmbedding` also provides a :meth:`from_embedding`
classmethod to convert embedding layers to :obj:`QuantizedEmbedding`
layers.
Args:
num_embeddings (int): How many possible discrete tokens can we embed.
Usually called the vocabulary size.
dims (int): The dimensionality of the embeddings.
group_size (int, optional): The group size to use for the quantized
weight. See :func:`~mlx.core.quantize`. Default: ``64``.
bits (int, optional): The bit width to use for the quantized weight.
See :func:`~mlx.core.quantize`. Default: ``4``.
mode (str): The quantization method to use (see
:func:`mlx.core.quantize`). Default: ``"affine"``.
"""
def __init__(
self,
num_embeddings: int,
dims: int,
group_size: int = ...,
bits: int = ...,
mode: str = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
def as_linear(self, x: mx.array) -> mx.array:
"""
Call the quantized embedding layer as a quantized linear layer.
Use this for example when input embedding and output projection
weights are tied.
"""
@classmethod
def from_embedding(
cls,
embedding_layer: Module,
group_size: int = ...,
bits: int = ...,
mode: str = ...,
) -> QuantizedEmbedding:
"""Create a :obj:`QuantizedEmbedding` layer from an :obj:`Embedding` layer."""
class QuantizedLinear(Module):
"""Applies an affine transformation to the input using a quantized weight matrix.
It is the quantized equivalent of :class:`Linear`. For now its
parameters are frozen and will not be included in any gradient computation
but this will probably change in the future.
:obj:`QuantizedLinear` also provides a classmethod :meth:`from_linear` to
convert linear layers to :obj:`QuantizedLinear` layers.
Args:
input_dims (int): The dimensionality of the input features.
output_dims (int): The dimensionality of the output features.
bias (bool, optional): If set to ``False`` then the layer will not use
a bias. Default: ``True``.
group_size (int, optional): The group size to use for the quantized
weight. See :func:`~mlx.core.quantize`. Default: ``64``.
bits (int, optional): The bit width to use for the quantized weight.
See :func:`~mlx.core.quantize`. Default: ``4``.
mode (str): The quantization method to use (see
:func:`mlx.core.quantize`). Default: ``"affine"``.
"""
def __init__(
self,
input_dims: int,
output_dims: int,
bias: bool = ...,
group_size: int = ...,
bits: int = ...,
mode: str = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...
@classmethod
def from_linear(
cls,
linear_layer: Module,
group_size: int = ...,
bits: int = ...,
mode: str = ...,
) -> QuantizedLinear:
"""Create a :obj:`QuantizedLinear` layer from a :obj:`Linear` layer."""

View File

@@ -0,0 +1,113 @@
"""
This type stub file was generated by pyright.
"""
from typing import Callable, Optional
import mlx.core as mx
from base import Module
class RNN(Module):
r"""An Elman recurrent layer.
The input is a sequence of shape ``NLD`` or ``LD`` where:
* ``N`` is the optional batch dimension
* ``L`` is the sequence length
* ``D`` is the input's feature dimension
Concretely, for each element along the sequence length axis, this
layer applies the function:
.. math::
h_{t + 1} = \text{tanh} (W_{ih}x_t + W_{hh}h_t + b)
The hidden state :math:`h` has shape ``NH`` or ``H``, depending on
whether the input is batched or not. Returns the hidden state at each
time step, of shape ``NLH`` or ``LH``.
Args:
input_size (int): Dimension of the input, ``D``.
hidden_size (int): Dimension of the hidden state, ``H``.
bias (bool, optional): Whether to use a bias. Default: ``True``.
nonlinearity (callable, optional): Non-linearity to use. If ``None``,
then func:`tanh` is used. Default: ``None``.
"""
def __init__(
self,
input_size: int,
hidden_size: int,
bias: bool = ...,
nonlinearity: Optional[Callable] = ...,
) -> None: ...
def __call__(self, x: mx.array, hidden=...) -> mx.array: ...
class GRU(Module):
r"""A gated recurrent unit (GRU) RNN layer.
The input has shape ``NLD`` or ``LD`` where:
* ``N`` is the optional batch dimension
* ``L`` is the sequence length
* ``D`` is the input's feature dimension
Concretely, for each element of the sequence, this layer computes:
.. math::
\begin{aligned}
r_t &= \sigma (W_{xr}x_t + W_{hr}h_t + b_{r}) \\
z_t &= \sigma (W_{xz}x_t + W_{hz}h_t + b_{z}) \\
n_t &= \text{tanh}(W_{xn}x_t + b_{n} + r_t \odot (W_{hn}h_t + b_{hn})) \\
h_{t + 1} &= (1 - z_t) \odot n_t + z_t \odot h_t
\end{aligned}
The hidden state :math:`h` has shape ``NH`` or ``H`` depending on
whether the input is batched or not. Returns the hidden state at each
time step of shape ``NLH`` or ``LH``.
Args:
input_size (int): Dimension of the input, ``D``.
hidden_size (int): Dimension of the hidden state, ``H``.
bias (bool): Whether to use biases or not. Default: ``True``.
"""
def __init__(self, input_size: int, hidden_size: int, bias: bool = ...) -> None: ...
def __call__(self, x: mx.array, hidden=...) -> mx.array: ...
class LSTM(Module):
r"""An LSTM recurrent layer.
The input has shape ``NLD`` or ``LD`` where:
* ``N`` is the optional batch dimension
* ``L`` is the sequence length
* ``D`` is the input's feature dimension
Concretely, for each element of the sequence, this layer computes:
.. math::
\begin{aligned}
i_t &= \sigma (W_{xi}x_t + W_{hi}h_t + b_{i}) \\
f_t &= \sigma (W_{xf}x_t + W_{hf}h_t + b_{f}) \\
g_t &= \text{tanh} (W_{xg}x_t + W_{hg}h_t + b_{g}) \\
o_t &= \sigma (W_{xo}x_t + W_{ho}h_t + b_{o}) \\
c_{t + 1} &= f_t \odot c_t + i_t \odot g_t \\
h_{t + 1} &= o_t \text{tanh}(c_{t + 1})
\end{aligned}
The hidden state :math:`h` and cell state :math:`c` have shape ``NH``
or ``H``, depending on whether the input is batched or not.
The layer returns two arrays, the hidden state and the cell state at
each time step, both of shape ``NLH`` or ``LH``.
Args:
input_size (int): Dimension of the input, ``D``.
hidden_size (int): Dimension of the hidden state, ``H``.
bias (bool): Whether to use biases or not. Default: ``True``.
"""
def __init__(self, input_size: int, hidden_size: int, bias: bool = ...) -> None: ...
def __call__(
self, x: mx.array, hidden=..., cell=...
) -> tuple[mx.array, mx.array]: ...

View File

@@ -0,0 +1,168 @@
"""
This type stub file was generated by pyright.
"""
from typing import Any, Callable, Optional
import mlx.core as mx
from base import Module
class MultiHeadAttention(Module):
"""Implements the scaled dot product attention with multiple heads.
Given inputs for queries, keys and values the ``MultiHeadAttention``
produces new values by aggregating information from the input values
according to the similarities of the input queries and keys.
All inputs as well as the output are linearly projected without biases by
default.
``MultiHeadAttention`` also takes an optional additive attention mask that
should be broadcastable with ``(batch, num_heads, # queries, # keys)``. The
mask should have ``-inf`` or very large negative numbers at the positions
that should *not* be attended to.
Args:
dims (int): The model dimensions. This is also the default
value for the queries, keys, values, and the output.
num_heads (int): The number of attention heads to use.
query_input_dims (int, optional): The input dimensions of the queries.
Default: ``dims``.
key_input_dims (int, optional): The input dimensions of the keys.
Default: ``dims``.
value_input_dims (int, optional): The input dimensions of the values.
Default: ``key_input_dims``.
value_dims (int, optional): The dimensions of the values after the
projection. Default: ``dims``.
value_output_dims (int, optional): The dimensions the new values will
be projected to. Default: ``dims``.
bias (bool, optional): Whether or not to use a bias in the projections.
Default: ``False``.
"""
def __init__(
self,
dims: int,
num_heads: int,
query_input_dims: Optional[int] = ...,
key_input_dims: Optional[int] = ...,
value_input_dims: Optional[int] = ...,
value_dims: Optional[int] = ...,
value_output_dims: Optional[int] = ...,
bias: bool = ...,
) -> None: ...
def __call__(
self, queries: mx.array, keys: mx.array, values: mx.array, mask: mx.array = ...
) -> mx.array: ...
@staticmethod
def create_additive_causal_mask(N: int, dtype: mx.Dtype = ...) -> mx.array: ...
class TransformerEncoderLayer(Module):
def __init__(
self,
dims: int,
num_heads: int,
mlp_dims: Optional[int] = ...,
dropout: float = ...,
activation: Callable[[Any], Any] = ...,
norm_first: bool = ...,
) -> None: ...
def __call__(self, x: mx.array, mask: mx.array) -> mx.array: ...
class TransformerEncoder(Module):
def __init__(
self,
num_layers: int,
dims: int,
num_heads: int,
mlp_dims: Optional[int] = ...,
dropout: float = ...,
activation=...,
norm_first: bool = ...,
checkpoint: bool = ...,
) -> None: ...
def __call__(self, x: mx.array, mask: mx.array) -> mx.array: ...
class TransformerDecoderLayer(Module):
def __init__(
self,
dims: int,
num_heads: int,
mlp_dims: Optional[int] = ...,
dropout: float = ...,
activation: Callable[[Any], Any] = ...,
norm_first: bool = ...,
) -> None: ...
def __call__(self, x: mx.array, memory, x_mask, memory_mask) -> mx.array: ...
class TransformerDecoder(Module):
def __init__(
self,
num_layers: int,
dims: int,
num_heads: int,
mlp_dims: Optional[int] = ...,
dropout: float = ...,
activation=...,
norm_first: bool = ...,
checkpoint: bool = ...,
) -> None: ...
def __call__(self, x: mx.array, memory, x_mask, memory_mask) -> mx.array: ...
class Transformer(Module):
"""
Implements a standard Transformer model.
The implementation is based on `Attention Is All You Need
<https://arxiv.org/abs/1706.03762>`_.
The Transformer model contains an encoder and a decoder. The encoder
processes the input sequence and the decoder generates the output sequence.
The interaction between encoder and decoder happens through the attention
mechanism.
Args:
dims (int, optional): The number of expected features in the
encoder/decoder inputs. Default: ``512``.
num_heads (int, optional): The number of attention heads. Default:
``8``.
num_encoder_layers (int, optional): The number of encoder layers in the
Transformer encoder. Default: ``6``.
num_decoder_layers (int, optional): The number of decoder layers in the
Transformer decoder. Default: ``6``.
mlp_dims (int, optional): The hidden dimension of the MLP block in each
Transformer layer. Defaults to ``4*dims`` if not provided. Default:
``None``.
dropout (float, optional): The dropout value for the Transformer
encoder and decoder. Dropout is used after each attention layer and
the activation in the MLP layer. Default: ``0.0``.
activation (function, optional): the activation function for the MLP
hidden layer. Default: :func:`relu`.
custom_encoder (nn.Module, optional): A custom encoder to replace the
standard Transformer encoder. Default: ``None``.
custom_decoder (nn.Module, optional): A custom decoder to replace the
standard Transformer decoder. Default: ``None``.
norm_first (bool, optional): if ``True``, encoder and decoder layers
will perform layer normalization before attention and MLP
operations, otherwise after. Default: ``True``.
checkpoint (bool, optional): if ``True`` perform gradient checkpointing
to reduce the memory usage at the expense of more computation.
Default: ``False``.
"""
def __init__(
self,
dims: int = ...,
num_heads: int = ...,
num_encoder_layers: int = ...,
num_decoder_layers: int = ...,
mlp_dims: Optional[int] = ...,
dropout: float = ...,
activation: Callable[[Any], Any] = ...,
custom_encoder: Optional[Any] = ...,
custom_decoder: Optional[Any] = ...,
norm_first: bool = ...,
checkpoint: bool = ...,
) -> None: ...
def __call__(
self, src, tgt, src_mask, tgt_mask, memory_mask
) -> mx.array: # -> array | Any:
...

View File

@@ -0,0 +1,87 @@
"""
This type stub file was generated by pyright.
"""
from typing import Literal, Tuple, Union
import mlx.core as mx
from base import Module
def upsample_nearest(x: mx.array, scale_factor: Tuple) -> mx.array: ...
def upsample_linear(
x: mx.array, scale_factor: Tuple, align_corners: bool = ...
): # -> int:
...
def upsample_cubic(
x: mx.array, scale_factor: Tuple, align_corners: bool = ...
): # -> int:
...
class Upsample(Module):
r"""Upsample the input signal spatially.
The spatial dimensions are by convention dimensions ``1`` to ``x.ndim -
2``. The first is the batch dimension and the last is the feature
dimension.
For example, an audio signal would be 3D with 1 spatial dimension, an image
4D with 2 and so on and so forth.
There are three upsampling algorithms implemented nearest neighbor upsampling,
linear interpolation, and cubic interpolation. All can be applied to any number
of spatial dimensions. The linear interpolation will be bilinear, trilinear etc
when applied to more than one spatial dimension. And cubic interpolation will be
bicubic when there are 2 spatial dimensions.
.. note::
When using one of the linear or cubic interpolation modes the ``align_corners``
argument changes how the corners are treated in the input image. If
``align_corners=True`` then the top and left edge of the input and
output will be matching as will the bottom right edge.
Parameters:
scale_factor (float or tuple): The multiplier for the spatial size.
If a ``float`` is provided, it is the multiplier for all spatial dimensions.
Otherwise, the number of scale factors provided must match the
number of spatial dimensions.
mode (str, optional): The upsampling algorithm, either ``"nearest"``,
``"linear"`` or ``"cubic"``. Default: ``"nearest"``.
align_corners (bool, optional): Changes the way the corners are treated
during ``"linear"`` and ``"cubic"`` upsampling. See the note above and the
examples below for more details. Default: ``False``.
Examples:
>>> import mlx.core as mx
>>> import mlx.nn as nn
>>> x = mx.arange(1, 5).reshape((1, 2, 2, 1))
>>> x
array([[[[1],
[2]],
[[3],
[4]]]], dtype=int32)
>>> n = nn.Upsample(scale_factor=2, mode='nearest')
>>> n(x).squeeze()
array([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4]], dtype=int32)
>>> b = nn.Upsample(scale_factor=2, mode='linear')
>>> b(x).squeeze()
array([[1, 1.25, 1.75, 2],
[1.5, 1.75, 2.25, 2.5],
[2.5, 2.75, 3.25, 3.5],
[3, 3.25, 3.75, 4]], dtype=float32)
>>> b = nn.Upsample(scale_factor=2, mode='linear', align_corners=True)
>>> b(x).squeeze()
array([[1, 1.33333, 1.66667, 2],
[1.66667, 2, 2.33333, 2.66667],
[2.33333, 2.66667, 3, 3.33333],
[3, 3.33333, 3.66667, 4]], dtype=float32)
"""
def __init__(
self,
scale_factor: Union[float, Tuple],
mode: Literal["nearest", "linear", "cubic"] = ...,
align_corners: bool = ...,
) -> None: ...
def __call__(self, x: mx.array) -> mx.array: ...

View File

@@ -0,0 +1,419 @@
"""
This type stub file was generated by pyright.
"""
from typing import Literal, Optional
import mlx.core as mx
Reduction = Literal["none", "mean", "sum"]
def cross_entropy(
logits: mx.array,
targets: mx.array,
weights: Optional[mx.array] = ...,
axis: int = ...,
label_smoothing: float = ...,
reduction: Reduction = ...,
) -> mx.array:
"""
Computes the cross entropy loss.
Args:
logits (array): The unnormalized logits.
targets (array): The ground truth values. These can be class indices or
probabilities for each class. If the ``targets`` are class indices,
then ``targets`` shape should match the ``logits`` shape with
the ``axis`` dimension removed. If the ``targets`` are probabilities
(or one-hot encoded), then the ``targets`` shape should be the same as
the ``logits`` shape.
weights (array, optional): Optional weights for each target. Default: ``None``.
axis (int, optional): The axis over which to compute softmax. Default: ``-1``.
label_smoothing (float, optional): Label smoothing factor. Default: ``0``.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.
Returns:
array: The computed cross entropy loss.
Examples:
>>> import mlx.core as mx
>>> import mlx.nn as nn
>>>
>>> # Class indices as targets
>>> logits = mx.array([[2.0, -1.0], [-1.0, 2.0]])
>>> targets = mx.array([0, 1])
>>> nn.losses.cross_entropy(logits, targets)
array([0.0485873, 0.0485873], dtype=float32)
>>>
>>> # Probabilities (or one-hot vectors) as targets
>>> logits = mx.array([[2.0, -1.0], [-1.0, 2.0]])
>>> targets = mx.array([[0.9, 0.1], [0.1, 0.9]])
>>> nn.losses.cross_entropy(logits, targets)
array([0.348587, 0.348587], dtype=float32)
"""
def binary_cross_entropy(
inputs: mx.array,
targets: mx.array,
weights: Optional[mx.array] = ...,
with_logits: bool = ...,
reduction: Reduction = ...,
) -> mx.array:
"""
Computes the binary cross entropy loss.
By default, this function takes the pre-sigmoid logits, which results in a faster
and more precise loss. For improved numerical stability when ``with_logits=False``,
the loss calculation clips the input probabilities (in log-space) to a minimum value
of ``-100``.
Args:
inputs (array): The predicted values. If ``with_logits`` is ``True``, then
``inputs`` are unnormalized logits. Otherwise, ``inputs`` are probabilities.
targets (array): The binary target values in {0, 1}.
with_logits (bool, optional): Whether ``inputs`` are logits. Default: ``True``.
weights (array, optional): Optional weights for each target. Default: ``None``.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'mean'``.
Returns:
array: The computed binary cross entropy loss.
Examples:
>>> import mlx.core as mx
>>> import mlx.nn as nn
>>> logits = mx.array([0.105361, 0.223144, 1.20397, 0.916291])
>>> targets = mx.array([0, 0, 1, 1])
>>> loss = nn.losses.binary_cross_entropy(logits, targets, reduction="mean")
>>> loss
array(0.539245, dtype=float32)
>>> probs = mx.array([0.1, 0.1, 0.4, 0.4])
>>> targets = mx.array([0, 0, 1, 1])
>>> loss = nn.losses.binary_cross_entropy(probs, targets, with_logits=False, reduction="mean")
>>> loss
array(0.510826, dtype=float32)
"""
def l1_loss(
predictions: mx.array, targets: mx.array, reduction: Reduction = ...
) -> mx.array:
"""
Computes the L1 loss.
Args:
predictions (array): The predicted values.
targets (array): The target values.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'mean'``.
Returns:
array: The computed L1 loss.
"""
def mse_loss(
predictions: mx.array, targets: mx.array, reduction: Reduction = ...
) -> mx.array:
"""
Computes the mean squared error loss.
Args:
predictions (array): The predicted values.
targets (array): The target values.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'mean'``.
Returns:
array: The computed mean squared error loss.
"""
def nll_loss(
inputs: mx.array, targets: mx.array, axis: int = ..., reduction: Reduction = ...
) -> mx.array:
"""
Computes the negative log likelihood loss.
Args:
inputs (array): The predicted distribution in log space.
targets (array): The target values.
axis (int, optional): The distribution axis. Default: ``-1``.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.
Returns:
array: The computed NLL loss.
"""
def gaussian_nll_loss(
inputs: mx.array,
targets: mx.array,
vars: mx.array,
full: bool = ...,
eps: float = ...,
reduction: Reduction = ...,
) -> mx.array:
r"""
Computes the negative log likelihood loss for a Gaussian distribution.
The loss is given by:
.. math::
\frac{1}{2}\left(\log\left(\max\left(\text{vars},
\ \epsilon\right)\right) + \frac{\left(\text{inputs} - \text{targets} \right)^2}
{\max\left(\text{vars}, \ \epsilon \right)}\right) + \text{const.}
where ``inputs`` are the predicted means and ``vars`` are the the
predicted variances.
Args:
inputs (array): The predicted expectation of the Gaussian distribution.
targets (array): The target values (samples from the Gaussian distribution).
vars (array): The predicted variance of the Gaussian distribution.
full (bool, optional): Whether to include the constant term in the loss calculation.
Default: ``False``.
eps (float, optional): Small positive constant for numerical stability.
Default: ``1e-6``.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.
Returns:
array: The Gaussian NLL loss.
"""
def kl_div_loss(
inputs: mx.array, targets: mx.array, axis: int = ..., reduction: Reduction = ...
) -> mx.array:
"""
Computes the Kullback-Leibler divergence loss.
Computes the following when ``reduction == 'none'``:
.. code-block:: python
mx.exp(targets) * (targets - inputs).sum(axis)
Args:
inputs (array): Log probabilities for the predicted distribution.
targets (array): Log probabilities for the target distribution.
axis (int, optional): The distribution axis. Default: ``-1``.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.
Returns:
array: The computed Kullback-Leibler divergence loss.
"""
def smooth_l1_loss(
predictions: mx.array,
targets: mx.array,
beta: float = ...,
reduction: Reduction = ...,
) -> mx.array:
r"""
Computes the smooth L1 loss.
The smooth L1 loss is a variant of the L1 loss which replaces the absolute
difference with a squared difference when the absolute difference is less
than ``beta``.
The formula for the smooth L1 Loss is:
.. math::
l = \begin{cases}
0.5 (x - y)^2 / \beta, & \text{if } |x - y| < \beta \\
|x - y| - 0.5 \beta, & \text{otherwise}
\end{cases}
Args:
predictions (array): Predicted values.
targets (array): Ground truth values.
beta (float, optional): The threshold after which the loss changes
from the squared to the absolute difference. Default: ``1.0``.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'mean'``.
Returns:
array: The computed smooth L1 loss.
"""
def triplet_loss(
anchors: mx.array,
positives: mx.array,
negatives: mx.array,
axis: int = ...,
p: int = ...,
margin: float = ...,
eps: float = ...,
reduction: Reduction = ...,
) -> mx.array:
r"""
Computes the triplet loss for a set of anchor, positive, and negative samples.
Margin is represented with alpha in the math section.
.. math::
\max\left(\|A - P\|_p - \|A - N\|_p + \alpha, 0\right)
Args:
anchors (array): The anchor samples.
positives (array): The positive samples.
negatives (array): The negative samples.
axis (int, optional): The distribution axis. Default: ``-1``.
p (int, optional): The norm degree for pairwise distance. Default: ``2``.
margin (float, optional): Margin for the triplet loss. Defaults to ``1.0``.
eps (float, optional): Small positive constant to prevent numerical instability. Defaults to ``1e-6``.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.
Returns:
array: Computed triplet loss. If reduction is "none", returns a tensor of the same shape as input;
if reduction is "mean" or "sum", returns a scalar tensor.
"""
def hinge_loss(
inputs: mx.array, targets: mx.array, reduction: Reduction = ...
) -> mx.array:
r"""
Computes the hinge loss between inputs and targets.
.. math::
\text{hinge}(y, y_{\text{pred}}) = \max(0, 1 - y \cdot y_{\text{pred}})
Args:
inputs (array): The predicted values.
targets (array): The target values. They should be -1 or 1.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.
Returns:
array: The computed hinge loss.
"""
def huber_loss(
inputs: mx.array, targets: mx.array, delta: float = ..., reduction: Reduction = ...
) -> mx.array:
r"""
Computes the Huber loss between inputs and targets.
.. math::
l_{\delta}(a) =
\left\{ \begin{array}{ll}
\frac{1}{2} a^2 & \text{for } |a| \leq \delta, \\
\delta \left( |a| - \frac{1}{2} \delta \right) & \text{otherwise.}
\end{array} \right.
Args:
inputs (array): The predicted values.
targets (array): The target values.
delta (float, optional): The threshold at which to change between L1 and L2 loss.
Default: ``1.0``.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.
Returns:
array: The computed Huber loss.
"""
def log_cosh_loss(
inputs: mx.array, targets: mx.array, reduction: Reduction = ...
) -> mx.array:
r"""
Computes the log cosh loss between inputs and targets.
Logcosh acts like L2 loss for small errors, ensuring stable gradients,
and like the L1 loss for large errors, reducing sensitivity to outliers. This
dual behavior offers a balanced, robust approach for regression tasks.
.. math::
\text{logcosh}(y_{\text{true}}, y_{\text{pred}}) =
\frac{1}{n} \sum_{i=1}^{n}
\log(\cosh(y_{\text{pred}}^{(i)} - y_{\text{true}}^{(i)}))
Args:
inputs (array): The predicted values.
targets (array): The target values.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.
Returns:
array: The computed log cosh loss.
"""
def cosine_similarity_loss(
x1: mx.array,
x2: mx.array,
axis: int = ...,
eps: float = ...,
reduction: Reduction = ...,
) -> mx.array:
r"""
Computes the cosine similarity between the two inputs.
The cosine similarity loss is given by
.. math::
\frac{x_1 \cdot x_2}{\max(\|x_1\| \cdot \|x_2\|, \epsilon)}
Args:
x1 (mx.array): The first set of inputs.
x2 (mx.array): The second set of inputs.
axis (int, optional): The embedding axis. Default: ``1``.
eps (float, optional): The minimum value of the denominator used for
numerical stability. Default: ``1e-8``.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.
Returns:
mx.array: The computed cosine similarity loss.
"""
def margin_ranking_loss(
inputs1: mx.array,
inputs2: mx.array,
targets: mx.array,
margin: float = ...,
reduction: Reduction = ...,
) -> mx.array:
r"""
Calculate the margin ranking loss that loss given inputs :math:`x_1`, :math:`x_2` and a label
:math:`y` (containing 1 or -1).
The loss is given by:
.. math::
\text{loss} = \max (0, -y * (x_1 - x_2) + \text{margin})
Where :math:`y` represents ``targets``, :math:`x_1` represents ``inputs1`` and :math:`x_2`
represents ``inputs2``.
Args:
inputs1 (array): Scores for the first input.
inputs2 (array): Scores for the second input.
targets (array): Labels indicating whether samples in ``inputs1`` should be ranked higher
than samples in ``inputs2``. Values should be 1 or -1.
margin (float, optional): The margin by which the scores should be separated.
Default: ``0.0``.
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. Default: ``'none'``.
Returns:
array: The computed margin ranking loss.
Examples:
>>> import mlx.core as mx
>>> import mlx.nn as nn
>>> targets = mx.array([1, 1, -1])
>>> inputs1 = mx.array([-0.573409, -0.765166, -0.0638])
>>> inputs2 = mx.array([0.75596, 0.225763, 0.256995])
>>> loss = nn.losses.margin_ranking_loss(inputs1, inputs2, targets)
>>> loss
array(0.773433, dtype=float32)
"""

View File

@@ -0,0 +1,73 @@
"""
This type stub file was generated by pyright.
"""
from typing import Any, Callable, Optional
import mlx.core as mx
from .layers.base import Module
def value_and_grad(
model: Module, fn: Callable
): # -> _Wrapped[..., Any, ..., tuple[Any, Any]]:
"""Transform the passed function ``fn`` to a function that computes the
gradients of ``fn`` wrt the model's trainable parameters and also its
value.
Args:
model (Module): The model whose trainable parameters to compute
gradients for
fn (Callable): The scalar function to compute gradients for
Returns:
A callable that returns the value of ``fn`` and the gradients wrt the
trainable parameters of ``model``
"""
def checkpoint(
module: Module, fn: Optional[Callable] = ...
): # -> _Wrapped[..., Any, ..., Any]:
"""Transform the passed callable to one that performs gradient
checkpointing with respect to the trainable parameters of the module (and
the callable's inputs).
Args:
module (Module): The module for whose parameters we will be
performing gradient checkpointing.
fn (Callable, optional): The function to checkpoint. If not provided it
defaults to the provided module.
Returns:
A callable that saves the inputs and outputs during the forward pass
and recomputes all intermediate states during the backward pass.
"""
def average_gradients(
gradients: Any,
group: Optional[mx.distributed.Group] = ...,
all_reduce_size: int = ...,
communication_type: Optional[mx.Dtype] = ...,
communication_stream: Optional[mx.Stream] = ...,
): # -> Any:
"""Average the gradients across the distributed processes in the passed group.
This helper enables concatenating several gradients of small arrays to one
big all reduce call for better networking performance.
Args:
gradients (Any): The Python tree containing the gradients (it should
have the same structure across processes)
group (Optional[mlx.core.distributed.Group]): The group of processes to
average the gradients. If set to ``None`` the global group is used.
Default: ``None``.
all_reduce_size (int): Group arrays until their size in bytes exceeds
this number. Perform one communication step per group of arrays. If
less or equal to 0 array grouping is disabled. Default: ``32MiB``.
communication_type (Optional[mlx.core.Dtype]): If provided cast to this
type before performing the communication. Typically cast to a
smaller float to reduce the communication size. Default: ``None``.
communication_stream (Optional[mlx.core.Stream]): The stream to usse
for the communication. If unspecified the default communication
stream is used which can vary by back-end. Default: ``None``.
"""

189
.mlx_typings/mlx/utils.pyi Normal file
View File

@@ -0,0 +1,189 @@
"""
This type stub file was generated by pyright.
"""
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from mlx.core import MX_ARRAY_TREE
def tree_map(
fn: Callable, tree: Any, *rest: Any, is_leaf: Optional[Callable] = ...
) -> Any:
"""Applies ``fn`` to the leaves of the Python tree ``tree`` and
returns a new collection with the results.
If ``rest`` is provided, every item is assumed to be a superset of ``tree``
and the corresponding leaves are provided as extra positional arguments to
``fn``. In that respect, :meth:`tree_map` is closer to :func:`itertools.starmap`
than to :func:`map`.
The keyword argument ``is_leaf`` decides what constitutes a leaf from
``tree`` similar to :func:`tree_flatten`.
.. code-block:: python
import mlx.nn as nn
from mlx.utils import tree_map
model = nn.Linear(10, 10)
print(model.parameters().keys())
# dict_keys(['weight', 'bias'])
# square the parameters
model.update(tree_map(lambda x: x*x, model.parameters()))
Args:
fn (callable): The function that processes the leaves of the tree.
tree (Any): The main Python tree that will be iterated upon.
rest (tuple[Any]): Extra trees to be iterated together with ``tree``.
is_leaf (callable, optional): An optional callable that returns ``True``
if the passed object is considered a leaf or ``False`` otherwise.
Returns:
A Python tree with the new values returned by ``fn``.
"""
def tree_map_with_path(
fn: Callable,
tree: Any,
*rest: Any,
is_leaf: Optional[Callable] = ...,
path: Optional[Any] = ...,
) -> Any:
"""Applies ``fn`` to the path and leaves of the Python tree ``tree`` and
returns a new collection with the results.
This function is the same :func:`tree_map` but the ``fn`` takes the path as
the first argument followed by the remaining tree nodes.
Args:
fn (callable): The function that processes the leaves of the tree.
tree (Any): The main Python tree that will be iterated upon.
rest (tuple[Any]): Extra trees to be iterated together with ``tree``.
is_leaf (Optional[Callable]): An optional callable that returns ``True``
if the passed object is considered a leaf or ``False`` otherwise.
path (Optional[Any]): Prefix will be added to the result.
Returns:
A Python tree with the new values returned by ``fn``.
Example:
>>> from mlx.utils import tree_map_with_path
>>> tree = {"model": [{"w": 0, "b": 1}, {"w": 0, "b": 1}]}
>>> new_tree = tree_map_with_path(lambda path, _: print(path), tree)
model.0.w
model.0.b
model.1.w
model.1.b
"""
def tree_flatten(
tree: Any,
prefix: str = ...,
is_leaf: Optional[Callable] = ...,
destination: Optional[Union[List[Tuple[str, Any]], Dict[str, Any]]] = ...,
) -> Union[List[Tuple[str, Any]], Dict[str, Any]]:
"""Flattens a Python tree to a list of key, value tuples.
The keys are using the dot notation to define trees of arbitrary depth and
complexity.
.. code-block:: python
from mlx.utils import tree_flatten
print(tree_flatten([[[0]]]))
# [("0.0.0", 0)]
print(tree_flatten([[[0]]], prefix=".hello"))
# [("hello.0.0.0", 0)]
tree_flatten({"a": {"b": 1}}, destination={})
{"a.b": 1}
.. note::
Dictionaries should have keys that are valid Python identifiers.
Args:
tree (Any): The Python tree to be flattened.
prefix (str): A prefix to use for the keys. The first character is
always discarded.
is_leaf (callable): An optional callable that returns True if the
passed object is considered a leaf or False otherwise.
destination (list or dict, optional): A list or dictionary to store the
flattened tree. If None an empty list will be used. Default: ``None``.
Returns:
Union[List[Tuple[str, Any]], Dict[str, Any]]: The flat representation of
the Python tree.
"""
def tree_unflatten(tree: Union[List[Tuple[str, Any]], Dict[str, Any]]) -> Any:
"""Recreate a Python tree from its flat representation.
.. code-block:: python
from mlx.utils import tree_unflatten
d = tree_unflatten([("hello.world", 42)])
print(d)
# {"hello": {"world": 42}}
d = tree_unflatten({"hello.world": 42})
print(d)
# {"hello": {"world": 42}}
Args:
tree (list[tuple[str, Any]] or dict[str, Any]): The flat representation of a Python tree.
For instance as returned by :meth:`tree_flatten`.
Returns:
A Python tree.
"""
def tree_reduce(
fn: Callable[[Any, Any], Any],
tree: list[MX_ARRAY_TREE] | tuple[MX_ARRAY_TREE, ...] | dict[str, MX_ARRAY_TREE],
initializer=...,
is_leaf=...,
) -> None:
"""Applies a reduction to the leaves of a Python tree.
This function reduces Python trees into an accumulated result by applying
the provided function ``fn`` to the leaves of the tree.
Example:
>>> from mlx.utils import tree_reduce
>>> tree = {"a": [1, 2, 3], "b": [4, 5]}
>>> tree_reduce(lambda acc, x: acc + x, tree, 0)
15
Args:
fn (callable): The reducer function that takes two arguments (accumulator,
current value) and returns the updated accumulator.
tree (Any): The Python tree to reduce. It can be any nested combination of
lists, tuples, or dictionaries.
initializer (Any, optional): The initial value to start the reduction. If
not provided, the first leaf value is used.
is_leaf (callable, optional): A function to determine if an object is a
leaf, returning ``True`` for leaf nodes and ``False`` otherwise.
Returns:
Any: The accumulated value.
"""
def tree_merge(
tree_a, tree_b, merge_fn=...
): # -> dict[Any, Any] | list[Any] | tuple[Any, *tuple[Any, ...]] | tuple[Any, ...]:
"""Merge two Python trees in one containing the values of both. It can be
thought of as a deep dict.update method.
Args:
tree_a (Any): The first Python tree.
tree_b (Any): The second Python tree.
merge_fn (callable, optional): A function to merge leaves.
Returns:
The Python tree containing the values of both ``tree_a`` and
``tree_b``.
"""

View File

@@ -0,0 +1,3 @@
import models as models
import tokenizer_utils as tokenizer_utils
from generate import *

View File

@@ -0,0 +1,45 @@
"""
This type stub file was generated by pyright.
"""
import argparse
from typing import Callable, Optional, Union
import mlx.nn as nn
def mixed_quant_predicate_builder(
recipe: str, model: nn.Module, group_size: int = ...
) -> Callable[[str, nn.Module, dict], Union[bool, dict]]: ...
QUANT_RECIPES = ...
MODEL_CONVERSION_DTYPES = ...
def convert(
hf_path: str,
mlx_path: str = ...,
quantize: bool = ...,
q_group_size: int = ...,
q_bits: int = ...,
q_mode: str = ...,
dtype: Optional[str] = ...,
upload_repo: str = ...,
revision: Optional[str] = ...,
dequantize: bool = ...,
quant_predicate: Optional[
Union[Callable[[str, nn.Module, dict], Union[bool, dict]], str]
] = ...,
trust_remote_code: bool = ...,
): # -> None:
...
def configure_parser() -> argparse.ArgumentParser:
"""
Configures and returns the argument parser for the script.
Returns:
argparse.ArgumentParser: Configured argument parser.
"""
def main(): # -> None:
...
if __name__ == "__main__": ...

View File

@@ -0,0 +1,324 @@
"""
This type stub file was generated by pyright.
"""
import contextlib
from dataclasses import dataclass
from typing import Any, Callable, Generator, List, Optional, Tuple, Union
import mlx.core as mx
import mlx.nn as nn
from transformers import PreTrainedTokenizer
from .tokenizer_utils import TokenizerWrapper
DEFAULT_PROMPT = ...
DEFAULT_MAX_TOKENS = ...
DEFAULT_TEMP = ...
DEFAULT_TOP_P = ...
DEFAULT_MIN_P = ...
DEFAULT_TOP_K = ...
DEFAULT_XTC_PROBABILITY = ...
DEFAULT_XTC_THRESHOLD = ...
DEFAULT_MIN_TOKENS_TO_KEEP = ...
DEFAULT_SEED = ...
DEFAULT_MODEL = ...
DEFAULT_QUANTIZED_KV_START = ...
def str2bool(string): # -> bool:
...
def setup_arg_parser(): # -> ArgumentParser:
"""Set up and return the argument parser."""
generation_stream = ...
@contextlib.contextmanager
def wired_limit(
model: nn.Module, streams: Optional[List[mx.Stream]] = ...
): # -> Generator[None, Any, None]:
"""
A context manager to temporarily change the wired limit.
Note, the wired limit should not be changed during an async eval. If an
async eval could be running pass in the streams to synchronize with prior
to exiting the context manager.
"""
@dataclass
class GenerationResponse:
"""
The output of :func:`stream_generate`.
Args:
text (str): The next segment of decoded text. This can be an empty string.
token (int): The next token.
from_draft (bool): Whether the token was generated by the draft model.
logprobs (mx.array): A vector of log probabilities.
prompt_tokens (int): The number of tokens in the prompt.
prompt_tps (float): The prompt processing tokens-per-second.
generation_tokens (int): The number of generated tokens.
generation_tps (float): The tokens-per-second for generation.
peak_memory (float): The peak memory used so far in GB.
finish_reason (str): The reason the response is being sent: "length", "stop" or `None`
"""
text: str
token: int
logprobs: mx.array
from_draft: bool
prompt_tokens: int
prompt_tps: float
generation_tokens: int
generation_tps: float
peak_memory: float
finish_reason: Optional[str] = ...
def maybe_quantize_kv_cache(
prompt_cache, quantized_kv_start, kv_group_size, kv_bits
): # -> None:
...
def generate_step(
prompt: mx.array,
model: nn.Module,
*,
max_tokens: int = ...,
sampler: Optional[Callable[[mx.array], mx.array]] = ...,
logits_processors: Optional[List[Callable[[mx.array, mx.array], mx.array]]] = ...,
max_kv_size: Optional[int] = ...,
prompt_cache: Optional[Any] = ...,
prefill_step_size: int = ...,
kv_bits: Optional[int] = ...,
kv_group_size: int = ...,
quantized_kv_start: int = ...,
prompt_progress_callback: Optional[Callable[[int], int]] = ...,
input_embeddings: Optional[mx.array] = ...,
) -> Generator[Tuple[mx.array, mx.array], None, None]:
"""
A generator producing token ids based on the given prompt from the model.
Args:
prompt (mx.array): The input prompt.
model (nn.Module): The model to use for generation.
max_tokens (int): The maximum number of tokens. Use``-1`` for an infinite
generator. Default: ``256``.
sampler (Callable[mx.array, mx.array], optional): A sampler for sampling a
token from a vector of log probabilities. Default: ``None``.
logits_processors (List[Callable[[mx.array, mx.array], mx.array]], optional):
A list of functions that take tokens and logits and return the processed
logits. Default: ``None``.
max_kv_size (int, optional): Maximum size of the key-value cache. Old
entries (except the first 4 tokens) will be overwritten.
prompt_cache (List[Any], optional): A pre-computed prompt cache. Note, if
provided, the cache will be updated in place.
prefill_step_size (int): Step size for processing the prompt.
kv_bits (int, optional): Number of bits to use for KV cache quantization.
None implies no cache quantization. Default: ``None``.
kv_group_size (int): Group size for KV cache quantization. Default: ``64``.
quantized_kv_start (int): Step to begin using a quantized KV cache.
when ``kv_bits`` is non-None. Default: ``0``.
prompt_progress_callback (Callable[[int], int]): A call-back which takes the
prompt tokens processed so far and the total number of prompt tokens.
input_embeddings (mx.array, optional): Input embeddings to use instead of or in
conjunction with prompt tokens. Default: ``None``.
Yields:
Tuple[mx.array, mx.array]: One token and a vector of log probabilities.
"""
def speculative_generate_step(
prompt: mx.array,
model: nn.Module,
draft_model: nn.Module,
*,
num_draft_tokens: int = ...,
max_tokens: int = ...,
sampler: Optional[Callable[[mx.array], mx.array]] = ...,
logits_processors: Optional[List[Callable[[mx.array, mx.array], mx.array]]] = ...,
prompt_cache: Optional[Any] = ...,
prefill_step_size: int = ...,
kv_bits: Optional[int] = ...,
kv_group_size: int = ...,
quantized_kv_start: int = ...,
) -> Generator[Tuple[mx.array, mx.array, bool], None, None]:
"""
A generator producing token ids based on the given prompt from the model.
Args:
prompt (mx.array): The input prompt.
model (nn.Module): The model to use for generation.
draft_model (nn.Module): The draft model for speculative decoding.
num_draft_tokens (int, optional): The number of draft tokens for
speculative decoding. Default: ``2``.
max_tokens (int): The maximum number of tokens. Use``-1`` for an infinite
generator. Default: ``256``.
sampler (Callable[[mx.array], mx.array], optional): A sampler for sampling a
token from a vector of log probabilities. Default: ``None``.
logits_processors (List[Callable[[mx.array, mx.array], mx.array]], optional):
A list of functions that take tokens and logits and return the processed
logits. Default: ``None``.
prompt_cache (List[Any], optional): A pre-computed prompt cache. Note, if
provided, the cache will be updated in place. The cache must be trimmable.
prefill_step_size (int): Step size for processing the prompt.
kv_bits (int, optional): Number of bits to use for KV cache quantization.
None implies no cache quantization. Default: ``None``.
kv_group_size (int): Group size for KV cache quantization. Default: ``64``.
quantized_kv_start (int): Step to begin using a quantized KV cache.
when ``kv_bits`` is non-None. Default: ``0``.
Yields:
Tuple[mx.array, mx.array, bool]: One token, a vector of log probabilities,
and a bool indicating if the token was generated by the draft model
"""
def stream_generate(
model: nn.Module,
tokenizer: Union[PreTrainedTokenizer, TokenizerWrapper],
prompt: Union[str, mx.array, List[int]],
max_tokens: int = ...,
draft_model: Optional[nn.Module] = ...,
**kwargs: object,
) -> Generator[GenerationResponse, None, None]:
"""
A generator producing text based on the given prompt from the model.
Args:
model (nn.Module): The model to use for generation.
tokenizer (PreTrainedTokenizer): The tokenizer.
prompt (Union[str, mx.array, List[int]]): The input prompt string or
integer tokens.
max_tokens (int): The maximum number of tokens to generate.
Default: ``256``.
draft_model (Optional[nn.Module]): An optional draft model. If provided
then speculative decoding is used. The draft model must use the same
tokenizer as the main model. Default: ``None``.
kwargs: The remaining options get passed to :func:`generate_step`.
See :func:`generate_step` for more details.
Yields:
GenerationResponse: An instance containing the generated text segment and
associated metadata. See :class:`GenerationResponse` for details.
"""
def generate(
model: nn.Module,
tokenizer: Union[PreTrainedTokenizer, TokenizerWrapper],
prompt: Union[str, List[int]],
verbose: bool = ...,
**kwargs,
) -> str:
"""
Generate a complete response from the model.
Args:
model (nn.Module): The language model.
tokenizer (PreTrainedTokenizer): The tokenizer.
prompt (Union[str, List[int]]): The input prompt string or integer tokens.
verbose (bool): If ``True``, print tokens and timing information.
Default: ``False``.
kwargs: The remaining options get passed to :func:`stream_generate`.
See :func:`stream_generate` for more details.
"""
@dataclass
class BatchStats:
"""
An data object to hold generation stats.
Args:
prompt_tokens (int): The number of prompt tokens processed.
prompt_tps (float): The prompt processing tokens-per-second.
prompt_time (float): The time in seconds spent in prompt processing.
generation_tokens (int): The number of generated tokens.
generation_tps (float): The tokens-per-second for generation.
generation_time (float): The time in seconds spent in generation .
peak_memory (float): The peak memory used so far in GB.
"""
prompt_tokens: int = ...
prompt_tps: float = ...
prompt_time: float = ...
generation_tokens: int = ...
generation_tps: float = ...
generation_time: float = ...
peak_memory: float = ...
@dataclass
class BatchResponse:
"""
An data object to hold a batch generation response.
Args:
texts: (List[str]): The generated text for each prompt.
stats (BatchStats): Statistics about the generation.
"""
texts: List[str]
stats: BatchStats
@dataclass
class Batch:
uids: List[int]
y: mx.array
logprobs: mx.array
max_tokens: List[int]
num_tokens: List[int]
cache: List[Any]
def __len__(self): # -> int:
...
def filter(self, keep_idx: List[int]): # -> None:
...
def extend(self, other): # -> None:
...
class BatchGenerator:
@dataclass
class Response:
uid: int
token: int
logprobs: mx.array
finish_reason: Optional[str]
def __init__(
self,
model,
max_tokens: int = ...,
stop_tokens: Optional[set] = ...,
sampler: Optional[Callable[[mx.array], mx.array]] = ...,
completion_batch_size: int = ...,
prefill_batch_size: int = ...,
prefill_step_size: int = ...,
) -> None: ...
def insert(
self, prompts, max_tokens: Union[List[int], int, None] = ...
): # -> list[Any]:
...
def stats(self): # -> BatchStats:
...
def next(self): # -> list[Any]:
...
def batch_generate(
model,
tokenizer,
prompts: List[int],
max_tokens: Union[int, List[int]] = ...,
verbose: bool = ...,
**kwargs,
) -> BatchResponse:
"""
Generate responses for the given batch of prompts.
Args:
model (nn.Module): The language model.
tokenizer (PreTrainedTokenizer): The tokenizer.
prompt (List[List[int]]): The input prompts.
verbose (bool): If ``True``, print tokens and timing information.
Default: ``False``.
max_tokens (Union[int, List[int]): Maximum number of output tokens. This
can be per prompt if a list is provided.
kwargs: The remaining options get passed to :obj:`BatchGenerator`.
See :obj:`BatchGenerator` for more details.
"""
def main(): # -> None:
...
if __name__ == "__main__": ...

View File

@@ -0,0 +1 @@
import cache as cache

View File

@@ -0,0 +1,47 @@
"""
This type stub file was generated by pyright.
"""
from dataclasses import dataclass
from typing import Optional
import mlx.core as mx
@dataclass
class BaseModelArgs:
@classmethod
def from_dict(cls, params): # -> Self:
...
def create_causal_mask(
N: int,
offset: int = ...,
window_size: Optional[int] = ...,
right_padding: Optional[mx.array] = ...,
left_padding: Optional[mx.array] = ...,
): # -> array:
...
def create_attention_mask(
h, cache=..., window_size: Optional[int] = ..., return_array: bool = ...
): # -> array | Literal['causal'] | None:
...
def create_ssm_mask(h, cache=...): # -> None:
...
def quantized_scaled_dot_product_attention(
queries: mx.array,
q_keys: tuple[mx.array, mx.array, mx.array],
q_values: tuple[mx.array, mx.array, mx.array],
scale: float,
mask: Optional[mx.array],
group_size: int = ...,
bits: int = ...,
) -> mx.array: ...
def scaled_dot_product_attention(
queries,
keys,
values,
cache,
scale: float,
mask: Optional[mx.array],
sinks: Optional[mx.array] = ...,
) -> mx.array: ...

View File

@@ -0,0 +1,26 @@
"""
This type stub file was generated by pyright.
"""
import mlx.nn as nn
def bitnet_quantize(model, quantization_config: dict): ...
def make_bitlinear_kernel():
"""
Custom Metal kernel that performs matrix multiplication directly on
packed weights and scales the output. This eliminates the need to
store unpacked weights in memory.
"""
_bitlinear_kernel = ...
class BitLinear(nn.Module):
"""
BitLinear module with memory-efficient weight handling.
"""
def __init__(
self, in_features, out_features, bias=..., invert_weight_scales=...
) -> None: ...
def execute_matmul_kernel(self, x, packed_weights): ...
def __call__(self, x): # -> array:
...

View File

@@ -0,0 +1,357 @@
"""
This type stub file was generated by pyright.
"""
from typing import Any, Dict, List, Optional, Protocol, Literal, Self
import mlx.nn as nn
from mlx.core import array
import mlx.core as mx
class Cache(Protocol):
keys: mx.array
values: mx.array
def update_and_fetch(self, keys: mx.array, values: mx.array) -> None: ...
@property
def state(self) -> tuple[mx.array, mx.array]: ...
@state.setter
def state(self, v) -> None: ...
def make_prompt_cache(
model: nn.Module, max_kv_size: Optional[int] = ...
) -> List[Cache | Any]:
"""
Construct the model's cache for use in generation.
This function will defer the cache construction to the model if it has a
``make_cache`` method, otherwise it will make a default KV cache.
Args:
model (nn.Module): The language model.
max_kv_size (Optional[int]): If provided and the model does not have a
``make_cache`` method, a ``RotatingKVCache`` is used with a maximum
size of ``max_kv_size``
"""
def save_prompt_cache(
file_name: str, cache: List[Cache], metadata: Dict[str, str] = ...
) -> None:
"""
Save a pre-computed prompt cache to a file.
Args:
file_name (str): The ``.safetensors`` file name.
cache (List[Any]): The model state.
metadata (Dict[str, str]): Optional metadata to save along with model
state.
"""
def load_prompt_cache(file_name: str, return_metadata=...) -> array:
"""
Load a prompt cache from a file.
Args:
file_name (str): The ``.safetensors`` file name.
return_metadata (bool): Whether or not to return metadata.
Default: ``False``.
Returns:
List[Any] or Tuple[List[Any], Dict[str, str]]: The prompt cache and
the metadata if requested.
"""
def can_trim_prompt_cache(cache: List[Cache]) -> bool:
"""
Check if model's cache can be trimmed.
"""
def trim_prompt_cache(cache: List[Cache], num_tokens: int) -> List[Cache]:
"""
Trim the model's cache by the given number of tokens.
This function will trim the cache if possible (in-place) and return the
number of tokens that were trimmed.
Args:
cache (List[Any]): The model's cache.
num_tokens (int): The number of tokens to trim.
Returns:
(int): The number of tokens that were trimmed.
"""
def create_attention_mask(
N: int, offset: int, return_array: bool, window_size: Optional[int]
) -> array | Literal["causal"] | None: ...
class _BaseCache(Cache):
keys: mx.array
values: mx.array
@property
def state(self) -> tuple[mx.array, mx.array]: ...
@state.setter
def state(self, v) -> None: ...
@property
def meta_state(self) -> Literal[""]: ...
@meta_state.setter
def meta_state(self, v) -> None: ...
def is_trimmable(self) -> Literal[False]: ...
@classmethod
def from_state(cls, state, meta_state) -> Self: ...
class ConcatenateKVCache(_BaseCache):
"""ConcatenateKVCache the simplest KV cache implementation.
Can be used as a mock KV cache or when large blocks are being processed at
a time in which case KVCache isn't necessarily faster. Consider using the
KVCache with a larger step size before using this cache.
"""
def __init__(self) -> None: ...
def update_and_fetch(self, keys, values): # -> tuple[Any | array, Any | array]:
...
@property
def state(self): # -> tuple[Any | array | None, Any | array | None]:
...
@state.setter
def state(self, v): # -> None:
...
def is_trimmable(self): # -> Literal[True]:
...
def trim(self, n): # -> int:
...
def make_mask(self, *args, **kwargs): # -> array | Literal['causal'] | None:
...
class QuantizedKVCache(_BaseCache):
step = ...
def __init__(self, group_size: int = ..., bits: int = ...) -> None: ...
def update_and_fetch(self, keys, values): # -> Any:
...
@property
def state(
self,
): # -> tuple[Any | tuple[array, array, array] | None, Any | tuple[array, array, array] | None] | Any:
...
@state.setter
def state(self, v): # -> None:
...
@property
def meta_state(self): # -> tuple[str, ...]:
...
@meta_state.setter
def meta_state(self, v): # -> None:
...
def is_trimmable(self): # -> Literal[True]:
...
def trim(self, n): # -> int:
...
def make_mask(self, *args, **kwargs): # -> array | Literal['causal'] | None:
...
class KVCache(_BaseCache):
step = ...
def __init__(self) -> None: ...
def update_and_fetch(self, keys, values): # -> tuple[array | Any, array | Any]:
...
@property
def state(
self,
) -> tuple[array, array]: ...
@state.setter
def state(self, v) -> None: ...
def is_trimmable(self): # -> Literal[True]:
...
def trim(self, n): # -> int:
...
def to_quantized(
self, group_size: int = ..., bits: int = ...
) -> QuantizedKVCache: ...
def make_mask(self, *args, **kwargs): # -> array | Literal['causal'] | None:
...
class RotatingKVCache(_BaseCache):
step = ...
def __init__(self, max_size, keep=...) -> None: ...
def update_and_fetch(
self, keys, values
): # -> tuple[array | Any, array | Any] | tuple[array | Any, array | Any | None]:
...
@property
def state(
self,
): # -> tuple[Any | array, Any | array] | tuple[Any | array | None, Any | array | None]:
...
@state.setter
def state(self, v): # -> None:
...
@property
def meta_state(self): # -> tuple[str, ...]:
...
@meta_state.setter
def meta_state(self, v): # -> None:
...
def is_trimmable(self): # -> bool:
...
def trim(self, n): # -> int:
...
def to_quantized(
self, group_size: int = ..., bits: int = ...
) -> QuantizedKVCache: ...
def make_mask(
self, N: int, window_size: Optional[int] = ..., return_array: bool = ...
): # -> array | Literal['causal'] | None:
...
class ArraysCache(_BaseCache):
def __init__(self, size, left_padding: Optional[List[int]] = ...) -> None: ...
def __setitem__(self, idx, value): # -> None:
...
def __getitem__(self, idx): ...
@property
def state(self): # -> list[Any | array] | list[array]:
...
@state.setter
def state(self, v): # -> None:
...
def filter(self, batch_indices): # -> None:
"""
In-place filter to keep just the given indices in the cache.
"""
def extend(self, other): # -> None:
"""
In-place extend this cache with the other cache.
"""
def make_mask(self, N: int): # -> array | None:
...
class MambaCache(ArraysCache):
def __init__(self, left_padding: Optional[List[int]] = ...) -> None: ...
class ChunkedKVCache(KVCache):
def __init__(self, chunk_size) -> None: ...
def maybe_trim_front(self): # -> None:
...
def update_and_fetch(self, keys, values): # -> tuple[array, array]:
...
def trim(self, n): # -> int:
...
@property
def meta_state(self): # -> tuple[str, ...]:
...
@meta_state.setter
def meta_state(self, v): # -> None:
...
class CacheList(_BaseCache):
def __init__(self, *caches) -> None: ...
def __getitem__(self, idx): ...
def is_trimmable(self): # -> bool:
...
def trim(self, n): ...
@property
def state(self): # -> list[Any]:
...
@state.setter
def state(self, v): # -> None:
...
def filter(self, batch_indices): # -> None:
"""
In-place filter to keep just the given indices in the cache.
"""
def extend(self, other): # -> None:
"""
In-place extend this cache with the other cache.
"""
class BatchKVCache(_BaseCache):
step = ...
def __init__(self, left_padding: List[int]) -> None:
"""
The BatchKV cache expects inputs to be left-padded.
E.g. the following prompts:
[1, 3, 5]
[7]
[2, 6, 8, 9]
Should be padded like so:
[0, 1, 3, 5]
[0, 0, 0, 7]
[2, 6, 8, 9]
And ``left_padding`` specifies the amount of padding for each.
In this case, ``left_padding = [1, 3, 0]``.
"""
def update_and_fetch(self, keys, values): # -> tuple[array | Any, array | Any]:
...
@property
def state(
self,
): # -> tuple[Any | array | None, Any | array | None, array | Any, array | Any]:
...
@state.setter
def state(self, v): # -> None:
...
def is_trimmable(self): # -> Literal[True]:
...
def trim(self, n): # -> int | float:
...
def make_mask(self, N: int, return_array: bool = ..., **kwargs): # -> array:
...
def filter(self, batch_indices): # -> None:
"""
In-place filter to keep just the given indices in the cache.
"""
def extend(self, other): # -> None:
"""
In-place extend this cache with the other cache.
"""
class BatchRotatingKVCache(_BaseCache):
step = ...
def __init__(self, max_size, left_padding: List[int]) -> None: ...
def update_and_fetch(
self, keys, values
): # -> tuple[array | Any, array | Any] | tuple[array | Any, array | Any | None]:
...
@property
def state(
self,
): # -> tuple[Any | array | None, Any | array | None, array | Any, array | Any]:
...
@state.setter
def state(self, v): # -> None:
...
@property
def meta_state(self): # -> tuple[str, ...]:
...
@meta_state.setter
def meta_state(self, v): # -> None:
...
def is_trimmable(self): # -> bool:
...
def trim(self, n): # -> int:
...
def to_quantized(
self, group_size: int = ..., bits: int = ...
) -> QuantizedKVCache: ...
def make_mask(
self, N: int, window_size: Optional[int] = ..., return_array: bool = ...
): # -> array:
...
def filter(self, batch_indices): # -> None:
"""
In-place filter to keep just the given indices in the cache.
"""
def extend(self, other): # -> None:
"""
In-place extend this cache with the other cache.
"""

View File

@@ -0,0 +1,79 @@
"""
This type stub file was generated by pyright.
"""
from functools import partial
import mlx.core as mx
import mlx.nn as nn
class QuantizedSwitchLinear(nn.Module):
def __init__(
self,
input_dims: int,
output_dims: int,
num_experts: int,
bias: bool = ...,
group_size: int = ...,
bits: int = ...,
mode: str = ...,
) -> None: ...
@property
def input_dims(self): # -> int:
...
@property
def output_dims(self): # -> int:
...
@property
def num_experts(self): # -> int:
...
def __call__(self, x, indices, sorted_indices=...): # -> array:
...
class SwitchLinear(nn.Module):
def __init__(
self, input_dims: int, output_dims: int, num_experts: int, bias: bool = ...
) -> None: ...
@property
def input_dims(self): # -> int:
...
@property
def output_dims(self): # -> int:
...
@property
def num_experts(self): # -> int:
...
def __call__(self, x, indices, sorted_indices=...): ...
def to_quantized(
self, group_size: int = ..., bits: int = ..., mode: str = ...
): # -> QuantizedSwitchLinear:
...
@partial(mx.compile, shapeless=True)
def swiglu(x, gate): ...
class SwiGLU(nn.Module):
def __init__(self) -> None: ...
def __call__(self, x, gate): ...
class SwitchGLU(nn.Module):
def __init__(
self,
input_dims: int,
hidden_dims: int,
num_experts: int,
activation=...,
bias: bool = ...,
) -> None: ...
def __call__(self, x, indices) -> mx.array: ...
class SwitchMLP(nn.Module):
def __init__(
self,
input_dims: int,
hidden_dims: int,
num_experts: int,
activation=...,
bias: bool = ...,
) -> None: ...
def __call__(self, x, indices) -> mx.array: ...

View File

@@ -0,0 +1,148 @@
"""
This type stub file was generated by pyright.
"""
from functools import partial
from typing import Callable, Dict, List, Optional
import mlx.core as mx
def make_sampler(
temp: float = ...,
top_p: float = ...,
min_p: float = ...,
min_tokens_to_keep: int = ...,
top_k: int = ...,
xtc_probability: float = ...,
xtc_threshold: float = ...,
xtc_special_tokens: List[int] = ...,
) -> Callable[[mx.array], mx.array]:
"""
Make a sampler function for use with ``generate_step``.
Args:
temp (float): The temperature for sampling, if 0 the argmax is used.
Default: ``0``.
top_p (float, optional): Nulceus sampling, higher means model considers
more less likely words.
min_p (float, optional): The minimum value (scaled by the top token's
probability) that a token probability must have to be considered.
min_tokens_to_keep (int, optional): Minimum number of tokens that cannot
be filtered by min_p sampling.
top_k (int, optional): The top k tokens ranked by probability to constrain
the sampling to.
xtc_probability (float, optional): The probability of applying XTC
sampling.
xtc_threshold (float, optional): The threshold the probs need to reach
for being sampled.
xtc_special_tokens (list(int), optional): List of special tokens IDs to
be excluded from XTC sampling.
Returns:
Callable[mx.array, mx.array]:
A sampler which takes log-probabilities and returns tokens.
"""
def make_logits_processors(
logit_bias: Optional[Dict[int, float]] = ...,
repetition_penalty: Optional[float] = ...,
repetition_context_size: Optional[int] = ...,
): # -> list[Any]:
"""
Make logits processors for use with ``generate_step``.
Args:
repetition_penalty (float, optional): The penalty factor for repeating
tokens.
repetition_context_size (int, optional): The number of tokens to
consider for repetition penalty. Default: ``20``.
logit_bias (dictionary, optional): Additive logit bias.
Returns:
List[Callable[[mx.array, mx.array], mx.array]]:
A list of logits processors. Each processor in the list is a
callable which takes an array of tokens and an array of logits
and returns the updated logits.
"""
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
def apply_top_k(logprobs: mx.array, top_k: int) -> mx.array:
"""
Sample from only the top K tokens ranked by probability.
Args:
logprobs: A vector of log probabilities.
top_k (int): Top k tokens to sample from.
"""
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
def apply_min_p(
logprobs: mx.array, min_p: float, min_tokens_to_keep: int = ...
) -> mx.array:
"""
Apply min-p sampling to the logprobs.
Min-p keeps all tokens that are above a minimum probability, scaled by the
probability of the most likely token. As a result, the filter is more
aggressive given a very high-probability token.
Args:
logprobs: A vector of log probabilities.
min_p (float): Minimum token probability. Typical values are in the
0.01-0.2 range, comparably selective as setting `top_p` in the
0.99-0.8 range.
min_tokens_to_keep (int, optional): Minimum number of tokens that cannot
be filtered. Default: ``1``.
"""
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
def apply_top_p(logprobs: mx.array, top_p: float) -> mx.array:
"""
Apply top-p (nucleus) sampling to logits.
Args:
logprobs: A vector of log probabilities.
top_p: The cumulative probability threshold for top-p filtering.
Returns:
token selected based on the top-p criterion.
"""
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
def apply_xtc(
logits: mx.array,
xtc_probability: float,
xtc_threshold: float,
xtc_special_tokens: List[int],
) -> mx.array:
"""
Apply XTC sampling to the logits.
Args:
logits: The logits from the model's output.
xtc_probability (float): Probability of XTC sampling to happen for each token
xtc_threshold (float): The threshold the probs need to reach for being sampled.
special_tokens_ids (list(int)): List of special tokens IDs to be excluded from XTC sampling.
"""
@partial(mx.compile, inputs=mx.random.state, outputs=mx.random.state)
def categorical_sampling(logits, temp): # -> array:
...
def make_repetition_penalty(
penalty: float, context_size: int = ...
): # -> Callable[..., Any]:
"""
Make repetition penalty processor.
Paper: https://arxiv.org/abs/1909.05858
Args:
penalty (float): The repetition penalty factor to be applied.
context_size (int): The number of previous tokens to use.
Default: ``20``.
Returns:
Callable[[mx.array, List[int]], mx.array]:
The repetition penalty processor.
"""

View File

@@ -0,0 +1,168 @@
"""
This type stub file was generated by pyright.
"""
from functools import partial
from pathlib import Path
from transformers import PreTrainedTokenizerFast
class StreamingDetokenizer:
"""The streaming detokenizer interface so that we can detokenize one token at a time.
Example usage is as follows:
detokenizer = ...
# Reset the tokenizer state
detokenizer.reset()
for token in generate(...):
detokenizer.add_token(token.item())
# Contains the whole text so far. Some tokens may not be included
# since it contains whole words usually.
detokenizer.text
# Contains the printable segment (usually a word) since the last
# time it was accessed
detokenizer.last_segment
# Contains all the tokens added so far
detokenizer.tokens
# Make sure that we detokenize any remaining tokens
detokenizer.finalize()
# Now detokenizer.text should match tokenizer.decode(detokenizer.tokens)
"""
__slots__ = ...
def reset(self): ...
def add_token(self, token): ...
def finalize(self): ...
@property
def last_segment(self):
"""Return the last segment of readable text since last time this property was accessed."""
class NaiveStreamingDetokenizer(StreamingDetokenizer):
"""NaiveStreamingDetokenizer relies on the underlying tokenizer
implementation and should work with every tokenizer.
Its complexity is O(T^2) where T is the longest line since it will
repeatedly detokenize the same tokens until a new line is generated.
"""
def __init__(self, tokenizer) -> None: ...
def reset(self): # -> None:
...
def add_token(self, token): # -> None:
...
def finalize(self): # -> None:
...
@property
def text(self): # -> str:
...
class SPMStreamingDetokenizer(StreamingDetokenizer):
"""A streaming detokenizer for SPM models.
It adds tokens to the text if the next token starts with the special SPM
underscore which results in linear complexity.
"""
def __init__(self, tokenizer, trim_space=...) -> None: ...
def reset(self): # -> None:
...
def add_token(self, token): # -> None:
...
def finalize(self): # -> None:
...
class BPEStreamingDetokenizer(StreamingDetokenizer):
"""A streaming detokenizer for OpenAI style BPE models.
It adds tokens to the text if the next token starts with a space similar to
the SPM detokenizer.
"""
_byte_decoder = ...
_space_matches = ...
def __init__(self, tokenizer) -> None: ...
def reset(self): # -> None:
...
def add_token(self, token): # -> None:
...
def finalize(self): # -> None:
...
@classmethod
def make_byte_decoder(cls): # -> None:
"""See https://github.com/openai/gpt-2/blob/master/src/encoder.py for the rationale."""
class TokenizerWrapper:
"""A wrapper that combines an HF tokenizer and a detokenizer.
Accessing any attribute other than the ``detokenizer`` is forwarded to the
huggingface tokenizer.
"""
def __init__(self, tokenizer, detokenizer_class=..., eos_token_ids=...) -> None: ...
def add_eos_token(self, token: str): # -> None:
...
@property
def has_thinking(self): # -> bool:
...
@property
def think_start(self): # -> str | None:
...
@property
def think_end(self): # -> str | None:
...
@property
def has_tool_calling(self): # -> bool:
...
@property
def tool_call_start(self): # -> str | None:
...
@property
def tool_call_end(self): # -> str | None:
...
@property
def detokenizer(self): # -> NaiveStreamingDetokenizer:
"""
Get a stateful streaming detokenizer.
"""
def __getattr__(self, attr): # -> set[Any] | Any:
...
def __setattr__(self, attr, value): # -> None:
...
class NewlineTokenizer(PreTrainedTokenizerFast):
"""A tokenizer that replaces newlines with <n> and <n> with new line."""
def __init__(self, *args, **kwargs) -> None: ...
def encode(self, text, **kwargs): # -> list[int]:
...
def encode_batch(self, texts, **kwargs): ...
def decode(self, *args, **kwargs): # -> str:
...
def batch_decode(self, *args, **kwargs): # -> list[str]:
...
def load_tokenizer(
model_path: Path,
tokenizer_config_extra=...,
return_tokenizer=...,
eos_token_ids=...,
) -> (
TokenizerWrapper
| type[SPMStreamingDetokenizer]
| partial[SPMStreamingDetokenizer]
| type[BPEStreamingDetokenizer]
| type[NaiveStreamingDetokenizer]
):
"""Load a huggingface tokenizer and try to infer the type of streaming
detokenizer to use.
Note, to use a fast streaming tokenizer, pass a local file path rather than
a Hugging Face repo ID.
"""
def no_bos_or_eos(sequence: list, bos: int, eos: int) -> list: ...

View File

@@ -0,0 +1,195 @@
"""
This type stub file was generated by pyright.
"""
import os
from pathlib import Path
from typing import Any, Callable, Dict, Optional, Tuple, Type, Union
import mlx.nn as nn
from transformers.utils.auto_docstring import ModelArgs
from .tokenizer_utils import TokenizerWrapper
if os.getenv("MLXLM_USE_MODELSCOPE", "False").lower() == "true": ...
else: ...
MODEL_REMAPPING = ...
MAX_FILE_SIZE_GB = ...
def compute_bits_per_weight(model): ...
def hf_repo_to_path(hf_repo): # -> Path:
...
def load_config(model_path: Path) -> dict: ...
def load_model(
model_path: Path,
lazy: bool = False,
strict: bool = True,
model_config: dict[str, Any] = {},
get_model_classes: Callable[
[dict[str, Any]], Tuple[Type[nn.Module], Type[ModelArgs]]
] = ...,
) -> Tuple[nn.Module, dict[str, Any]]:
"""
Load and initialize the model from a given path.
Args:
model_path (Path): The path to load the model from.
lazy (bool): If False eval the model parameters to make sure they are
loaded in memory before returning, otherwise they will be loaded
when needed. Default: ``False``
strict (bool): Whether or not to raise an exception if weights don't
match. Default: ``True``
model_config (dict, optional): Optional configuration parameters for the
model. Defaults to an empty dictionary.
get_model_classes (Callable[[dict], Tuple[Type[nn.Module], Type]], optional):
A function that returns the model class and model args class given a config.
Defaults to the ``_get_classes`` function.
Returns:
Tuple[nn.Module, dict[str, Any]]: The loaded and initialized model and config.
Raises:
FileNotFoundError: If the weight files (.safetensors) are not found.
ValueError: If the model class or args class are not found or cannot be instantiated.
"""
def load(
path_or_hf_repo: str,
tokenizer_config=...,
model_config=...,
adapter_path: Optional[str] = ...,
lazy: bool = ...,
return_config: bool = ...,
revision: str = ...,
) -> Union[
Tuple[nn.Module, TokenizerWrapper],
Tuple[nn.Module, TokenizerWrapper, Dict[str, Any]],
]:
"""
Load the model and tokenizer from a given path or a huggingface repository.
Args:
path_or_hf_repo (Path): The path or the huggingface repository to load the model from.
tokenizer_config (dict, optional): Configuration parameters specifically for the tokenizer.
Defaults to an empty dictionary.
model_config(dict, optional): Configuration parameters specifically for the model.
Defaults to an empty dictionary.
adapter_path (str, optional): Path to the LoRA adapters. If provided, applies LoRA layers
to the model. Default: ``None``.
lazy (bool): If ``False`` eval the model parameters to make sure they are
loaded in memory before returning, otherwise they will be loaded
when needed. Default: ``False``
return_config (bool: If ``True`` return the model config as the last item..
revision (str, optional): A revision id which can be a branch name, a tag, or a commit hash.
Returns:
Union[Tuple[nn.Module, TokenizerWrapper], Tuple[nn.Module, TokenizerWrapper, Dict[str, Any]]]:
A tuple containing the loaded model, tokenizer and, if requested, the model config.
Raises:
FileNotFoundError: If config file or safetensors are not found.
ValueError: If model class or args class are not found.
"""
def make_shards(weights: dict, max_file_size_gb: int = ...) -> list:
"""
Splits the weights into smaller shards.
Args:
weights (dict): Model weights.
max_file_size_gb (int): Maximum size of each shard in gigabytes.
Returns:
list: List of weight shards.
"""
def create_model_card(
path: Union[str, Path], hf_path: Union[str, Path, None]
): # -> None:
"""
Uploads the model to Hugging Face hub.
Args:
path (Union[str, Path]): Local path to the model.
hf_path (Union[str, Path, None]): Path to the original Hugging Face model.
"""
def upload_to_hub(path: str, upload_repo: str): # -> None:
"""
Uploads the model to Hugging Face hub.
Args:
path (str): Local path to the model.
upload_repo (str): Name of the HF repo to upload to.
"""
def save_model(
save_path: Union[str, Path], model: nn.Module, *, donate_model: bool = ...
) -> None:
"""Save model weights and metadata index into specified directory."""
def quantize_model(
model: nn.Module,
config: dict,
group_size: int,
bits: int,
mode: str = ...,
quant_predicate: Optional[Callable[[str, nn.Module], Union[bool, dict]]] = ...,
) -> Tuple[nn.Module, dict]:
"""
Applies quantization to the model weights.
Args:
model (nn.Module): The model to be quantized.
config (dict): Model configuration.
group_size (int): Group size for quantization.
bits (int): Bits per weight for quantization.
mode (str): The quantization mode.
quant_predicate (Callable): A callable that decides how to quantize
each layer based on the path. Accepts the layer `path` and the
`module`. Returns either a bool to signify quantize/no quantize or
a dict of quantization parameters to pass to `to_quantized`.
Returns:
Tuple: Tuple containing quantized model and config.
"""
def save_config(config: dict, config_path: Union[str, Path]) -> None:
"""Save the model configuration to the ``config_path``.
The final configuration will be sorted before saving for better readability.
Args:
config (dict): The model configuration.
config_path (Union[str, Path]): Model configuration file path.
"""
def save(
dst_path: Union[str, Path],
src_path_or_repo: Union[str, Path],
model: nn.Module,
tokenizer: TokenizerWrapper,
config: Dict[str, Any],
donate_model: bool = ...,
): # -> None:
...
def common_prefix_len(list1, list2): # -> int:
"""
Calculates the length of the common prefix of two lists.
Args:
list1: The first list of strings.
list2: The second list of strings.
Returns:
The length of the common prefix. Returns 0 if lists are empty
or do not match at the first element.
"""
def does_model_support_input_embeddings(model: nn.Module) -> bool:
"""
Check if the model supports input_embeddings in its call signature.
Args:
model (nn.Module): The model to check.
Returns:
bool: True if the model supports input_embeddings, False otherwise.
"""

1
.python-version Normal file
View File

@@ -0,0 +1 @@
3.13

View File

@@ -1,19 +0,0 @@
[style]
based_on_style = pep8
indent_width = 2
column_limit = 200
allow_split_before_dict_value = False
dedent_closing_brackets = True
split_before_first_argument = False
split_complex_comprehension = False
continuation_indent_width = 2
indent_dictionary_value = True
allow_multiline_dictionary_keys = True
each_dict_entry_on_separate_line = False
allow_multiline_lambdas = True
blank_line_before_nested_class_or_def = False
arithmetic_precedence_indication = True
no_spaces_around_selected_binary_operators = "*,/"
coalesce_brackets = True
space_between_ending_comma_and_closing_bracket = False
split_before_expression_after_opening_paren = False

11
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,11 @@
{
"recommendations": [
"detachhead.basedpyright",
"ms-python.python"
],
"unwantedRecommendations": [
"ms-python.vscode-pylance",
"ms-python.pyright",
"ms-python.mypy-type-checker"
]
}

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"basedpyright.importStrategy": "fromEnvironment"
}

29
.zed/settings.json Normal file
View File

@@ -0,0 +1,29 @@
// Folder-specific settings
//
// For a full list of overridable settings, and general information on folder-specific settings,
// see the documentation: https://zed.dev/docs/configuring-zed#settings-files
{
"lsp": {
"nix_python": {
"binary": {
"path": "nix",
"arguments": [
"run",
"--quiet",
"--no-warn-dirty",
"--no-allow-import-from-derivation",
"--print-build-logs",
"never",
"${projectRoot}#python-lsp",
"--",
"--stdio"
]
}
}
},
"languages": {
"Python": {
"language_servers": ["nix_python"]
}
}
}

65
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,65 @@
# Contributing to EXO
Thank you for your interest in contributing to EXO!
## Getting Started
To run EXO from source:
**Prerequisites:**
- [uv](https://github.com/astral-sh/uv) (for Python dependency management)
```bash
brew install uv
```
- [macmon](https://github.com/vladkens/macmon) (for hardware monitoring on Apple Silicon)
```bash
brew install macmon
```
```bash
git clone https://github.com/exo-explore/exo.git
cd exo/dashboard
npm install && npm run build && cd ..
uv run exo
```
## Development
EXO is built with a mix of Rust, Python, and TypeScript (Svelte for the dashboard), and the codebase is actively evolving. Before starting work:
- Pull the latest source to ensure you're working with the most recent code
- Keep your changes focused - implement one feature or fix per pull request
- Avoid combining unrelated changes, even if they seem small
This makes reviews faster and helps us maintain code quality as the project evolves.
## Code Style
Write pure functions where possible. When adding new code, prefer Rust unless there's a good reason otherwise. Leverage the type systems available to you - Rust's type system, Python type hints, and TypeScript types. Comments should explain why you're doing something, not what the code does - especially for non-obvious decisions.
Run `nix fmt` to auto-format your code before submitting.
## Testing
EXO relies heavily on manual testing at this point in the project, but this is evolving. Before submitting a change, test both before and after to demonstrate how your change improves behavior. Do the best you can with the hardware you have available - if you need help testing, ask and we'll do our best to assist. Add automated tests where possible - we're actively working to substantially improve our automated testing story.
## Submitting Changes
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/your-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin feature/your-feature`)
5. Open a Pull Request and follow the PR template
## Reporting Issues
If you find a bug or have a feature request, please open an issue on GitHub with:
- A clear description of the problem or feature
- Steps to reproduce (for bugs)
- Expected vs actual behavior
- Your environment (macOS version, hardware, etc.)
## Questions?
Join our community:
- [X](https://x.com/exolabs)

5597
Cargo.lock generated Normal file
View File

File diff suppressed because it is too large Load Diff

165
Cargo.toml Normal file
View File

@@ -0,0 +1,165 @@
[workspace]
resolver = "3"
members = [
"rust/networking",
"rust/exo_pyo3_bindings",
"rust/system_custodian",
"rust/util",
]
[workspace.package]
version = "0.0.1"
edition = "2024"
[profile.dev]
opt-level = 1
debug = true
[profile.release]
opt-level = 3
# Common shared dependendencies configured once at the workspace
# level, to be re-used more easily across workspace member crates.
#
# Common configurations include versions, paths, features, etc.
[workspace.dependencies]
## Crate members as common dependencies
networking = { path = "rust/networking" }
system_custodian = { path = "rust/system_custodian" }
util = { path = "rust/util" }
# Proc-macro authoring tools
syn = "2.0"
quote = "1.0"
proc-macro2 = "1.0"
darling = "0.20"
# Macro dependecies
extend = "1.2"
delegate = "0.13"
impl-trait-for-tuples = "0.2"
clap = "4.5"
derive_more = { version = "2.0.1", features = ["display"] }
pin-project = "1"
# Utility dependencies
itertools = "0.14"
thiserror = "2"
internment = "0.8"
recursion = "0.5"
regex = "1.11"
once_cell = "1.21"
thread_local = "1.1"
bon = "3.4"
generativity = "1.1"
anyhow = "1.0"
keccak-const = "0.2"
# Functional generics/lenses frameworks
frunk_core = "0.4"
frunk = "0.4"
frunk_utils = "0.2"
frunk-enum-core = "0.3"
# Async dependencies
tokio = "1.46"
futures = "0.3"
futures-util = "0.3"
futures-timer = "3.0"
# Data structures
either = "1.15"
ordered-float = "5.0"
ahash = "0.8"
# Tracing/logging
log = "0.4"
# networking
libp2p = "0.56"
libp2p-tcp = "0.44"
[workspace.lints.rust]
static_mut_refs = "warn" # Or use "warn" instead of deny
incomplete_features = "allow"
# Clippy's lint category level configurations;
# every member crate needs to inherit these by adding
#
# ```toml
# [lints]
# workspace = true
# ```
#
# to their `Cargo.toml` files
[workspace.lints.clippy]
# Clippy lint categories meant to be enabled all at once
correctness = { level = "deny", priority = -1 }
suspicious = { level = "warn", priority = -1 }
style = { level = "warn", priority = -1 }
complexity = { level = "warn", priority = -1 }
perf = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }
nursery = { level = "warn", priority = -1 }
cargo = { level = "warn", priority = -1 }
# Individual Clippy lints from the `restriction` category
arithmetic_side_effects = "warn"
as_conversions = "warn"
assertions_on_result_states = "warn"
clone_on_ref_ptr = "warn"
decimal_literal_representation = "warn"
default_union_representation = "warn"
deref_by_slicing = "warn"
disallowed_script_idents = "deny"
else_if_without_else = "warn"
empty_enum_variants_with_brackets = "warn"
empty_structs_with_brackets = "warn"
error_impl_error = "warn"
exit = "deny"
expect_used = "warn"
float_cmp_const = "warn"
get_unwrap = "warn"
if_then_some_else_none = "warn"
impl_trait_in_params = "warn"
indexing_slicing = "warn"
infinite_loop = "warn"
let_underscore_must_use = "warn"
let_underscore_untyped = "warn"
lossy_float_literal = "warn"
mem_forget = "warn"
missing_inline_in_public_items = "warn"
multiple_inherent_impl = "warn"
multiple_unsafe_ops_per_block = "warn"
mutex_atomic = "warn"
non_zero_suggestions = "warn"
panic = "warn"
partial_pub_fields = "warn"
pattern_type_mismatch = "warn"
pub_without_shorthand = "warn"
rc_buffer = "warn"
rc_mutex = "warn"
redundant_type_annotations = "warn"
renamed_function_params = "warn"
rest_pat_in_fully_bound_structs = "warn"
same_name_method = "warn"
self_named_module_files = "deny"
semicolon_inside_block = "warn"
shadow_same = "warn"
shadow_unrelated = "warn"
str_to_string = "warn"
string_add = "warn"
string_lit_chars_any = "warn"
string_to_string = "warn"
tests_outside_test_module = "warn"
todo = "warn"
try_err = "warn"
undocumented_unsafe_blocks = "warn"
unnecessary_safety_comment = "warn"
unnecessary_safety_doc = "warn"
unneeded_field_pattern = "warn"
unseparated_literal_suffix = "warn"
unused_result_ok = "warn"
unused_trait_names = "warn"
unwrap_used = "warn"
verbose_file_reads = "warn"

875
LICENSE
View File

@@ -1,675 +1,202 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 Exo Technologies Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

38
PLATFORMS.md Normal file
View File

@@ -0,0 +1,38 @@
# EXO Platform support (partial roadmap)
## Tier 1 support - tested and maintained
Apple Silicon MacOS
- Mac Studio: M3 Ultra
- Mac Mini: M4 Pro
- Macbook Pro: M5, M4 Max
## Tier 2 support - checked occasionally, should run without crashing
## Tier 3 support - minimal support and testing, but no theoretical reason it shouldnt work
# Planned
## Tier 1
Linux CUDA Support
- Nvidia DGX Spark
Linux CPU Support
## Tier 2
Linux Vulkan Support -- depends heavily on ecosystem
- Framework Desktop
Linux CUDA Support -- depends heavily on ecosystem
- Framework Desktop
## Longer term!
Windows CUDA Support
Windows CPU Support

347
README.md
View File

@@ -1,270 +1,223 @@
<div align="center">
<picture>
<source media="(prefers-color-scheme: light)" srcset="/docs/exo-logo-black-bg.jpg">
<img alt="exo logo" src="/docs/exo-logo-transparent.png" width="50%" height="50%">
<source media="(prefers-color-scheme: light)" srcset="/docs/imgs/exo-logo-black-bg.jpg">
<img alt="exo logo" src="/docs/imgs/exo-logo-transparent.png" width="50%" height="50%">
</picture>
exo: Run your own AI cluster at home with everyday devices. Maintained by [exo labs](https://x.com/exolabs).
<h3>
[Discord](https://discord.gg/EUnjGpsmWw) | [Telegram](https://t.me/+Kh-KqHTzFYg3MGNk) | [X](https://x.com/exolabs)
</h3>
[![GitHub Repo stars](https://img.shields.io/github/stars/exo-explore/exo)](https://github.com/exo-explore/exo/stargazers)
[![Tests](https://dl.circleci.com/status-badge/img/circleci/TrkofJDoGzdQAeL6yVHKsg/4i5hJuafuwZYZQxbRAWS71/tree/main.svg?style=svg)](https://dl.circleci.com/status-badge/redirect/circleci/TrkofJDoGzdQAeL6yVHKsg/4i5hJuafuwZYZQxbRAWS71/tree/main)
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
<a href="https://trendshift.io/repositories/11849" target="_blank"><img src="https://trendshift.io/api/badge/repositories/11849" alt="exo-explore%2Fexo | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
<p align="center">
<a href="https://discord.gg/72NsF6ux" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/Discord-Join%20Server-5865F2?logo=discord&logoColor=white" alt="Discord"></a>
<a href="https://x.com/exolabs" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/twitter/follow/exolabs?style=social" alt="X"></a>
<a href="https://www.apache.org/licenses/LICENSE-2.0.html" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/License-Apache2.0-blue.svg" alt="License: Apache-2.0"></a>
</p>
</div>
---
Forget expensive NVIDIA GPUs, unify your existing devices into one powerful GPU: iPhone, iPad, Android, Mac, Linux, pretty much any device!
<div align="center">
<h2>Update: exo is hiring. See <a href="https://exolabs.net">here</a> for more details.</h2>
</div>
## Get Involved
exo is **experimental** software. Expect bugs early on. Create issues so they can be fixed. The [exo labs](https://x.com/exolabs) team will strive to resolve issues quickly.
We also welcome contributions from the community. We have a list of bounties in [this sheet](https://docs.google.com/spreadsheets/d/1cTCpTIp48UnnIvHeLEUNg1iMy_Q6lRybgECSFCoVJpE/edit?usp=sharing).
exo connects all your devices into an AI cluster. Not only does exo enable running models larger than would fit on a single device, but with [day-0 support for RDMA over Thunderbolt](https://x.com/exolabs/status/2001817749744476256?s=20), makes models run faster as you add more devices.
## Features
### Wide Model Support
- **Automatic Device Discovery**: Devices running exo automatically discover each other - no manual configuration.
- **RDMA over Thunderbolt**: exo ships with [day-0 support for RDMA over Thunderbolt 5](https://x.com/exolabs/status/2001817749744476256?s=20), enabling 99% reduction in latency between devices.
- **Topology-Aware Auto Parallel**: exo figures out the best way to split your model across all available devices based on a realtime view of your device topology. It takes into account device resources and network latency/bandwidth between each link.
- **Tensor Parallelism**: exo supports sharding models, for up to 1.8x speedup on 2 devices and 3.2x speedup on 4 devices.
- **MLX Support**: exo uses [MLX](https://github.com/ml-explore/mlx) as an inference backend and [MLX distributed](https://ml-explore.github.io/mlx/build/html/usage/distributed.html) for distributed communication.
exo supports different models including LLaMA ([MLX](exo/inference/mlx/models/llama.py) and [tinygrad](exo/inference/tinygrad/models/llama.py)), Mistral, LlaVA, Qwen, and Deepseek.
## Benchmarks
### Dynamic Model Partitioning
<details>
<summary>Qwen3-235B (8-bit) on 4 × M3 Ultra Mac Studio with Tensor Parallel RDMA</summary>
<img src="docs/benchmarks/jeffgeerling/mac-studio-cluster-ai-full-1-qwen3-235b.jpeg" alt="Benchmark - Qwen3-235B (8-bit) on 4 × M3 Ultra Mac Studio with Tensor Parallel RDMA" width="80%" />
<p>
<strong>Source:</strong> <a href="https://www.jeffgeerling.com/blog/2025/15-tb-vram-on-mac-studio-rdma-over-thunderbolt-5">Jeff Geerling: 15 TB VRAM on Mac Studio RDMA over Thunderbolt5</a>
</p>
</details>
exo [optimally splits up models](exo/topology/ring_memory_weighted_partitioning_strategy.py) based on the current network topology and device resources available. This enables you to run larger models than you would be able to on any single device.
<details>
<summary>DeepSeek v3.1 671B (8-bit) on 4 × M3 Ultra Mac Studio with Tensor Parallel RDMA</summary>
<img src="docs/benchmarks/jeffgeerling/mac-studio-cluster-ai-full-2-deepseek-3.1-671b.jpeg" alt="Benchmark - DeepSeek v3.1 671B (8-bit) on 4 × M3 Ultra Mac Studio with Tensor Parallel RDMA" width="80%" />
<p>
<strong>Source:</strong> <a href="https://www.jeffgeerling.com/blog/2025/15-tb-vram-on-mac-studio-rdma-over-thunderbolt-5">Jeff Geerling: 15 TB VRAM on Mac Studio RDMA over Thunderbolt5</a>
</p>
</details>
### Automatic Device Discovery
<details>
<summary>Kimi K2 Thinking (native 4-bit) on 4 × M3 Ultra Mac Studio with Tensor Parallel RDMA</summary>
<img src="docs/benchmarks/jeffgeerling/mac-studio-cluster-ai-full-3-kimi-k2-thinking.jpeg" alt="Benchmark - Kimi K2 Thinking (native 4-bit) on 4 × M3 Ultra Mac Studio with Tensor Parallel RDMA" width="80%" />
<p>
<strong>Source:</strong> <a href="https://www.jeffgeerling.com/blog/2025/15-tb-vram-on-mac-studio-rdma-over-thunderbolt-5">Jeff Geerling: 15 TB VRAM on Mac Studio RDMA over Thunderbolt5</a>
</p>
</details>
exo will [automatically discover](https://github.com/exo-explore/exo/blob/945f90f676182a751d2ad7bcf20987ab7fe0181e/exo/orchestration/node.py#L154) other devices using the best method available. Zero manual configuration.
---
### ChatGPT-compatible API
## Quick Start
exo provides a [ChatGPT-compatible API](exo/api/chatgpt_api.py) for running models. It's a [one-line change](examples/chatgpt_api.sh) in your application to run models on your own hardware using exo.
Devices running exo automatically discover each other, without needing any manual configuration. Each device provides an API and a dashboard for interacting with your cluster (runs at `http://localhost:52415`).
### Device Equality
There are two ways to run exo:
Unlike other distributed inference frameworks, exo does not use a master-worker architecture. Instead, exo devices [connect p2p](https://github.com/exo-explore/exo/blob/945f90f676182a751d2ad7bcf20987ab7fe0181e/exo/orchestration/node.py#L161). As long as a device is connected somewhere in the network, it can be used to run models.
### Run from Source (Mac & Linux)
Exo supports different [partitioning strategies](exo/topology/partitioning_strategy.py) to split up a model across devices. The default partitioning strategy is [ring memory weighted partitioning](exo/topology/ring_memory_weighted_partitioning_strategy.py). This runs an inference in a ring where each device runs a number of model layers proportional to the memory of the device.
**Prerequisites:**
- [brew](https://github.com/Homebrew/brew) (for simple package management on MacOS)
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
- [uv](https://github.com/astral-sh/uv) (for Python dependency management)
- [macmon](https://github.com/vladkens/macmon) (for hardware monitoring on Apple Silicon)
- [node](https://github.com/nodejs/node) (for building the dashboard)
```bash
brew install uv macmon node
```
- [rust](https://github.com/rust-lang/rustup) (to build Rust bindings, nightly for now)
!["A screenshot of exo running 5 nodes](docs/exo-screenshot.png)
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustup toolchain install nightly
```
## Installation
Clone the repo, build the dashboard, and run exo:
The current recommended way to install exo is from source.
```bash
# Clone exo
git clone https://github.com/exo-explore/exo
### Prerequisites
# Build dashboard
cd exo/dashboard && npm install && npm run build && cd ..
- Python>=3.12.0 is required because of [issues with asyncio](https://github.com/exo-explore/exo/issues/5) in previous versions.
- For Linux with NVIDIA GPU support (Linux-only, skip if not using Linux or NVIDIA):
- NVIDIA driver - verify with `nvidia-smi`
- CUDA toolkit - install from [NVIDIA CUDA guide](https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#cuda-cross-platform-installation), verify with `nvcc --version`
- cuDNN library - download from [NVIDIA cuDNN page](https://developer.nvidia.com/cudnn-downloads), verify installation by following [these steps](https://docs.nvidia.com/deeplearning/cudnn/latest/installation/linux.html#verifying-the-install-on-linux:~:text=at%20a%20time.-,Verifying%20the%20Install%20on%20Linux,Test%20passed!,-Upgrading%20From%20Older)
### Hardware Requirements
- The only requirement to run exo is to have enough memory across all your devices to fit the entire model into memory. For example, if you are running llama 3.1 8B (fp16), you need 16GB of memory across all devices. Any of the following configurations would work since they each have more than 16GB of memory in total:
- 2 x 8GB M3 MacBook Airs
- 1 x 16GB NVIDIA RTX 4070 Ti Laptop
- 2 x Raspberry Pi 400 with 4GB of RAM each (running on CPU) + 1 x 8GB Mac Mini
- exo is designed to run on devices with heterogeneous capabilities. For example, you can have some devices with powerful GPUs and others with integrated GPUs or even CPUs. Adding less capable devices will slow down individual inference latency but will increase the overall throughput of the cluster.
### From source
```sh
git clone https://github.com/exo-explore/exo.git
cd exo
pip install -e .
# alternatively, with venv
source install.sh
# Run exo
uv run exo
```
This starts the exo dashboard and API at http://localhost:52415/
### Troubleshooting
### macOS App
- If running on Mac, MLX has an [install guide](https://ml-explore.github.io/mlx/build/html/install.html) with troubleshooting steps.
exo ships a macOS app that runs in the background on your Mac.
### Performance
<img src="docs/imgs/macos-app-one-macbook.png" alt="exo macOS App - running on a MacBook" width="35%" />
- There are a number of things users have empirically found to improve performance on Apple Silicon Macs:
The macOS app requires macOS Tahoe 26.2 or later.
1. Upgrade to the latest version of macOS Sequoia.
2. Run `./configure_mlx.sh`. This runs commands to optimize GPU memory allocation on Apple Silicon Macs.
Download the latest build here: [EXO-latest.dmg](https://assets.exolabs.net/EXO-latest.dmg).
The app will ask for permission to modify system settings and install a new Network profile. Improvements to this are being worked on.
## Documentation
---
### Example Usage on Multiple macOS Devices
### Using the API
#### Device 1:
If you prefer to interact with exo via the API, here is an example creating an instance of a small model (`mlx-community/Llama-3.2-1B-Instruct-4bit`), sending a chat completions request and deleting the instance.
```sh
exo
---
**1. Preview instance placements**
The `/instance/previews` endpoint will preview all valid placements for your model.
```bash
curl "http://localhost:52415/instance/previews?model_id=llama-3.2-1b"
```
#### Device 2:
```sh
exo
Sample response:
```json
{
"previews": [
{
"model_id": "mlx-community/Llama-3.2-1B-Instruct-4bit",
"sharding": "Pipeline",
"instance_meta": "MlxRing",
"instance": {...},
"memory_delta_by_node": {"local": 729808896},
"error": null
}
// ...possibly more placements...
]
}
```
That's it! No configuration required - exo will automatically discover the other device(s).
This will return all valid placements for this model. Pick a placement that you like.
To pick the first one, pipe into `jq`:
exo starts a ChatGPT-like WebUI (powered by [tinygrad tinychat](https://github.com/tinygrad/tinygrad/tree/master/examples/tinychat)) on http://localhost:52415
```bash
curl "http://localhost:52415/instance/previews?model_id=llama-3.2-1b" | jq -c '.previews[] | select(.error == null) | .instance' | head -n1
```
For developers, exo also starts a ChatGPT-compatible API endpoint on http://localhost:52415/v1/chat/completions. Examples with curl:
---
#### Llama 3.2 3B:
**2. Create a model instance**
```sh
curl http://localhost:52415/v1/chat/completions \
-H "Content-Type: application/json" \
Send a POST to `/instance` with your desired placement in the `instance` field (the full payload must match types as in `CreateInstanceParams`), which you can copy from step 1:
```bash
curl -X POST http://localhost:52415/instance \
-H 'Content-Type: application/json' \
-d '{
"model": "llama-3.2-3b",
"messages": [{"role": "user", "content": "What is the meaning of exo?"}],
"temperature": 0.7
}'
"instance": {...}
}'
```
#### Llama 3.1 405B:
```sh
curl http://localhost:52415/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "llama-3.1-405b",
"messages": [{"role": "user", "content": "What is the meaning of exo?"}],
"temperature": 0.7
}'
Sample response:
```json
{
"message": "Command received.",
"command_id": "e9d1a8ab-...."
}
```
#### Llava 1.5 7B (Vision Language Model):
---
```sh
curl http://localhost:52415/v1/chat/completions \
-H "Content-Type: application/json" \
**3. Send a chat completion**
Now, make a POST to `/v1/chat/completions` (the same format as OpenAI's API):
```bash
curl -N -X POST http://localhost:52415/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{
"model": "llava-1.5-7b-hf",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What are these?"
},
{
"type": "image_url",
"image_url": {
"url": "http://images.cocodataset.org/val2017/000000039769.jpg"
}
}
]
}
"model": "mlx-community/Llama-3.2-1B-Instruct-4bit",
"messages": [
{"role": "user", "content": "What is Llama 3.2 1B?"}
],
"temperature": 0.0
}'
"stream": true
}'
```
### Example Usage on Multiple Heterogenous Devices (macOS + Linux)
---
#### Device 1 (macOS):
**4. Delete the instance**
```sh
exo
When you're done, delete the instance by its ID (find it via `/state` or `/instance` endpoints):
```bash
curl -X DELETE http://localhost:52415/instance/YOUR_INSTANCE_ID
```
Note: We don't need to explicitly tell exo to use the **tinygrad** inference engine. **MLX** and **tinygrad** are interoperable!
**Other useful API endpoints*:**
#### Device 2 (Linux):
```sh
exo
```
- List all models: `curl http://localhost:52415/models`
- Inspect instance IDs and deployment state: `curl http://localhost:52415/state`
Linux devices will automatically default to using the **tinygrad** inference engine.
For further details, see API types and endpoints in [src/exo/master/api.py](src/exo/master/api.py).
You can read about tinygrad-specific env vars [here](https://docs.tinygrad.org/env_vars/). For example, you can configure tinygrad to use the cpu by specifying `CLANG=1`.
---
### Example Usage on a single device with "exo run" command
## Hardware Accelerator Support
```sh
exo run llama-3.2-3b
```
On macOS, exo uses the GPU. On Linux, exo currently runs on CPU. We are working on extending hardware accelerator support. If you'd like support for a new hardware platform, please [search for an existing feature request](https://github.com/exo-explore/exo/issues) and add a thumbs up so we know what hardware is important to the community.
With a custom prompt:
---
```sh
exo run llama-3.2-3b --prompt "What is the meaning of exo?"
```
## Contributing
### Model Storage
Models by default are stored in `~/.cache/huggingface/hub`.
You can set a different model storage location by setting the `HF_HOME` env var.
## Debugging
Enable debug logs with the DEBUG environment variable (0-9).
```sh
DEBUG=9 exo
```
For the **tinygrad** inference engine specifically, there is a separate DEBUG flag `TINYGRAD_DEBUG` that can be used to enable debug logs (1-6).
```sh
TINYGRAD_DEBUG=2 exo
```
## Formatting
We use [yapf](https://github.com/google/yapf) to format the code. To format the code, first install the formatting requirements:
```sh
pip3 install -e '.[formatting]'
```
Then run the formatting script:
```sh
python3 format.py ./exo
```
## Known Issues
- On certain versions of Python on macOS, certificates may not installed correctly, potentially causing SSL errors (e.g., when accessing huggingface.co). To resolve this, run the `Install Certificates` command, typicall as follows:
```sh
/Applications/Python 3.x/Install Certificates.command
```
- 🚧 As the library is evolving so quickly, the iOS implementation has fallen behind Python. We have decided for now not to put out the buggy iOS version and receive a bunch of GitHub issues for outdated code. We are working on solving this properly and will make an announcement when it's ready. If you would like access to the iOS implementation now, please email alex@exolabs.net with your GitHub username explaining your use-case and you will be granted access on GitHub.
## Inference Engines
exo supports the following inference engines:
- ✅ [MLX](exo/inference/mlx/sharded_inference_engine.py)
- ✅ [tinygrad](exo/inference/tinygrad/inference.py)
- 🚧 [PyTorch](https://github.com/exo-explore/exo/pull/139)
- 🚧 [llama.cpp](https://github.com/exo-explore/exo/issues/167)
## Networking Modules
- ✅ [GRPC](exo/networking/grpc)
- 🚧 [Radio](TODO)
- 🚧 [Bluetooth](TODO)
See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to contribute to exo.

84
RULES.md Normal file
View File

@@ -0,0 +1,84 @@
# Repository Rules
* if you see any code that violates these rules, raise it with me directly rather than trying to fix.
* where applicable, file a GitHub Issue.
* adhere to these rules strictly.
## General Rules
* if its possible to eliminate an extra try-catch or if-statement at runtime using type-level discipline, do it!
* name your types, functions, and classes appropriately.
* no three-letter acronyms.
* no non-standard contractions.
* each data type has a meaning, pick a name which is accurate and descriptive.
* the average layman should be able to easily understand what your function does using the function signature alone!
* sometimes, there will be exceptions. eg, when you're using specific technical terms that are well understood (saga, event, etc).
* usually, you'll think that your code is an exception to the rules, but it won't be.
## State, Functions and Classes
* every function, given the same inputs, should produce the same outputs. ie, no hidden state.
* use classes to prevent fixed state from being mutated arbitrarily (unsafely); methods provide a safe way of interfacing with state.
* if your logic doesn't mutate fixed state, it probably belongs in a standalone function rather than a class.
* functions shouldn't usually produce side-effects (they should be computationally pure).
* if, for example, you're updating a state using an event (computationally pure), and you want to trigger a saga (computational side-effect), store the logic for triggering the saga into an effect handler (a function, capable of producing side-effects, that you pass into an otherwise computationally pure function, so that it may trigger side-effects safely).
## Pydantic
* read the Pydantic docs.
* respect the Pydantic docs.
* pydantic is all you need.
* declare and re-use a central `ConfigDict` for your use-case, you'll usually want `frozen` and `strict` to be `True`.
## Unique ID (UUID) Generation
* inherit from Pydantic's `UUID4` class to create your own UUID class.
* use `uuid.uuid4()` to initialize your class with a fresh UUID where possible.
* ensure that idempotency tags are generated by taking the salted hash of persisted state.
* rationale: if a node crashes and resumes from an older state, it should not accidentally re-publish the same event twice under different idempotency tags.
* every distinct function should feature a unique salt, so that there are no accidental collisions in idempotency tags.
## Type Wrappers
* reuse types that already exist in the Python standard library.
* when two distinct data types are structurally identical (for example, different IDs which are both UUIDs but shouldn't never mixed up), make sure they can't be conflated by the type system.
* if you're working with a primitive data type (`str`, `int`, etc), use `NewType` (it has zero runtime overhead).
* if you're working with serializable data objects, consider adding a field (type `str`) that states its type.
## Type Discipline
* do not bypass the type-checker, preserve strict typing by any means necessary.
* by default, use literal types (like `Literal['one', 'two']`) where an enum seems appropriate.
pro-tip: Python's type system is quite complex and feature-rich, so reading the documentation is often advisable; Matt discovered that Python `typing` library allows you to check that you've implemented a `match` exhaustively using `Literal` and `get_args(type)` after reading the docs.
## Use of `@final`, Freezing
* use wherever applicable.
## Error Handling
* don't try-catch for no reason.
* make sure that you always know where and when the exceptions your code produces are meant to be handled, so that it's never a nasty surprise.
* always write the rationale for your error-handling down in the docstring!
* communicate the details to your colleagues when appropriate.
## Dependencies
* don't introduce any new dependencies without asking.
* don't ask for any dependencies that aren't ubiquitous within production environments.
## Commit Messages
* use the imperative mood in the subject line.
* prefix the subject line with a change type. our change types are:
* `documentation`: documentation changes.
* `feature`: a new feature.
* `refactor`: a code change that neither fixes a bug nor adds a feature.
* `bugfix`: a bug fix.
* `chore`: routine tasks, maintenance, or tooling changes.
* `test`: adding or correcting tests.
* restrict the subject line to fifty characters or less.
* capitalize the subject line.
* do not end the subject line with a period.
* separate subject from body with a blank line.

27
TODO.md Normal file
View File

@@ -0,0 +1,27 @@
2. Currently a lot of requests from the API are timing out, but we still process those requests internally. If an API request times out, we should cancel all corresponding tasks to that API request (why process a request with nobody listening).
3. Task cancellation. When API http request gets cancelled, it should cancel corresponding task.
4. I'd like to see profiled network latency / bandwidth.
5. I'd like to see how much bandwidth each link is using.
6. We should handle the case where one machine doesn't have the model downloaded and then other machines are waiting on it. In this case we get loads of timeout errors because the others are waiting for the one that needs to download the model.
7. Solve the problem of in continuous batching when a new prompt comes in, it will block decode of the current batch until the prefill is complete.
8. We want people to be able to copy models over to a new device without ever connecting EXO to the internet. Right now EXO require internet connection once to cache some files to check if a download is complete. Instead, we should simply check if there is a non-empty model folder locally with no .partial files. This indicates it's a fully downloaded model that can be loaded.
10. More granular control over how to deploy instances.
12. Nix is great but installing it is a pain and we have ended up in a lot of cases having PATH issues or installation issues. For example, after rebooting mike it seemed to no longer have a nix installation and needed reinstalling. It has a bunch of broken symlinks left over from nix that caused ssh to fail, making it even harder to debug. We need consistent environments (perhaps MDM) so we can guarantee nix is installed properly on each machine.
13. Memory pressure instead of memory used.
14. Show the type of each connection (TB5, Ethernet, etc.) in the UI. Refer to old exo: https://github.com/exo-explore/exo/blob/56f783b38dc6b08ce606b07a5386dc40dae00330/exo/helpers.py#L251
15. Prioritise certain connection types (or by latency). TB5 > Ethernet > WiFi. Refer to old exo: https://github.com/exo-explore/exo/blob/56f783b38dc6b08ce606b07a5386dc40dae00330/exo/helpers.py#L251
16. Dynamically switch to higher priority connection when it becomes available. Probably bring back InstanceReplacedAtomically.
17. Faster model loads by streaming model from other devices in cluster.
18. Add support for specifying the type of network connection to use in a test. Depends on 15/16.
20. Add chat completion cancellations (e.g OpenWebUI has something for cancelling an ongoing request).
23. Do we need cache_limit? We went back and forth on that a lot because we thought it might be causing issues. One problem is it sets it relative to model size. So if you have multiple models loaded in it will take the most recent model size for the cache_limit. This is problematic if you launch DeepSeek -> Llama for example.
24. further openai/lmstudio api compatibility
25. Rethink retry logic
26. Task cancellation. When API http request gets cancelled, it should cancel corresponding task.
27. Log cleanup - per-module log filters and default to DEBUG log levels
Potential refactors:
2. Topology can be simplified
Random errors we've run into:

View File

@@ -0,0 +1,602 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 77;
objects = {
/* Begin PBXBuildFile section */
E0140D402ED1F909001F3171 /* exo in Resources */ = {isa = PBXBuildFile; fileRef = E0140D3F2ED1F909001F3171 /* exo */; };
E0A1B1002F5A000100000003 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = E0A1B1002F5A000100000002 /* Sparkle */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
E0140D212ED1F79B001F3171 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = E0140D072ED1F79A001F3171 /* Project object */;
proxyType = 1;
remoteGlobalIDString = E0140D0E2ED1F79A001F3171;
remoteInfo = EXO;
};
E0140D2B2ED1F79B001F3171 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = E0140D072ED1F79A001F3171 /* Project object */;
proxyType = 1;
remoteGlobalIDString = E0140D0E2ED1F79A001F3171;
remoteInfo = EXO;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
E0140D0F2ED1F79A001F3171 /* EXO.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = EXO.app; sourceTree = BUILT_PRODUCTS_DIR; };
E0140D202ED1F79B001F3171 /* EXOTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = EXOTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
E0140D2A2ED1F79B001F3171 /* EXOUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = EXOUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
E0140D3F2ED1F909001F3171 /* exo */ = {isa = PBXFileReference; lastKnownFileType = folder; name = exo; path = ../../dist/exo; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
E0140D112ED1F79A001F3171 /* EXO */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = EXO;
sourceTree = "<group>";
};
E0140D232ED1F79B001F3171 /* EXOTests */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = EXOTests;
sourceTree = "<group>";
};
E0140D2D2ED1F79B001F3171 /* EXOUITests */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = EXOUITests;
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
E0140D0C2ED1F79A001F3171 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
E0A1B1002F5A000100000003 /* Sparkle in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
E0140D1D2ED1F79B001F3171 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
E0140D272ED1F79B001F3171 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
E0140D062ED1F79A001F3171 = {
isa = PBXGroup;
children = (
E0140D3F2ED1F909001F3171 /* exo */,
E0140D112ED1F79A001F3171 /* EXO */,
E0140D232ED1F79B001F3171 /* EXOTests */,
E0140D2D2ED1F79B001F3171 /* EXOUITests */,
E0140D102ED1F79A001F3171 /* Products */,
);
sourceTree = "<group>";
};
E0140D102ED1F79A001F3171 /* Products */ = {
isa = PBXGroup;
children = (
E0140D0F2ED1F79A001F3171 /* EXO.app */,
E0140D202ED1F79B001F3171 /* EXOTests.xctest */,
E0140D2A2ED1F79B001F3171 /* EXOUITests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
E0140D0E2ED1F79A001F3171 /* EXO */ = {
isa = PBXNativeTarget;
buildConfigurationList = E0140D342ED1F79B001F3171 /* Build configuration list for PBXNativeTarget "EXO" */;
buildPhases = (
E0140D0B2ED1F79A001F3171 /* Sources */,
E0140D0C2ED1F79A001F3171 /* Frameworks */,
E0140D0D2ED1F79A001F3171 /* Resources */,
);
buildRules = (
);
dependencies = (
);
fileSystemSynchronizedGroups = (
E0140D112ED1F79A001F3171 /* EXO */,
);
name = EXO;
packageProductDependencies = (
E0A1B1002F5A000100000002 /* Sparkle */,
);
productName = EXO;
productReference = E0140D0F2ED1F79A001F3171 /* EXO.app */;
productType = "com.apple.product-type.application";
};
E0140D1F2ED1F79B001F3171 /* EXOTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = E0140D372ED1F79B001F3171 /* Build configuration list for PBXNativeTarget "EXOTests" */;
buildPhases = (
E0140D1C2ED1F79B001F3171 /* Sources */,
E0140D1D2ED1F79B001F3171 /* Frameworks */,
E0140D1E2ED1F79B001F3171 /* Resources */,
);
buildRules = (
);
dependencies = (
E0140D222ED1F79B001F3171 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
E0140D232ED1F79B001F3171 /* EXOTests */,
);
name = EXOTests;
packageProductDependencies = (
);
productName = EXOTests;
productReference = E0140D202ED1F79B001F3171 /* EXOTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
E0140D292ED1F79B001F3171 /* EXOUITests */ = {
isa = PBXNativeTarget;
buildConfigurationList = E0140D3A2ED1F79B001F3171 /* Build configuration list for PBXNativeTarget "EXOUITests" */;
buildPhases = (
E0140D262ED1F79B001F3171 /* Sources */,
E0140D272ED1F79B001F3171 /* Frameworks */,
E0140D282ED1F79B001F3171 /* Resources */,
);
buildRules = (
);
dependencies = (
E0140D2C2ED1F79B001F3171 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
E0140D2D2ED1F79B001F3171 /* EXOUITests */,
);
name = EXOUITests;
packageProductDependencies = (
);
productName = EXOUITests;
productReference = E0140D2A2ED1F79B001F3171 /* EXOUITests.xctest */;
productType = "com.apple.product-type.bundle.ui-testing";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
E0140D072ED1F79A001F3171 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1610;
LastUpgradeCheck = 1610;
TargetAttributes = {
E0140D0E2ED1F79A001F3171 = {
CreatedOnToolsVersion = 16.1;
};
E0140D1F2ED1F79B001F3171 = {
CreatedOnToolsVersion = 16.1;
TestTargetID = E0140D0E2ED1F79A001F3171;
};
E0140D292ED1F79B001F3171 = {
CreatedOnToolsVersion = 16.1;
TestTargetID = E0140D0E2ED1F79A001F3171;
};
};
};
buildConfigurationList = E0140D0A2ED1F79A001F3171 /* Build configuration list for PBXProject "EXO" */;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = E0140D062ED1F79A001F3171;
minimizedProjectReferenceProxies = 1;
packageReferences = (
E0A1B1002F5A000100000001 /* XCRemoteSwiftPackageReference "Sparkle" */,
);
preferredProjectObjectVersion = 77;
productRefGroup = E0140D102ED1F79A001F3171 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
E0140D0E2ED1F79A001F3171 /* EXO */,
E0140D1F2ED1F79B001F3171 /* EXOTests */,
E0140D292ED1F79B001F3171 /* EXOUITests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
E0140D0D2ED1F79A001F3171 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
E0140D402ED1F909001F3171 /* exo in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
E0140D1E2ED1F79B001F3171 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
E0140D282ED1F79B001F3171 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
E0140D0B2ED1F79A001F3171 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
E0140D1C2ED1F79B001F3171 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
E0140D262ED1F79B001F3171 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
E0140D222ED1F79B001F3171 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = E0140D0E2ED1F79A001F3171 /* EXO */;
targetProxy = E0140D212ED1F79B001F3171 /* PBXContainerItemProxy */;
};
E0140D2C2ED1F79B001F3171 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = E0140D0E2ED1F79A001F3171 /* EXO */;
targetProxy = E0140D2B2ED1F79B001F3171 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
E0140D322ED1F79B001F3171 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 15.1;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
E0140D332ED1F79B001F3171 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 15.1;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
};
name = Release;
};
E0140D352ED1F79B001F3171 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = EXO/EXO.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"EXO/Preview Content\"";
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = EXO/Info.plist;
INFOPLIST_KEY_LSUIElement = YES;
INFOPLIST_KEY_EXOBuildCommit = "$(EXO_BUILD_COMMIT)";
INFOPLIST_KEY_EXOBuildTag = "$(EXO_BUILD_TAG)";
INFOPLIST_KEY_NSAppleEventsUsageDescription = "EXO needs to run a signed network setup script with administrator privileges.";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
INFOPLIST_KEY_SUEnableAutomaticChecks = YES;
INFOPLIST_KEY_SUFeedURL = "$(SPARKLE_FEED_URL)";
INFOPLIST_KEY_SUPublicEDKey = "$(SPARKLE_ED25519_PUBLIC)";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MARKETING_VERSION = 1.0.1;
PRODUCT_BUNDLE_IDENTIFIER = exolabs.EXO;
PRODUCT_NAME = "$(TARGET_NAME)";
EXO_BUILD_COMMIT = local;
EXO_BUILD_TAG = dev;
SPARKLE_ED25519_PUBLIC = "";
SPARKLE_FEED_URL = "";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
E0140D362ED1F79B001F3171 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = EXO/EXO.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"EXO/Preview Content\"";
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = EXO/Info.plist;
INFOPLIST_KEY_LSUIElement = YES;
INFOPLIST_KEY_EXOBuildCommit = "$(EXO_BUILD_COMMIT)";
INFOPLIST_KEY_EXOBuildTag = "$(EXO_BUILD_TAG)";
INFOPLIST_KEY_NSAppleEventsUsageDescription = "EXO needs to run a signed network setup script with administrator privileges.";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
INFOPLIST_KEY_SUEnableAutomaticChecks = YES;
INFOPLIST_KEY_SUFeedURL = "$(SPARKLE_FEED_URL)";
INFOPLIST_KEY_SUPublicEDKey = "$(SPARKLE_ED25519_PUBLIC)";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MARKETING_VERSION = 1.0.1;
PRODUCT_BUNDLE_IDENTIFIER = exolabs.EXO;
PRODUCT_NAME = "$(TARGET_NAME)";
EXO_BUILD_COMMIT = local;
EXO_BUILD_TAG = dev;
SPARKLE_ED25519_PUBLIC = "";
SPARKLE_FEED_URL = "";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
E0140D382ED1F79B001F3171 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.1;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = exolabs.EXOTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/EXO.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/EXO";
};
name = Debug;
};
E0140D392ED1F79B001F3171 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.1;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = exolabs.EXOTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/EXO.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/EXO";
};
name = Release;
};
E0140D3B2ED1F79B001F3171 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = exolabs.EXOUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TEST_TARGET_NAME = EXO;
};
name = Debug;
};
E0140D3C2ED1F79B001F3171 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = exolabs.EXOUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TEST_TARGET_NAME = EXO;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
E0140D0A2ED1F79A001F3171 /* Build configuration list for PBXProject "EXO" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E0140D322ED1F79B001F3171 /* Debug */,
E0140D332ED1F79B001F3171 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E0140D342ED1F79B001F3171 /* Build configuration list for PBXNativeTarget "EXO" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E0140D352ED1F79B001F3171 /* Debug */,
E0140D362ED1F79B001F3171 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E0140D372ED1F79B001F3171 /* Build configuration list for PBXNativeTarget "EXOTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E0140D382ED1F79B001F3171 /* Debug */,
E0140D392ED1F79B001F3171 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E0140D3A2ED1F79B001F3171 /* Build configuration list for PBXNativeTarget "EXOUITests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E0140D3B2ED1F79B001F3171 /* Debug */,
E0140D3C2ED1F79B001F3171 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
E0A1B1002F5A000100000001 /* XCRemoteSwiftPackageReference "Sparkle" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/sparkle-project/Sparkle.git";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 2.8.1;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
E0A1B1002F5A000100000002 /* Sparkle */ = {
isa = XCSwiftPackageProductDependency;
package = E0A1B1002F5A000100000001 /* XCRemoteSwiftPackageReference "Sparkle" */;
productName = Sparkle;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = E0140D072ED1F79A001F3171 /* Project object */;
}

View File

@@ -0,0 +1,15 @@
{
"originHash" : "5751fcbe53b64441ed73aceb16987d6b3fc3ebc666cb9ec2de1f6a2d441f2515",
"pins" : [
{
"identity" : "sparkle",
"kind" : "remoteSourceControl",
"location" : "https://github.com/sparkle-project/Sparkle.git",
"state" : {
"revision" : "5581748cef2bae787496fe6d61139aebe0a451f6",
"version" : "2.8.1"
}
}
],
"version" : 3
}

View File

@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1610"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "E0140D0E2ED1F79A001F3171"
BuildableName = "EXO.app"
BlueprintName = "EXO"
ReferencedContainer = "container:EXO.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "E0140D1F2ED1F79B001F3171"
BuildableName = "EXOTests.xctest"
BlueprintName = "EXOTests"
ReferencedContainer = "container:EXO.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "E0140D292ED1F79B001F3171"
BuildableName = "EXOUITests.xctest"
BlueprintName = "EXOUITests"
ReferencedContainer = "container:EXO.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "E0140D0E2ED1F79A001F3171"
BuildableName = "EXO.app"
BlueprintName = "EXO"
ReferencedContainer = "container:EXO.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "EXO_BUG_AWS_ACCESS_KEY_ID"
value = "AKIAYEKP5EMXTOBYDGHX"
isEnabled = "YES">
</EnvironmentVariable>
<EnvironmentVariable
key = "EXO_BUG_AWS_SECRET_ACCESS_KEY"
value = "Ep5gIlUZ1o8ssTLQwmyy34yPGfTPEYQ4evE8NdPE"
isEnabled = "YES">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "E0140D0E2ED1F79A001F3171"
BuildableName = "EXO.app"
BlueprintName = "EXO"
ReferencedContainer = "container:EXO.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

Some files were not shown because too many files have changed in this diff Show More