Kernels
This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50) hide show
  1. .github/actionlint.yaml +0 -3
  2. .github/workflows/build-and-commit.yml +0 -120
  3. .github/workflows/pre-commit.yml +0 -30
  4. .github/workflows/push-to-hf.yml +0 -40
  5. .gitignore +0 -21
  6. .pre-commit-config.yaml +0 -33
  7. CLAUDE.md +0 -108
  8. README.md +4 -75
  9. build.toml +14 -24
  10. build/torch210-cxx11-cu126-x86_64-linux/adamw.py +0 -154
  11. build/torch210-cxx11-cu126-x86_64-linux/async_utils.py +0 -77
  12. build/torch210-cxx11-cu126-x86_64-linux/core.py +0 -116
  13. build/torch210-cxx11-cu126-x86_64-linux/distributed/utils.py +0 -234
  14. build/torch210-cxx11-cu126-x86_64-linux/matmul_transpose_triton.py +0 -121
  15. build/torch210-cxx11-cu126-x86_64-linux/metadata.json +0 -3
  16. build/torch210-cxx11-cu126-x86_64-linux/muon.py +0 -594
  17. build/torch210-cxx11-cu126-x86_64-linux/newton_schulz.py +0 -50
  18. build/torch210-cxx11-cu126-x86_64-linux/optimizer/__init__.py +0 -26
  19. build/torch210-cxx11-cu126-x86_64-linux/pipeline.py +0 -390
  20. build/torch210-cxx11-cu126-x86_64-linux/qk_clip.py +0 -129
  21. build/torch210-cxx11-cu128-x86_64-linux/adamw.py +0 -154
  22. build/torch210-cxx11-cu128-x86_64-linux/async_utils.py +0 -77
  23. build/torch210-cxx11-cu128-x86_64-linux/core.py +0 -116
  24. build/torch210-cxx11-cu128-x86_64-linux/distributed/utils.py +0 -234
  25. build/torch210-cxx11-cu128-x86_64-linux/matmul_transpose_triton.py +0 -121
  26. build/torch210-cxx11-cu128-x86_64-linux/metadata.json +0 -3
  27. build/torch210-cxx11-cu128-x86_64-linux/muon.py +0 -594
  28. build/torch210-cxx11-cu128-x86_64-linux/newton_schulz.py +0 -50
  29. build/torch210-cxx11-cu128-x86_64-linux/optimizer/__init__.py +0 -26
  30. build/torch210-cxx11-cu128-x86_64-linux/pipeline.py +0 -390
  31. build/torch210-cxx11-cu128-x86_64-linux/qk_clip.py +0 -129
  32. build/torch210-cxx11-cu130-x86_64-linux/adamw.py +0 -154
  33. build/torch210-cxx11-cu130-x86_64-linux/async_utils.py +0 -77
  34. build/torch210-cxx11-cu130-x86_64-linux/core.py +0 -116
  35. build/torch210-cxx11-cu130-x86_64-linux/distributed/utils.py +0 -234
  36. build/torch210-cxx11-cu130-x86_64-linux/matmul_transpose_triton.py +0 -121
  37. build/torch210-cxx11-cu130-x86_64-linux/metadata.json +0 -3
  38. build/torch210-cxx11-cu130-x86_64-linux/muon.py +0 -594
  39. build/torch210-cxx11-cu130-x86_64-linux/newton_schulz.py +0 -50
  40. build/torch210-cxx11-cu130-x86_64-linux/optimizer/__init__.py +0 -26
  41. build/torch210-cxx11-cu130-x86_64-linux/pipeline.py +0 -390
  42. build/torch210-cxx11-cu130-x86_64-linux/qk_clip.py +0 -129
  43. build/torch210-cxx11-rocm70-x86_64-linux/adamw.py +0 -154
  44. build/torch210-cxx11-rocm70-x86_64-linux/async_utils.py +0 -77
  45. build/torch210-cxx11-rocm70-x86_64-linux/core.py +0 -116
  46. build/torch210-cxx11-rocm70-x86_64-linux/distributed/utils.py +0 -234
  47. build/torch210-cxx11-rocm70-x86_64-linux/matmul_transpose_triton.py +0 -121
  48. build/torch210-cxx11-rocm70-x86_64-linux/metadata.json +0 -3
  49. build/torch210-cxx11-rocm70-x86_64-linux/muon.py +0 -594
  50. build/torch210-cxx11-rocm70-x86_64-linux/newton_schulz.py +0 -50
.github/actionlint.yaml DELETED
@@ -1,3 +0,0 @@
1
- self-hosted-runner:
2
- labels:
3
- - docker-builder-01
 
 
 
 
.github/workflows/build-and-commit.yml DELETED
@@ -1,120 +0,0 @@
1
- name: Nix build and commit
2
-
3
- on:
4
- pull_request:
5
- types: [opened, synchronize, reopened]
6
- workflow_dispatch:
7
-
8
- permissions:
9
- contents: write
10
-
11
- jobs:
12
- check-commit:
13
- runs-on: ubuntu-latest
14
- outputs:
15
- skip: ${{ steps.check.outputs.skip }}
16
- steps:
17
- - uses: actions/checkout@v4
18
- with:
19
- fetch-depth: 0
20
- - id: check
21
- run: |
22
- if [ "${{ github.event_name }}" = "pull_request" ]; then
23
- msg=$(git log -1 --pretty=%B "${{ github.event.pull_request.head.sha }}")
24
- else
25
- msg="manual dispatch"
26
- fi
27
- echo "Commit message: $msg"
28
- if echo "$msg" | grep -q '\[skip-build\]'; then
29
- echo "skip=true" >> "$GITHUB_OUTPUT"
30
- else
31
- echo "skip=false" >> "$GITHUB_OUTPUT"
32
- fi
33
-
34
- build_and_commit:
35
- needs: check-commit
36
- if: needs.check-commit.outputs.skip == 'false'
37
- runs-on: docker-builder-01
38
- steps:
39
- - name: Show disk usage
40
- run: df -h
41
-
42
- - name: Notify build start on Slack
43
- id: slack_start
44
- run: |
45
- msg="*Build started* for \`${{ github.repository }}\`\nBranch: \`${{ github.ref_name }}\`\n<${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Workflow>"
46
- response=$(curl -s -X POST \
47
- -H "Authorization: Bearer ${{ secrets.SLACK_TOKEN }}" \
48
- -H "Content-type: application/json; charset=utf-8" \
49
- --data "{\"channel\":\"${{ secrets.SLACK_CHANNEL_ID }}\",\"text\":\"$msg\"}" \
50
- https://slack.com/api/chat.postMessage)
51
- ts=$(echo "$response" | jq -r '.ts')
52
- echo "thread_ts=$ts" >> "$GITHUB_OUTPUT"
53
- echo "$response"
54
-
55
- - name: Checkout repository
56
- uses: actions/checkout@v4
57
- with:
58
- fetch-depth: 0
59
- lfs: true
60
- ref: ${{ github.head_ref || github.ref }}
61
-
62
- - name: Install Nix
63
- uses: cachix/install-nix-action@v31
64
-
65
- - name: Setup huggingface cachix
66
- uses: cachix/cachix-action@v15
67
- with:
68
- name: huggingface
69
-
70
- - name: Clean build directory
71
- run: |
72
- rm -rf build
73
-
74
- - name: Build with Nix
75
- run: |
76
- nix run .#build-and-copy \
77
- --override-input kernel-builder github:huggingface/kernel-builder \
78
- --max-jobs 8 \
79
- -j 8 \
80
- -L
81
-
82
- - name: List built binaries
83
- run: |
84
- ls build
85
-
86
- - name: Commit build artifact
87
- run: |
88
- git config user.name "github-actions[bot]"
89
- git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
90
- git add build/*
91
- git commit -m "Add built binary [skip-build]"
92
-
93
- - name: Push changes
94
- run: |
95
- git push origin HEAD:"$HEAD_REF"
96
- env:
97
- HEAD_REF: ${{ github.head_ref || github.ref }}
98
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
99
-
100
- - name: Notify success on Slack (thread)
101
- if: success()
102
- run: |
103
- ts="${{ steps.slack_start.outputs.thread_ts }}"
104
- msg="*Build succeeded* for \`${{ github.repository }}\`\nBranch: \`${{ github.ref_name }}\`\n<${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Workflow>"
105
- curl -s -X POST \
106
- -H "Authorization: Bearer ${{ secrets.SLACK_TOKEN }}" \
107
- -H "Content-type: application/json; charset=utf-8" \
108
- --data "{\"channel\":\"${{ secrets.SLACK_CHANNEL_ID }}\",\"text\":\"$msg\",\"thread_ts\":\"$ts\"}" \
109
- https://slack.com/api/chat.postMessage
110
-
111
- - name: Notify failure on Slack (thread)
112
- if: failure()
113
- run: |
114
- ts="${{ steps.slack_start.outputs.thread_ts }}"
115
- msg="*Build failed* for \`${{ github.repository }}\`\nBranch: \`${{ github.ref_name }}\`\n<${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Workflow>"
116
- curl -s -X POST \
117
- -H "Authorization: Bearer ${{ secrets.SLACK_TOKEN }}" \
118
- -H "Content-type: application/json; charset=utf-8" \
119
- --data "{\"channel\":\"${{ secrets.SLACK_CHANNEL_ID }}\",\"text\":\"$msg\",\"thread_ts\":\"$ts\"}" \
120
- https://slack.com/api/chat.postMessage
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.github/workflows/pre-commit.yml DELETED
@@ -1,30 +0,0 @@
1
- name: pre-commit
2
-
3
- on:
4
- pull_request:
5
- push:
6
- branches: [ main, master ]
7
-
8
- jobs:
9
- run-pre-commit:
10
- runs-on: ubuntu-latest
11
- permissions:
12
- contents: read
13
- pull-requests: read
14
- steps:
15
- - uses: actions/checkout@v4
16
-
17
- - uses: actions/setup-python@v5
18
- with:
19
- python-version: "3.11"
20
-
21
- - name: Cache pre-commit
22
- uses: actions/cache@v4
23
- with:
24
- path: ~/.cache/pre-commit
25
- key: pre-commit-${{ runner.os }}-${{ hashFiles('.pre-commit-config.yaml') }}
26
- restore-keys: |
27
- pre-commit-${{ runner.os }}-
28
-
29
- - name: Run pre-commit
30
- uses: pre-commit/action@v3.0.1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.github/workflows/push-to-hf.yml DELETED
@@ -1,40 +0,0 @@
1
- name: Push to HF Repo
2
-
3
- on:
4
- push:
5
- branches:
6
- - main
7
- workflow_dispatch:
8
-
9
- jobs:
10
- push_to_hf:
11
- runs-on: ubuntu-latest
12
- steps:
13
- # 1. Checkout the repo
14
- - name: Checkout repository
15
- uses: actions/checkout@v4
16
- with:
17
- fetch-depth: 0
18
- - name: Install Git LFS
19
- run: |
20
- git lfs install
21
- git lfs fetch --all
22
- git lfs pull
23
- # 2. Set up Git
24
- - name: Configure Git
25
- run: |
26
- git config user.name "MotifTech"
27
- git config user.email "huggingface@motiftech.io"
28
-
29
- # 3. Add HF remote
30
- - name: Add Hugging Face remote
31
- run: |
32
- git remote add hf https://huggingface.co/Motif-Technologies/optimizer
33
- git fetch hf || true
34
-
35
- # 4. Push to HF repo
36
- - name: Push to Hugging Face
37
- env:
38
- HF_TOKEN: ${{ secrets.HF_TOKEN }}
39
- run: |
40
- git push "https://hf_token:${HF_TOKEN}@huggingface.co/Motif-Technologies/optimizer" HEAD:main
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore DELETED
@@ -1,21 +0,0 @@
1
- __pycache__
2
- .idea
3
- .DS_Store
4
- *.egg-info
5
- outputs
6
- dist/*
7
- .vscode
8
-
9
- # data
10
- data
11
- out
12
- wandb
13
-
14
- torchtitan/datasets/**/*.model
15
- torchtitan/experiments/flux/assets/*
16
-
17
- # temp files
18
- *.log
19
- error.json
20
- _remote_module_non_scriptable.py
21
- .git_disabled/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.pre-commit-config.yaml DELETED
@@ -1,33 +0,0 @@
1
- default_install_hook_types:
2
- - pre-commit
3
- - commit-msg
4
- default_stages:
5
- - pre-commit # Run locally
6
- - manual # Run in CI
7
- exclude: '(build|result)/.*|__pycache__/.*|.*\.(png|html)$'
8
- repos:
9
- - repo: https://github.com/google/yapf
10
- rev: v0.43.0
11
- hooks:
12
- - id: yapf
13
- args: [--in-place, --verbose]
14
- - repo: https://github.com/crate-ci/typos
15
- rev: v1.34.0
16
- hooks:
17
- - id: typos
18
- exclude: '.gitattributes'
19
- - repo: https://github.com/PyCQA/isort
20
- rev: 6.0.1
21
- hooks:
22
- - id: isort
23
- - repo: https://github.com/pre-commit/mirrors-clang-format
24
- rev: v20.1.3
25
- hooks:
26
- - id: clang-format
27
- types_or: [c++, cuda]
28
- args: [--style=file, --verbose]
29
- - repo: https://github.com/jackdewinter/pymarkdown
30
- rev: v0.9.29
31
- hooks:
32
- - id: pymarkdown
33
- args: [fix]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
CLAUDE.md DELETED
@@ -1,108 +0,0 @@
1
- # CLAUDE.md
2
-
3
- This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
-
5
- ## Project Overview
6
-
7
- Optimizer is a PyTorch package implementing the **Muon optimizer** with support for N-D sharding parallelism for large-scale distributed training. Based on the paper at https://arxiv.org/abs/2511.07464. It supports general N-D sharding configurations (FSDP2 through hybrid setups like 2 TP + 2 DP-Replicate + 2 DP-Shard).
8
-
9
- ## Commands
10
-
11
- ### Lint & Format
12
-
13
- ```bash
14
- pre-commit run --all-files # Run all pre-commit hooks
15
- pre-commit run isort --all-files # Run a specific hook (e.g., isort)
16
- ```
17
-
18
- Hooks: yapf (Python formatter), isort (import sorter), typos (spell checker), clang-format (C++/CUDA), pymarkdown (Markdown linter), actionlint (GitHub Actions).
19
-
20
- ### Tests
21
-
22
- Tests require **8 GPUs**, access to `Motif-Technologies/Motif-2.6B-4layer-random` on HuggingFace (`HF_TOKEN` env var), and PyTorch >= 2.8.0.
23
-
24
- ```bash
25
- cd test && ./run_test.sh
26
- # Equivalent to:
27
- cd test && torchrun --nproc-per-node=8 --local-ranks-filter=0 -m pytest test_muon.py
28
- ```
29
-
30
- Useful pytest flags: `--measure-perf` (timing/memory), `--do-profile` (profiling, requires `--measure-perf`), `--skip-verify` (skip correctness check against sequential implementation).
31
-
32
- ### Build
33
-
34
- Uses kernel-builder infrastructure (`build.toml`, `flake.nix`). Pre-built binaries for various PyTorch/CUDA/ROCm combinations are stored in `build/`.
35
-
36
- ### Commit Convention
37
-
38
- **Always append `[skip-build]` to every commit message.** This prevents CI from triggering unnecessary build jobs on development branches.
39
-
40
- ## Architecture
41
-
42
- ### Source Layout
43
-
44
- ```
45
- torch-ext/optimizer/
46
- ├── __init__.py # Public API: exports Muon
47
- ├── muon.py # Muon optimizer class (~430 lines)
48
- ├── newton_schulz.py # Newton-Schulz iteration (~50 lines)
49
- ├── qk_clip.py # QK clipping for attention heads (~130 lines)
50
- ├── core.py # Shared state, helpers, param grouping (~110 lines)
51
- ├── pipeline.py # Async generator pipeline for parallel mode (~290 lines)
52
- ├── async_utils.py # AsyncTask / AsyncRuntime scheduling (~75 lines)
53
- ├── adamw.py # Fused AdamW for non-Muon parameters (~160 lines)
54
- ├── matmul_transpose_triton.py # Triton kernel for X @ X.T (~130 lines)
55
- └── distributed/
56
- └── utils.py # Shard mesh construction, DTensor slicing (~175 lines)
57
- ```
58
-
59
- ### Optimizer Modes
60
-
61
- The `Muon` optimizer has three execution paths selected per-parameter based on its tensor type and mesh structure:
62
-
63
- 1. **Base mode** (`base()`) — Single-device / non-sharded tensors. Standard Muon with Newton-Schulz orthogonalization.
64
- 2. **Distributed mode** (`distributed_muon()`) — Gathers full tensors via all-gather, computes updates, redistributes. Used for small parameters or fallback.
65
- 3. **Parallel mode** (`parallel()`) — Pipelined all2all communication overlapped with compute. Uses an async generator pipeline scheduled by `run_pipeline()`. This is the main advanced feature.
66
-
67
- ### Parallel Mode Pipeline
68
-
69
- The parallel pipeline is implemented as a single generator function `muon_chunk_pipeline()` in `pipeline.py`. Parameters are split into chunks, and each chunk flows through:
70
-
71
- ```
72
- build bufs + async all2all_gather → yield → wait + Newton-Schulz compute + async all2all_scatter → yield → wait + update_param
73
- ```
74
-
75
- The generator yields 2 times (after launching async gather and async scatter via `async_op=True`), allowing `run_pipeline()` to interleave multiple chunks for communication overlap. `work.wait()` completes each async operation after the yield.
76
-
77
- `warmup_step` maps to `max_concurrent_tasks = warmup_step + 1` in `run_pipeline()`.
78
-
79
- For detailed implementation documentation (pipeline internals, distributed utilities, QK clipping with strided sharding, etc.), see [`docs/implementation.md`](docs/implementation.md).
80
-
81
- ### Key Abstractions
82
-
83
- - **`get_default_muon_param_groups(model, is_muon_func)`** (`core.py`) — Separates parameters into Muon-optimizable (2D+) and AdamW groups. Skips embeddings and output layers by default.
84
- - **`_muon_state` dataclass** (`core.py`) — Per-parameter config: rank ownership (`worker_rank`), process group, precomputed shard indices (`rank_indices`, `rank_numels`), and optional QK clip state. Config-only; no transient pipeline state.
85
- - **`muon_chunk_pipeline()` generator** (`pipeline.py`) — Processes one chunk through the full gather→compute→scatter→update pipeline. Uses `async_op=True` for non-blocking all-to-all and yields to allow chunk interleaving. All intermediate buffers are generator-local variables.
86
- - **`run_pipeline()`** (`async_utils.py`) — Generator-based pipeline scheduling with bounded concurrency. Interleaves multiple chunk pipelines at yield points.
87
- - **`construct_shard_mesh()` / `get_slices_of_dtensor()`** (`distributed/utils.py`) — Utilities for building shard meshes from DTensor placements and computing per-rank local slices. Handles both `Shard` and `_StridedShard` (PyTorch 2.10+).
88
- - **Newton-Schulz iteration** (`newton_schulz.py`) — `_zeropower_via_newtonschulz5()`: 5 quintic iterations in bfloat16 with pre-optimized coefficients for gradient orthogonalization. Uses Triton kernel `matmul_transpose_assign` for efficient X @ X.T.
89
- - **QK Clipping** (`qk_clip.py`) — Optional dynamic clipping of attention head projections when QK logits exceed a threshold. Configured via `q_indices`, `k_indices`, `head_dim`, `threshold`.
90
- - **Fused AdamW** (`adamw.py`) — Uses PyTorch's `torch._fused_adamw_` for non-Muon parameters, grouping tensors by device/dtype and DTensor placement.
91
-
92
- ### Dependency Graph
93
-
94
- ```
95
- matmul_transpose_triton.py (leaf)
96
-
97
- newton_schulz.py (leaf + triton)
98
-
99
- core.py ──── qk_clip.py (leaf, distributed/utils)
100
- │ │ │
101
- │ pipeline.py ─── async_utils.py
102
- │ │
103
- │ adamw.py
104
- │ │
105
- muon.py (all above)
106
-
107
- __init__.py
108
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,7 +1,6 @@
1
  ---
2
  tags:
3
- - kernels
4
- license: apache-2.0
5
  ---
6
 
7
  # Optimizer
@@ -10,14 +9,8 @@ Optimizer is a python package that provides:
10
  - PyTorch implementation of recent optimizer algorithms
11
  - with support for parallelism techniques for efficient large-scale training.
12
 
13
- ## Currently implemented
14
- - Parallel Muon with N-D sharding
15
- - [arxiv URL](https://arxiv.org/abs/2511.07464)
16
- - Supports **general N-D sharding configurations**
17
- - The implementation is not tied to any specific parallel strategy.
18
- - Verified from basic FSDP2 setups up to hybrid configurations such as
19
- **(2 TP + 2 DP-Replicate + 2 DP-Shard)**.
20
- - Verified configurations can be found in [test_muon.py](./test/test_muon.py)
21
 
22
  ## Usage
23
 
@@ -27,78 +20,14 @@ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
27
  from kernels import get_kernel
28
 
29
  optimizer = get_kernel("motif-technologies/optimizer")
30
- get_default_muon_param_groups = optimizer.muon.get_default_muon_param_groups
31
 
32
  model = None # your model here
33
  fsdp_model = FSDP(model)
34
 
35
- # muon, in nature, cannot use 1-d tensor
36
- # we provide helper function to group such tensors
37
- # you can use your own function, if necessary
38
- params = get_default_muon_param_groups(model) # user can write own is_muon_func, if necessary
39
-
40
  optim = optimizer.Muon(
41
- params,
42
  lr=0.01,
43
  momentum=0.9,
44
  weight_decay=1e-4,
45
  )
46
  ```
47
-
48
- ## Documentation
49
-
50
- - [Implementation Guide](./docs/implementation.md) — Detailed walkthrough of the internal architecture, parallel pipeline, distributed utilities, and QK clipping. Recommended for code reviewers and new contributors.
51
- - [PyTorch 2.10 TP Fix](./docs/pytorch-2.10-tp-fix.md) — Root cause analysis and fixes for `_StridedShard` compatibility with PyTorch 2.10+.
52
-
53
- ## Test
54
-
55
- - Check [test/README.md](./test/README.md) for how to run the tests.
56
-
57
- ## Pre-commit Hooks
58
-
59
- This project uses [pre-commit](https://pre-commit.com/) to automatically check and format code before commits.
60
-
61
- ### Setup
62
-
63
- 1. Install pre-commit:
64
-
65
- ```bash
66
- pip install pre-commit
67
- ```
68
-
69
- 2. Install the git hooks:
70
-
71
- ```bash
72
- pre-commit install
73
- ```
74
-
75
- Once installed, the configured hooks will run automatically on each commit.
76
-
77
- ### Included Hooks
78
-
79
- The following tools are run via pre-commit:
80
-
81
- - **[yapf](https://github.com/google/yapf)** – Python code formatter
82
- - **[typos](https://github.com/crate-ci/typos)** – Spell checker for common typos
83
- - **[isort](https://github.com/PyCQA/isort)** – Organizes and sorts Python imports
84
- - **[clang-format](https://clang.llvm.org/docs/ClangFormat.html)** – Formats C++/CUDA code (`--style=file`)
85
- - **[pymarkdown](https://github.com/jackdewinter/pymarkdown)** – Lints and auto-fixes Markdown files
86
- - **[actionlint](https://github.com/rhysd/actionlint)** – Validates GitHub Actions workflows
87
-
88
- ### Usage
89
-
90
- - Run all checks on the entire codebase:
91
-
92
- ```bash
93
- pre-commit run --all-files
94
- ```
95
-
96
- - Run a specific hook (example: isort):
97
-
98
- ```bash
99
- pre-commit run isort --all-files
100
- ```
101
-
102
- ### Test
103
-
104
- - There is a [simple unittest for Parallel Muon](./test/test_muon/README.md)
 
1
  ---
2
  tags:
3
+ - kernel
 
4
  ---
5
 
6
  # Optimizer
 
9
  - PyTorch implementation of recent optimizer algorithms
10
  - with support for parallelism techniques for efficient large-scale training.
11
 
12
+ ### Currently implemented
13
+ - [Parallel Muon with FSDP2](./docs/muon/parallel_muon.pdf)
 
 
 
 
 
 
14
 
15
  ## Usage
16
 
 
20
  from kernels import get_kernel
21
 
22
  optimizer = get_kernel("motif-technologies/optimizer")
 
23
 
24
  model = None # your model here
25
  fsdp_model = FSDP(model)
26
 
 
 
 
 
 
27
  optim = optimizer.Muon(
28
+ fsdp_model.parameters(),
29
  lr=0.01,
30
  momentum=0.9,
31
  weight_decay=1e-4,
32
  )
33
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build.toml CHANGED
@@ -1,33 +1,23 @@
1
  [general]
2
  name = "optimizer"
3
- backends = [
4
- "cuda",
5
- "rocm",
6
- ]
7
 
8
  [torch]
9
  src = [
10
- "torch-ext/torch_binding.cpp",
11
- "torch-ext/torch_binding.h",
12
  ]
13
 
14
- [kernel.optimizer]
15
- backend = "cuda"
16
- depends = ["torch"]
17
- src = ["optimizer/dummy.cu"]
18
-
19
- [kernel.optimizer_rocm]
20
  backend = "rocm"
21
- rocm-archs = [
22
- "gfx906",
23
- "gfx908",
24
- "gfx90a",
25
- "gfx940",
26
- "gfx941",
27
- "gfx942",
28
- "gfx1030",
29
- "gfx1100",
30
- "gfx1101",
31
  ]
32
- depends = ["torch"]
33
- src = ["optimizer/dummy.cu"]
 
1
  [general]
2
  name = "optimizer"
3
+ universal = false
 
 
 
4
 
5
  [torch]
6
  src = [
7
+ "torch-ext/torch_binding.cpp",
8
+ "torch-ext/torch_binding.h",
9
  ]
10
 
11
+ [kernel.activation]
 
 
 
 
 
12
  backend = "rocm"
13
+ src = [
14
+ "optimizer/dummy.cu",
15
+ ]
16
+ depends = [ "torch" ]
17
+
18
+ [kernel.activation_cuda]
19
+ backend = "cuda"
20
+ src = [
21
+ "optimizer/dummy.cu",
 
22
  ]
23
+ depends = [ "torch" ]
 
build/torch210-cxx11-cu126-x86_64-linux/adamw.py DELETED
@@ -1,154 +0,0 @@
1
- from collections import defaultdict
2
- from typing import cast
3
-
4
- import torch
5
- from torch.distributed.tensor import DTensor
6
-
7
-
8
- def fused_adamw(
9
- params: list[torch.Tensor],
10
- grads: list[torch.Tensor],
11
- exp_avgs: list[torch.Tensor],
12
- exp_avg_sqs: list[torch.Tensor],
13
- max_exp_avg_sqs: list[torch.Tensor],
14
- state_steps: list[torch.Tensor],
15
- amsgrad: bool,
16
- beta1: float,
17
- beta2: float,
18
- lr: float | torch.Tensor,
19
- weight_decay: float,
20
- eps: float,
21
- maximize: bool,
22
- ) -> None:
23
- if not params:
24
- return
25
-
26
- # We only shuffle around the lr when it is a Tensor and on CUDA, otherwise, we prefer
27
- # treating it as a scalar.
28
- lr_dict: dict | None = ({
29
- lr.device: lr
30
- } if isinstance(lr, torch.Tensor) and str(lr.device) != "cpu" else None)
31
- grouped_tensors = torch.optim.Optimizer._group_tensors_by_device_and_dtype(
32
- [params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs,
33
- state_steps] # type: ignore[list-item]
34
- )
35
- for (device, _), (
36
- (
37
- device_params_,
38
- device_grads_,
39
- device_exp_avgs_,
40
- device_exp_avg_sqs_,
41
- device_max_exp_avg_sqs,
42
- device_state_steps_,
43
- ),
44
- _,
45
- ) in grouped_tensors.items():
46
- device_params = cast(list[torch.Tensor], device_params_)
47
- device_grads = cast(list[torch.Tensor], device_grads_)
48
- device_exp_avgs = cast(list[torch.Tensor], device_exp_avgs_)
49
- device_exp_avg_sqs = cast(list[torch.Tensor], device_exp_avg_sqs_)
50
- device_state_steps = cast(list[torch.Tensor], device_state_steps_)
51
-
52
- if lr_dict is not None and device not in lr_dict:
53
- lr_dict[device] = lr.to(
54
- device=device, non_blocking=True) # type: ignore[union-attr]
55
- lr = lr_dict[device]
56
- torch._foreach_add_(device_state_steps, 1)
57
- func = torch._fused_adamw_
58
- func(
59
- device_params,
60
- device_grads,
61
- device_exp_avgs,
62
- device_exp_avg_sqs,
63
- device_max_exp_avg_sqs, # type: ignore[arg-type]
64
- device_state_steps,
65
- amsgrad=amsgrad,
66
- lr=lr, # type: ignore[arg-type]
67
- beta1=beta1,
68
- beta2=beta2,
69
- weight_decay=weight_decay,
70
- eps=eps,
71
- maximize=maximize,
72
- )
73
-
74
-
75
- def step_adamw_params(optimizer_state, params, group):
76
- """Run fused AdamW on a list of parameters sharing the same placement.
77
-
78
- Args:
79
- optimizer_state: The optimizer's state dict (self.state in Muon).
80
- params: List of parameters to update.
81
- group: Parameter group dict with lr, adamw_betas, adamw_eps, weight_decay.
82
- """
83
- params_with_grads = []
84
- grads = []
85
- moment1 = []
86
- moment2 = []
87
- max_exp_avg_sqs = []
88
- state_steps = []
89
- lr = group["lr"]
90
- beta1, beta2 = group["adamw_betas"]
91
- eps = group["adamw_eps"]
92
- weight_decay = group["weight_decay"]
93
-
94
- for p in params:
95
- g = p.grad
96
- if g is None:
97
- continue
98
- state = optimizer_state[p]
99
- params_with_grads.append(p)
100
- grads.append(g)
101
- if "step" not in state:
102
- state["step"] = (torch.zeros((),
103
- dtype=torch.float32,
104
- device=p.device))
105
- state["moment1"] = torch.zeros_like(g)
106
- state["moment2"] = torch.zeros_like(g)
107
- moment1.append(state["moment1"])
108
- moment2.append(state["moment2"])
109
- if not isinstance(state["step"], torch.Tensor):
110
- step_tensor = torch.tensor(state["step"],
111
- dtype=torch.float32,
112
- device=p.device)
113
- else:
114
- step_tensor = state["step"]
115
- state_steps.append(step_tensor)
116
-
117
- fused_adamw(
118
- params_with_grads,
119
- grads,
120
- moment1,
121
- moment2,
122
- max_exp_avg_sqs,
123
- state_steps,
124
- amsgrad=False,
125
- beta1=beta1,
126
- beta2=beta2,
127
- lr=lr,
128
- weight_decay=weight_decay,
129
- eps=eps,
130
- maximize=False,
131
- )
132
-
133
-
134
- def step_adamw(optimizer_state, group):
135
- """Dispatch AdamW step, grouping parameters by type and placement.
136
-
137
- Args:
138
- optimizer_state: The optimizer's state dict (self.state in Muon).
139
- group: Parameter group dict.
140
- """
141
- params = group["params"]
142
-
143
- # group params with its type and placement
144
- placement_to_params: dict[tuple, list[torch.Tensor]] = defaultdict(list)
145
- for p in params:
146
- match p:
147
- case DTensor():
148
- placement_to_params[tuple([p.placements,
149
- p.device_mesh])].append(p)
150
- case torch.Tensor():
151
- placement_to_params[tuple([torch.Tensor, None])].append(p)
152
-
153
- for group_params in placement_to_params.values():
154
- step_adamw_params(optimizer_state, group_params, group)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu126-x86_64-linux/async_utils.py DELETED
@@ -1,77 +0,0 @@
1
- import logging
2
- from typing import Generator
3
-
4
- logger = logging.getLogger(__name__)
5
-
6
-
7
- class _Task:
8
- """Internal: wraps a generator, advances one yield at a time."""
9
-
10
- def __init__(self, generator: Generator[None, None, None], index: int):
11
- self._generator = generator
12
- self._index = index
13
- self._steps_completed = 0
14
- self.step() # run to first yield
15
-
16
- def step(self) -> bool:
17
- try:
18
- next(self._generator)
19
- self._steps_completed += 1
20
- logger.debug("pipeline[%d] completed stage %d", self._index,
21
- self._steps_completed)
22
- return True
23
- except StopIteration:
24
- logger.debug("pipeline[%d] finished after %d stages", self._index,
25
- self._steps_completed)
26
- return False
27
-
28
- def close(self):
29
- self._generator.close()
30
-
31
-
32
- def run_pipeline(
33
- pipelines: Generator[Generator[None, None, None], None, None],
34
- max_concurrent: int,
35
- ) -> None:
36
- """Run generator-based pipelines with bounded concurrency.
37
-
38
- Each pipeline is a generator that yields at stage boundaries.
39
- The runtime interleaves pipelines so communication and computation
40
- overlap across chunks.
41
- """
42
- if max_concurrent <= 0:
43
- raise ValueError(f"max_concurrent must be > 0, got {max_concurrent}")
44
-
45
- have_new = True
46
- task_index = 0
47
- previous_tasks: list[_Task] = []
48
-
49
- try:
50
- while have_new or previous_tasks:
51
- running_tasks: list[_Task] = []
52
-
53
- # Admit one new pipeline per iteration (staggered admission).
54
- # Admitting one at a time ensures that while chunk N does NS
55
- # compute on the default stream, chunk N+1's NCCL all-to-all
56
- # runs concurrently on the NCCL stream — creating real
57
- # communication/computation overlap on the GPU.
58
- if have_new and len(previous_tasks) < max_concurrent:
59
- try:
60
- gen = next(pipelines)
61
- task = _Task(gen, task_index)
62
- task_index += 1
63
- running_tasks.append(task)
64
- except StopIteration:
65
- have_new = False
66
-
67
- # Advance every previously-yielded task by one step.
68
- for task in previous_tasks:
69
- if task.step():
70
- running_tasks.append(task)
71
-
72
- previous_tasks = running_tasks
73
- except BaseException:
74
- # Clean up all in-flight generators to release GPU resources.
75
- for task in previous_tasks:
76
- task.close()
77
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu126-x86_64-linux/core.py DELETED
@@ -1,116 +0,0 @@
1
- import math
2
- from dataclasses import dataclass
3
-
4
- import torch
5
- import torch.distributed as dist
6
- from torch.distributed import ProcessGroup
7
- from torch.distributed.tensor import DTensor
8
-
9
-
10
- @dataclass
11
- class _muon_state:
12
- worker_rank: int
13
- process_group: ProcessGroup
14
- rank_indices: dict[int, tuple] # local_rank -> per-dim indices
15
- rank_numels: dict[int, int] # local_rank -> numel
16
- name: str
17
- qk_clip_state: torch.Tensor | None = None
18
-
19
-
20
- def update_g(optimizer_state, p, g, group, momentum):
21
- """Apply momentum update to gradient.
22
-
23
- Args:
24
- optimizer_state: The optimizer's state dict (self.state in Muon).
25
- p: Parameter tensor.
26
- g: Gradient tensor.
27
- group: Parameter group dict.
28
- momentum: Momentum coefficient.
29
-
30
- Returns:
31
- Momentum-updated gradient tensor.
32
- """
33
- state = optimizer_state[p]
34
- buf = state.setdefault("momentum_buffer", torch.zeros_like(g))
35
- torch.add(g, buf, alpha=momentum, out=buf)
36
- if group["nesterov"]:
37
- g.add_(buf, alpha=momentum)
38
- return g
39
- return buf
40
-
41
-
42
- def update_p(p, u, lr, adjusted_lr, weight_decay):
43
- """Apply weight decay and orthogonalized update to parameter.
44
-
45
- Args:
46
- p: Parameter (torch.nn.Parameter or DTensor).
47
- u: Orthogonalized update tensor.
48
- lr: Base learning rate.
49
- adjusted_lr: Size-adjusted learning rate.
50
- weight_decay: Weight decay coefficient.
51
- """
52
- if isinstance(p, torch.nn.Parameter):
53
- # apply weight decay
54
- p.data.mul_(1 - lr * weight_decay)
55
- # apply update
56
- p.data.add_(u, alpha=-adjusted_lr)
57
- else:
58
- p.mul_(1 - lr * weight_decay)
59
- p.add_(u, alpha=-adjusted_lr)
60
-
61
-
62
- def adjust_lr_for_muon(lr, param_shape):
63
- """Scale learning rate based on parameter matrix dimensions.
64
-
65
- Args:
66
- lr: Base learning rate.
67
- param_shape: Shape of the parameter tensor.
68
-
69
- Returns:
70
- Adjusted learning rate.
71
- """
72
- A, B = param_shape[:2]
73
- # We adjust the learning rate and weight decay based on the size of the parameter matrix
74
- # as described in the paper
75
- adjusted_ratio = 0.2 * math.sqrt(max(A, B))
76
- adjusted_lr = lr * adjusted_ratio
77
- return adjusted_lr
78
-
79
-
80
- def default_is_muon(name, x, expert_keys=None):
81
- skip_keys = ["embed_tokens", "lm_head", "tok_embeddings", "output"]
82
- if any(key in name for key in skip_keys):
83
- return False
84
- effective_ndim = x.ndim
85
- if expert_keys and any(key in name for key in expert_keys):
86
- effective_ndim -= 1
87
- return effective_ndim >= 2
88
-
89
-
90
- def get_default_muon_param_groups(model, is_muon_func=None, expert_keys=None):
91
- if is_muon_func is None:
92
- is_muon_func = lambda n, x: default_is_muon(n, x, expert_keys)
93
-
94
- muon_params, muon_names = [], []
95
- non_muon_params = []
96
-
97
- for n, p in model.named_parameters():
98
- if not p.requires_grad:
99
- continue
100
- if is_muon_func(n, p):
101
- muon_params.append(p)
102
- muon_names.append(n)
103
- else:
104
- non_muon_params.append(p)
105
-
106
- return [
107
- {
108
- "params": muon_params,
109
- "names": muon_names,
110
- "use_muon": True,
111
- },
112
- {
113
- "params": non_muon_params,
114
- "use_muon": False,
115
- },
116
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu126-x86_64-linux/distributed/utils.py DELETED
@@ -1,234 +0,0 @@
1
- import torch
2
- import torch.distributed as dist
3
- from torch.distributed import ProcessGroup
4
- from torch.distributed.device_mesh import DeviceMesh
5
- from torch.distributed.tensor import DTensor
6
- from torch.distributed.tensor.placement_types import (Placement, Shard,
7
- _StridedShard)
8
-
9
-
10
- def _is_shard(placement: Placement) -> bool:
11
- """Check if a placement is a shard type (Shard or _StridedShard).
12
-
13
- In PyTorch 2.10+, _StridedShard no longer inherits from Shard, so
14
- ``placement.is_shard()`` returns False for _StridedShard. This helper
15
- handles both old and new hierarchies.
16
- """
17
- return isinstance(placement, (Shard, _StridedShard))
18
-
19
-
20
- def get_slices_of_dtensor(
21
- target: DTensor | torch.Tensor,
22
- local_rank: int,
23
- shard_mesh: DeviceMesh,
24
- shard_placements: tuple[Placement],
25
- ) -> tuple[slice | torch.Tensor, ...]:
26
- """
27
- Get per-dimension indices for a given rank's shard of the target tensor.
28
-
29
- Uses ``Shard.local_shard_size_and_offset`` and
30
- ``_StridedShard.local_shard_size_and_offset`` for correct handling of
31
- both contiguous and strided (non-contiguous) sharding.
32
-
33
- Args:
34
- target (DTensor | torch.Tensor): The target tensor (for its shape).
35
- local_rank (int): The local rank within the shard group.
36
- shard_mesh (DeviceMesh): The shard mesh (only shard dimensions).
37
- shard_placements (tuple[Placement]): The shard placements.
38
-
39
- Returns:
40
- A tuple of indices (one per tensor dim). Each element is either:
41
- - A ``slice`` (for contiguous or unsharded dims)
42
- - A 1-D ``torch.LongTensor`` of indices (for strided sharding)
43
- """
44
-
45
- # find the global rank of the local rank in the shard mesh
46
- rank = sorted(shard_mesh.mesh.flatten().tolist())[local_rank]
47
-
48
- rank_coords = (shard_mesh.mesh == rank).nonzero()
49
-
50
- assert len(rank_coords) == 1
51
- rank_coords = tuple(rank_coords[0].tolist())
52
-
53
- assert len(rank_coords) == len(shard_placements)
54
-
55
- # Track per-shard-dim indices.
56
- # None means "not yet sharded on this dim".
57
- dim_indices: dict[int, torch.Tensor] = {}
58
-
59
- # Caution: Assuming replicate-to-shard of the shard mesh goes with
60
- # left-to-right sharding. This is ensured by the sorting logic of
61
- # construct_shard_mesh function.
62
- for mesh_dim_idx, (rank_coord, placement) in enumerate(
63
- zip(rank_coords, shard_placements)):
64
- assert _is_shard(placement)
65
-
66
- num_chunks = shard_mesh.mesh.shape[mesh_dim_idx]
67
- shard_dim = placement.dim
68
-
69
- # Current effective size on this dim (may already be sub-sharded)
70
- if shard_dim in dim_indices:
71
- curr_size = len(dim_indices[shard_dim])
72
- else:
73
- curr_size = target.size()[shard_dim]
74
-
75
- if curr_size % num_chunks != 0:
76
- raise NotImplementedError(
77
- f"Dimension size {curr_size} is not divisible "
78
- f"by number of ranks {num_chunks} for shard "
79
- f"placement on dim {shard_dim}. (shape: {target.shape})")
80
-
81
- # Compute indices for this level of sharding
82
- if isinstance(placement, _StridedShard):
83
- _shard_size, offsets = _StridedShard.local_shard_size_and_offset(
84
- placement,
85
- curr_size,
86
- num_chunks,
87
- rank_coord,
88
- return_first_offset=False)
89
- new_indices = torch.tensor(offsets, dtype=torch.long)
90
- else:
91
- shard_size, offset = Shard.local_shard_size_and_offset(
92
- curr_size, num_chunks, rank_coord)
93
- new_indices = torch.arange(offset,
94
- offset + shard_size,
95
- dtype=torch.long)
96
-
97
- # Compose with previous indices on this dim
98
- if shard_dim in dim_indices:
99
- dim_indices[shard_dim] = dim_indices[shard_dim][new_indices]
100
- else:
101
- dim_indices[shard_dim] = new_indices
102
-
103
- # Build result tuple
104
- result: list[slice | torch.Tensor] = []
105
- for d in range(len(target.size())):
106
- if d not in dim_indices:
107
- result.append(slice(None))
108
- else:
109
- indices = dim_indices[d]
110
- # Convert contiguous indices to slice for efficiency
111
- if len(indices) > 0:
112
- start = indices[0].item()
113
- expected = torch.arange(start,
114
- start + len(indices),
115
- dtype=torch.long)
116
- if torch.equal(indices, expected):
117
- result.append(slice(start, start + len(indices)))
118
- else:
119
- result.append(indices)
120
- else:
121
- result.append(slice(0, 0))
122
-
123
- return tuple(result)
124
-
125
-
126
- _ranks_to_dist_cache: dict[tuple[int, ...], tuple[DeviceMesh,
127
- ProcessGroup]] = dict()
128
-
129
-
130
- def construct_shard_mesh(
131
- placements: tuple[Placement],
132
- mesh: DeviceMesh,
133
- ) -> tuple[DeviceMesh, ProcessGroup, tuple[Placement, ...]]:
134
- """Construct shard sub-mesh and ProcessGroup for all-to-all communication.
135
-
136
- Given a DTensor's placements and device mesh, extracts the "shard group"
137
- — the set of ranks that together hold all shards of the same replica —
138
- and creates a ProcessGroup for all-to-all among them.
139
-
140
- Steps:
141
- 1. Sort placements: Replicate first, then Shard by (dim, granularity).
142
- 2. Permute the mesh tensor to match the sorted order.
143
- 3. Collapse Replicate dims → list of shard sub-meshes (one per replica).
144
- 4. Create/retrieve a cached ProcessGroup for the current rank's sub-mesh.
145
-
146
- Example — 8 GPUs, mesh shape (2, 2, 2),
147
- placements ``[Shard(0), Replicate, _StridedShard(0)]``::
148
-
149
- Step 1 — Sort: [Replicate, _StridedShard(0), Shard(0)]
150
- Permutation: [1, 2, 0]
151
-
152
- Step 2 — Permute mesh dims by [1, 2, 0]:
153
- Original: Permuted:
154
- [[[0,1],[2,3]], [[[0,2],[1,3]],
155
- [[4,5],[6,7]]] [[4,6],[5,7]]]
156
-
157
- Step 3 — Unbind replicate dim (dim 0), giving 2 shard sub-meshes:
158
- sub-mesh 0 = [[0,2],[1,3]] (replica group 0)
159
- sub-mesh 1 = [[4,6],[5,7]] (replica group 1)
160
- shard_placements = (_StridedShard(0), Shard(0))
161
-
162
- Step 4 — Rank 0 → ProcessGroup([0,1,4,5])
163
- Rank 2 → ProcessGroup([2,3,6,7])
164
-
165
- Returns:
166
- ``(shard_mesh, process_group, shard_placements)``
167
- """
168
- my_rank = dist.get_rank()
169
- assert mesh.mesh.device.type == 'cpu'
170
-
171
- # -- Fast path: 1D all-shard mesh → reuse existing PG. ----------------
172
- # This avoids a non-collective dist.new_group() call, which would
173
- # deadlock when only a subset of ranks call this function (e.g. expert
174
- # DTensors on a TP submesh where ranks 0-3 and 4-7 call separately).
175
- if mesh.ndim == 1 and len(placements) == 1 and _is_shard(placements[0]):
176
- key = (*mesh.mesh.shape, *mesh.mesh.flatten().tolist())
177
- if key not in _ranks_to_dist_cache:
178
- _ranks_to_dist_cache[key] = (mesh, mesh.get_group())
179
- return (*_ranks_to_dist_cache[key], tuple(placements))
180
-
181
- mesh_tensor = mesh.mesh.clone()
182
-
183
- # -- Step 1: Sort placements (Replicate first, then Shard by dim). ------
184
- # _StridedShard comes BEFORE regular Shard on the same dim so that
185
- # get_slices_of_dtensor applies the outer sharding first, matching
186
- # DTensor's left-to-right (outer-to-inner) composition order.
187
- def _sort_key(item):
188
- index, placement = item
189
- assert not placement.is_partial(), "Partial placement not supported"
190
- if placement.is_replicate():
191
- return (-1, 0, index)
192
- assert _is_shard(placement), f"Unsupported: {type(placement)}"
193
- split = (-1 / placement.split_factor if isinstance(
194
- placement, _StridedShard) else 0)
195
- return (placement.dim, split, index)
196
-
197
- indexed = sorted(enumerate(placements), key=_sort_key)
198
- perm, sorted_placements = zip(*indexed)
199
-
200
- # -- Step 2: Permute mesh to match sorted placement order. --------------
201
- sorted_mesh = mesh_tensor.permute(perm)
202
-
203
- # -- Step 3: Collapse replicate dims → list of shard sub-meshes. --------
204
- # E.g. mesh (2, 3, 4, 4) with [R, R, S(0), S(1)] → 6 sub-meshes of (4, 4)
205
- num_rep = sum(1 for p in sorted_placements if p.is_replicate())
206
- if num_rep > 0:
207
- if num_rep > 1:
208
- sorted_mesh = sorted_mesh.flatten(0, num_rep - 1)
209
- shard_meshes = list(torch.unbind(sorted_mesh, dim=0))
210
- else:
211
- shard_meshes = [sorted_mesh]
212
- shard_placements = sorted_placements[num_rep:]
213
- assert len(shard_placements) == len(set(shard_placements))
214
-
215
- # -- Step 4: Create/retrieve ProcessGroup for current rank's sub-mesh. --
216
- # All ranks must call dist.new_group in the same order, even though each
217
- # rank only joins one group.
218
- def _cache_key(t: torch.Tensor) -> tuple:
219
- return (*t.shape, *t.flatten().tolist())
220
-
221
- my_key = None
222
- for sm in shard_meshes:
223
- key = _cache_key(sm)
224
- if (my_rank == sm).any().item():
225
- assert my_key is None, "Rank appears in multiple shard groups"
226
- my_key = key
227
- if key not in _ranks_to_dist_cache:
228
- pg = dist.new_group(sm.flatten().tolist())
229
- _ranks_to_dist_cache[key] = (
230
- DeviceMesh(device_type="cuda", mesh=sm),
231
- pg,
232
- )
233
-
234
- return (*_ranks_to_dist_cache[my_key], shard_placements)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu126-x86_64-linux/matmul_transpose_triton.py DELETED
@@ -1,121 +0,0 @@
1
- # MIT License
2
- #
3
- # Copyright (c) 2025 Tianyang Lin
4
- #
5
- # Permission is hereby granted, free of charge, to any person obtaining a copy
6
- # of this software and associated documentation files (the "Software"), to deal
7
- # in the Software without restriction, including without limitation the rights
8
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- # copies of the Software, and to permit persons to whom the Software is
10
- # furnished to do so, subject to the following conditions:
11
- #
12
- # The above copyright notice and this permission notice shall be included in all
13
- # copies or substantial portions of the Software.
14
- #
15
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- # SOFTWARE.
22
-
23
- import torch
24
- import triton
25
- import triton.language as tl
26
-
27
-
28
- def get_autotune_config():
29
- return [
30
- triton.Config(
31
- {
32
- 'BLOCK_SIZE_M': blk_m,
33
- 'BLOCK_SIZE_K': blk_k,
34
- 'GROUP_SIZE_M': grp_sz
35
- },
36
- num_stages=n_stages,
37
- num_warps=n_warps) for blk_m in [32, 64, 128]
38
- for blk_k in [32, 64] for grp_sz in [8] for n_stages in [3, 4, 5]
39
- for n_warps in [4, 8]
40
- ]
41
-
42
-
43
- @triton.autotune(
44
- configs=get_autotune_config(),
45
- key=['M', 'K'],
46
- )
47
- @triton.jit
48
- def mmt_kernel(x, y, M, K, stride_xm, stride_xk, stride_ym, stride_yn,
49
- BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
50
- GROUP_SIZE_M: tl.constexpr):
51
- """
52
- Core kernel jit function of matmul_transpose that computes y = x @ x.T
53
- The code is a simple adaptation from the triton `matmul` tutorial:
54
- https://triton-lang.org/main/getting-started/tutorials/03-matrix-multiplication.html
55
- """
56
- pid = tl.program_id(axis=0)
57
- num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
58
- num_pid_n = tl.cdiv(M, BLOCK_SIZE_M)
59
- num_pid_in_group = GROUP_SIZE_M * num_pid_n
60
- group_id = pid // num_pid_in_group
61
- first_pid_m = group_id * GROUP_SIZE_M
62
- group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
63
- pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
64
- pid_n = (pid % num_pid_in_group) // group_size_m
65
- if pid_m > pid_n:
66
- return
67
-
68
- offs_xm = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
69
- offs_xn = (pid_n * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
70
- offs_k = tl.arange(0, BLOCK_SIZE_K)
71
- # we use a & b ptrs to denote different rows of x.
72
- a_ptrs = x + (offs_xm[:, None] * stride_xm + offs_k[None, :] * stride_xk)
73
- b_ptrs = x + (offs_xn[:, None] * stride_xm + offs_k[None, :] * stride_xk)
74
-
75
- accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_M), dtype=tl.float32)
76
-
77
- for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
78
- a = tl.load(a_ptrs,
79
- mask=offs_k[None, :] < K - k * BLOCK_SIZE_K,
80
- other=0.0)
81
- b = tl.load(b_ptrs,
82
- mask=offs_k[None, :] < K - k * BLOCK_SIZE_K,
83
- other=0.0)
84
- accumulator = tl.dot(a, tl.permute(b, (1, 0)), accumulator)
85
- a_ptrs += BLOCK_SIZE_K * stride_xk
86
- b_ptrs += BLOCK_SIZE_K * stride_xk
87
- # use dtype.element_ty to accommodate different input datatypes as in cpp templates
88
- # https://github.com/triton-lang/triton/issues/2252
89
- c = accumulator.to(x.dtype.element_ty)
90
-
91
- offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
92
- offs_cn = pid_n * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
93
- c_ptrs = y + stride_ym * offs_cm[:, None] + stride_yn * offs_cn[None, :]
94
- c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < M)
95
- tl.store(c_ptrs, c, mask=c_mask)
96
-
97
- # transpose and copy
98
- if pid_m < pid_n:
99
- ct_ptrs = y + stride_ym * offs_cn[:,
100
- None] + stride_yn * offs_cm[None, :]
101
- ct_mask = (offs_cn[:, None] < M) & (offs_cm[None, :] < M)
102
- tl.store(ct_ptrs, tl.permute(c, (1, 0)), mask=ct_mask)
103
-
104
-
105
- def matmul_transpose_assign(d_in, d_out):
106
- assert d_in.is_cuda, "Input `d_in` must be a CUDA tensor"
107
- assert d_out.is_cuda, "Input `d_out` must be a CUDA tensor"
108
- assert d_in.device == d_out.device, "Inputs `d_in` and `d_out` must be on the same CUDA device"
109
- assert d_in.dtype == d_out.dtype, "Inputs must have the same data type"
110
- assert d_in.ndim == 2, "Input `d_in` must be a 2D tensor"
111
- assert d_out.ndim == 2, "Input `d_out` must be a 2D tensor"
112
- assert d_in.size(0) == d_out.size(0) == d_out.size(0), \
113
- "First dimension of `d_in` must match first and second dimension of `d_out`"
114
-
115
- d_in = d_in.contiguous()
116
- M, K = d_in.shape
117
- grid = lambda META: (triton.cdiv(M, META['BLOCK_SIZE_M']) * triton.cdiv(
118
- M, META['BLOCK_SIZE_M']), )
119
- with torch.cuda.device(d_in.device.index):
120
- mmt_kernel[grid](d_in, d_out, M, K, d_in.stride(0), d_in.stride(1),
121
- d_out.stride(0), d_out.stride(1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu126-x86_64-linux/metadata.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "python-depends": []
3
- }
 
 
 
 
build/torch210-cxx11-cu126-x86_64-linux/muon.py DELETED
@@ -1,594 +0,0 @@
1
- import logging
2
- import types
3
- from collections import defaultdict
4
- from typing import Any
5
-
6
- import torch
7
- import torch.distributed as dist
8
- from torch.distributed.tensor import DTensor, Replicate, Shard
9
- from torch.profiler import record_function
10
-
11
- from .adamw import step_adamw
12
- from .async_utils import run_pipeline
13
- from .core import (_muon_state, adjust_lr_for_muon,
14
- get_default_muon_param_groups, update_g, update_p)
15
- from .distributed.utils import (_is_shard, construct_shard_mesh,
16
- get_slices_of_dtensor)
17
- from .newton_schulz import (COMM_DTYPE, DEFAULT_CHUNK_SIZE_RATIO,
18
- _zeropower_via_newtonschulz5)
19
- from .pipeline import muon_chunk_pipeline
20
- from .qk_clip import compute_scales, get_qk_clip_info, qk_clip
21
-
22
- logger = logging.getLogger(__name__)
23
-
24
-
25
- def _expand_expert_params(names, params, expert_keys):
26
- """Expand expert params by splitting on dim 0 (expert dimension).
27
-
28
- Params whose name matches any key in ``expert_keys`` are treated as
29
- expert-parallel tensors. Their outermost dimension is the expert
30
- dimension: an ``(E, out, in)`` tensor becomes ``E`` separate 2D
31
- ``nn.Parameter`` views so that in-place updates propagate back to
32
- the original storage.
33
-
34
- Non-expert params with ``ndim > 2`` trigger an ``AssertionError`` —
35
- if they are expert params, their key must be added to ``expert_keys``.
36
-
37
- The grad must already be set on each expert param (e.g. after momentum).
38
-
39
- For DTensor expert params, placements that shard on dim 0 (expert dim)
40
- are consumed by the split. Non-dim-0 shard placements (e.g. TP) are
41
- preserved: each 2D slice is wrapped as a DTensor on the corresponding
42
- submesh so the parallel pipeline handles the TP communication.
43
- """
44
- expanded_names = []
45
- expanded_params = []
46
-
47
- for n, p in zip(names, params):
48
- is_expert = expert_keys and any(key in n for key in expert_keys)
49
- is_dtensor = isinstance(p.data, DTensor)
50
-
51
- if not is_expert:
52
- assert p.data.ndim <= 2, (
53
- f"Param {n} has ndim={p.data.ndim} but does not match "
54
- f"expert_keys={expert_keys}. If this is an expert param, "
55
- f"add its key to expert_keys.")
56
- expanded_names.append(n)
57
- expanded_params.append(p)
58
- continue
59
-
60
- g = p.grad
61
- assert g is not None, (
62
- f"Expert param {n} must have grad set before expansion")
63
-
64
- tp_mesh = None
65
- tp_placements_2d = None
66
-
67
- if is_dtensor:
68
- local_data = p.to_local()
69
- local_grad = g.to_local() if isinstance(g, DTensor) else g
70
-
71
- # Find non-dim-0 shard placements (e.g. TP sharding).
72
- # After splitting on dim 0, Shard(k) becomes Shard(k-1).
73
- tp_dim_indices = []
74
- tp_placements_2d = []
75
- for i, pl in enumerate(p.placements):
76
- if _is_shard(pl) and pl.dim != 0:
77
- tp_dim_indices.append(i)
78
- tp_placements_2d.append(Shard(pl.dim - 1))
79
-
80
- if tp_dim_indices:
81
- tp_dim_names = tuple(p.device_mesh.mesh_dim_names[i]
82
- for i in tp_dim_indices)
83
- if len(tp_dim_names) == 1:
84
- tp_mesh = p.device_mesh[tp_dim_names[0]]
85
- else:
86
- tp_mesh = p.device_mesh[tp_dim_names]
87
- else:
88
- local_data = p.data
89
- local_grad = g
90
-
91
- # Expand: split dim 0, reshape each slice to 2D.
92
- num_local_experts = local_data.shape[0]
93
- for i in range(num_local_experts):
94
- slice_data = local_data[i]
95
- slice_grad = local_grad[i]
96
-
97
- if tp_mesh is not None:
98
- # Wrap as DTensor on TP submesh so the pipeline handles
99
- # TP communication (gather/scatter across TP ranks).
100
- dt_data = DTensor.from_local(slice_data,
101
- device_mesh=tp_mesh,
102
- placements=tp_placements_2d)
103
- dt_grad = DTensor.from_local(slice_grad,
104
- device_mesh=tp_mesh,
105
- placements=tp_placements_2d)
106
- expert_param = torch.nn.Parameter(dt_data, requires_grad=False)
107
- expert_param.grad = dt_grad
108
- else:
109
- expert_param = torch.nn.Parameter(slice_data,
110
- requires_grad=False)
111
- expert_param.grad = slice_grad
112
-
113
- expanded_names.append(f"{n}[{i}]")
114
- expanded_params.append(expert_param)
115
-
116
- p.grad = None # allow expert grad storage to be freed after pipeline
117
-
118
- return expanded_names, expanded_params
119
-
120
-
121
- class Muon(torch.optim.Optimizer):
122
- """
123
- Muon - MomentUm Orthogonalized by Newton-schulz
124
-
125
- Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-
126
- processing step, in which each 2D parameter's update is replaced with the nearest orthogonal
127
- matrix. To efficiently orthogonalize each update, we use a Newton-Schulz iteration, which has
128
- the advantage that it can be stably run in bfloat16 on the GPU.
129
-
130
- Some warnings:
131
- - We believe this optimizer is unlikely to work well for training with small batch size.
132
- - We believe it may not work well for finetuning pretrained models, but we haven't tested this.
133
-
134
- Arguments:
135
- model: The model to be optimized by Muon.
136
- is_muon_func: A function that takes a parameter and its name, and returns whether the parameter should be optimized by Muon.
137
- lr: The learning rate. The updates will have spectral norm of `lr`. (0.02 is a good default)
138
- momentum: The momentum used by the internal SGD. (0.95 is a good default)
139
- nesterov: Whether to use Nesterov-style momentum in the internal SGD. (recommended)
140
- ns_steps: The number of Newton-Schulz iterations to run. (6 is probably always enough)
141
- weight_decay: The weight decay for Muon and AdamW.
142
- Parameters that are {0, 1}-D or are detected as being the embed or lm_head will be optimized by AdamW instead.
143
- adamw_lr: The learning rate for the internal AdamW.
144
- adamw_betas: The betas for the internal AdamW.
145
- adamw_eps: The epsilon for the internal AdamW.
146
- none_grad: Whether to set p.grad to None after gathering the gradients. This can save memory.
147
- debug: Whether to print debug information.
148
- clip_info : Configuration for QK clipping. Expected keys:
149
- - "q_indices" (list[int]): Indices of query heads to consider.
150
- - "k_indices" (list[int]): Indices of key heads to consider.
151
- - "head_dim" (int): Dimensionality of each attention head.
152
- - "threshold" (float): Threshold value; heads whose QK logits exceed
153
- this value will be scaled down.
154
- Default is:
155
- {
156
- "q_indices": [],
157
- "k_indices": [],
158
- "head_dim": 128,
159
- "threshold": 100
160
- }
161
- warmup_step : How many all2all gather, compute operations are launched in advance
162
- before the corresponding all2all scatter steps begin.
163
- A higher warmup_step increases memory usage but can improve
164
- performance by overlapping communication.
165
- Parallel muon only.
166
- chunk_size : Batch size of parameters to process in each
167
- all2all gather/compute/scatter step.
168
- Use shard ranks * DEFAULT_CHUNK_SIZE_RATIO when -1 is specified.
169
- use_distributed_muon: Use distributed muon by Liu et al. (2024).
170
- For testing purpose only.
171
- small_param_numel_threshold: Threshold for classifying parameters as small and falling back to distributed Muon
172
- expert_keys: List of strings to identify expert-parallel parameters.
173
- If any key appears in a parameter's name, its outermost
174
- dimension is treated as the expert dimension and expanded
175
- into per-expert 2D params for Muon. For example,
176
- ``expert_keys=["experts"]`` matches any param whose name
177
- contains "experts". 3D+ params not matched by any key
178
- will raise an error.
179
- """
180
-
181
- def __init__(self,
182
- params,
183
- lr=1e-3,
184
- momentum=0.95,
185
- nesterov=True,
186
- ns_steps=5,
187
- weight_decay=0.1,
188
- adamw_betas=(0.9, 0.95),
189
- adamw_eps=1e-8,
190
- none_grad=True,
191
- debug=False,
192
- clip_config=None,
193
- warmup_step=5,
194
- chunk_size=-1,
195
- use_distributed_muon=False,
196
- small_param_numel_threshold=65536,
197
- expert_keys=None):
198
- defaults = dict(
199
- lr=lr,
200
- weight_decay=weight_decay,
201
- momentum=momentum,
202
- nesterov=nesterov,
203
- ns_steps=ns_steps,
204
- adamw_betas=adamw_betas,
205
- adamw_eps=adamw_eps,
206
- none_grad=none_grad,
207
- use_muon=True,
208
- )
209
- error_message = "The key 'use_muon' is not set in parameter group {idx}. Assuming all parameters in the group will use muon optimization, which may lead to unexpected behavior."
210
- instruction_code = "\n\n please follow this code snippet \n```optimizer = get_kernel('motif-technologies/optimizer')\n\n\nparams = optimizer.muon.get_default_muon_param_groups(model)\n\noptim = optimizer.Muon(params, ...)```"
211
-
212
- if isinstance(params, types.GeneratorType):
213
- raise ValueError(error_message.format(idx=0) + instruction_code)
214
- for _idx, param_group in enumerate(params):
215
- if param_group.get("use_muon", None) is None:
216
- raise ValueError(
217
- error_message.format(idx=_idx) + instruction_code)
218
-
219
- super().__init__(params, defaults)
220
-
221
- self.debug = debug
222
- self.clip_config = clip_config if clip_config is not None else {
223
- "q_indices": [],
224
- "k_indices": [],
225
- "head_dim": 128,
226
- "threshold": 100,
227
- }
228
- self.warmup_step = warmup_step
229
- self.chunk_size = chunk_size
230
- self.use_distributed_muon = use_distributed_muon
231
- self.small_param_numel_threshold = small_param_numel_threshold
232
- self.expert_keys = expert_keys
233
-
234
- def _calc_flops(self, G, steps):
235
- assert len(G.shape) == 2
236
- M, N = G.shape
237
- if M > N:
238
- M, N = N, M
239
-
240
- return steps * ((M**3) * 2 + (M**2 * N) * 4 + M * N * 2 + M**2 * 3)
241
-
242
- def get_shard_mesh(self, p):
243
- """
244
- Get the shard mesh for a parameter p on the given rank.
245
- """
246
- assert isinstance(
247
- p, DTensor), "Parallel Muon only supports DTensor parameters."
248
-
249
- shard_mesh, shard_pg, shard_placements = construct_shard_mesh(
250
- p.placements, p.device_mesh)
251
-
252
- return shard_mesh, shard_pg, shard_placements
253
-
254
- def init_state_and_assign_params(self, names, params, group, qk_logits):
255
- param_to_state = {}
256
- param_to_flops = {}
257
-
258
- total_flops = 0
259
- for p in params:
260
- g = p.grad
261
- if g is None:
262
- continue
263
- assert g.ndim == 2, "Muon only supports 2D parameters."
264
-
265
- flops = self._calc_flops(g, group["ns_steps"])
266
- param_to_flops[id(p)] = flops
267
- total_flops += flops
268
-
269
- if self.debug:
270
- logger.debug("Total TFLOPs for Muon: %.2f TFLOPs",
271
- total_flops / 1e12)
272
-
273
- paired = list(zip(names, params))
274
-
275
- paired_sorted = sorted(paired,
276
- key=lambda x: param_to_flops[id(x[1])],
277
- reverse=True)
278
-
279
- names_sorted, params_sorted = zip(*paired_sorted)
280
- ordered_names = list(names_sorted)
281
- ordered_params = list(params_sorted)
282
-
283
- round_robin = 0
284
- mesh = ordered_params[0].device_mesh
285
- placements = ordered_params[0].placements
286
-
287
- shard_mesh, shard_pg, shard_placements = self.get_shard_mesh(
288
- ordered_params[0])
289
- shard_mesh_flattened = shard_mesh.mesh.flatten()
290
- num_ranks = dist.get_world_size(group=shard_pg)
291
-
292
- for n, p in zip(ordered_names, ordered_params):
293
- if mesh != p.device_mesh:
294
- raise ValueError("All parameters must be on the same mesh.")
295
- if placements != p.placements:
296
- raise ValueError("All parameters must have same placements.")
297
-
298
- worker_rank = shard_mesh_flattened[round_robin].item() % num_ranks
299
- round_robin = (round_robin + 1) % len(shard_mesh_flattened)
300
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
301
-
302
- # Precompute per-rank indices and numels for all-to-all.
303
- rank_indices: dict[int, tuple] = {}
304
- rank_numels: dict[int, int] = {}
305
- for r in range(num_ranks):
306
- indices = get_slices_of_dtensor(p, r, shard_mesh,
307
- shard_placements)
308
- rank_indices[r] = indices
309
- numel = 1
310
- for idx, dim_size in zip(indices, p.shape):
311
- if isinstance(idx, slice):
312
- start, stop, step = idx.indices(dim_size)
313
- numel *= max(0, (stop - start + (step - 1)) // step)
314
- else:
315
- numel *= len(idx)
316
- rank_numels[r] = numel
317
-
318
- param_to_state[id(p)] = _muon_state(
319
- worker_rank=worker_rank,
320
- process_group=shard_pg,
321
- rank_indices=rank_indices,
322
- rank_numels=rank_numels,
323
- name=n,
324
- qk_clip_state=qk_clip_state,
325
- )
326
-
327
- return param_to_state, ordered_params
328
-
329
- def base(self, names, params, group, lr, weight_decay, qk_logits):
330
- # Momentum is already applied by _step_muon before this method.
331
- for n, p in zip(names, params):
332
- g = p.grad
333
- if g is None:
334
- continue
335
-
336
- u = _zeropower_via_newtonschulz5(g.to(COMM_DTYPE),
337
- steps=group["ns_steps"])
338
-
339
- adjusted_lr = adjust_lr_for_muon(lr, p.shape)
340
- update_p(p, u, lr, adjusted_lr, weight_decay)
341
-
342
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
343
-
344
- scales_full = compute_scales(
345
- p, qk_clip_state) if qk_clip_state is not None else None
346
- if scales_full is not None:
347
- qk_clip(p, scales_full, qk_clip_state.head_dim)
348
-
349
- def distributed_muon(
350
- self,
351
- names: list[str],
352
- params: list[torch.nn.Parameter],
353
- group: dict[str, Any],
354
- lr: float,
355
- weight_decay: float,
356
- qk_logits: list[torch.Tensor | DTensor] | None,
357
- ):
358
- """ Implementation of Distributed Muon by Liu et al. """
359
-
360
- # Momentum is already applied by _step_muon before this method.
361
- for n, p in zip(names, params):
362
- g = p.grad
363
- if g is None:
364
- continue
365
-
366
- # Gather G
367
- if isinstance(p.data, DTensor):
368
- g_full = g.full_tensor()
369
- p_full = p.data.full_tensor()
370
- else:
371
- g_full = g
372
- p_full = p
373
-
374
- u_full = _zeropower_via_newtonschulz5(g_full.to(COMM_DTYPE),
375
- steps=group["ns_steps"])
376
-
377
- adjusted_lr = adjust_lr_for_muon(lr, p_full.shape)
378
- update_p(p_full, u_full, lr, adjusted_lr, weight_decay)
379
-
380
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
381
-
382
- scales_full = compute_scales(
383
- p_full, qk_clip_state) if qk_clip_state is not None else None
384
-
385
- if scales_full is not None:
386
- qk_clip(p_full, scales_full, qk_clip_state.head_dim)
387
-
388
- if isinstance(p.data, DTensor):
389
- ndims = len(p.device_mesh.mesh.shape)
390
- p_replicate = DTensor.from_local(
391
- p_full,
392
- device_mesh=p.device_mesh,
393
- placements=[Replicate() for _ in range(ndims)],
394
- )
395
-
396
- p_sharded = p_replicate.redistribute(
397
- device_mesh=p.device_mesh,
398
- placements=p.placements,
399
- )
400
-
401
- p.copy_(p_sharded)
402
-
403
- def parallel(self, names, params, group, lr, weight_decay, qk_logits):
404
- """
405
- Perform a parallel optimization step using Muon.
406
-
407
- Parameters are chunked and each chunk is processed by a
408
- :func:`muon_chunk_pipeline` generator. :func:`run_pipeline`
409
- interleaves multiple chunks so that communication and computation
410
- overlap across chunks (the same overlap previously achieved by the
411
- warmup + main-loop index scheduling).
412
- """
413
-
414
- # Momentum is already applied by _step_muon before this method.
415
-
416
- param_to_state, ordered_params = self.init_state_and_assign_params(
417
- names, params, group, qk_logits)
418
-
419
- # Compute local rank for this group's shard process group.
420
- shard_pg = param_to_state[id(ordered_params[0])].process_group
421
- rank = dist.get_rank(group=shard_pg)
422
-
423
- if self.chunk_size == -1:
424
- shard_ranks = dist.get_world_size(param_to_state[id(
425
- ordered_params[0])].process_group)
426
- chunk_size = shard_ranks * DEFAULT_CHUNK_SIZE_RATIO
427
- elif self.chunk_size > 0:
428
- chunk_size = self.chunk_size
429
- else:
430
- raise ValueError("chunk_size must be -1 or a positive integer.")
431
-
432
- def pipelines():
433
- for start in range(0, len(ordered_params), chunk_size):
434
- chunk = ordered_params[start:start + chunk_size]
435
- if chunk:
436
- yield muon_chunk_pipeline(
437
- params=chunk,
438
- param_to_state=param_to_state,
439
- rank=rank,
440
- ns_steps=group["ns_steps"],
441
- lr=lr,
442
- weight_decay=weight_decay,
443
- none_grad=group["none_grad"],
444
- )
445
-
446
- with record_function("muon::barrier"):
447
- dist.barrier()
448
- with record_function("muon::pipeline"):
449
- run_pipeline(pipelines(), max_concurrent=self.warmup_step + 1)
450
-
451
- def _step_muon(self, group, qk_logits=None):
452
- params = group["params"]
453
- lr = group["lr"]
454
- weight_decay = group["weight_decay"]
455
- momentum = group["momentum"]
456
- names = group["names"]
457
-
458
- # Apply momentum to all params before routing/expansion.
459
- with record_function("muon::momentum"):
460
- for n, p in zip(names, params):
461
- g = p.grad
462
- if g is None:
463
- continue
464
- g = update_g(self.state, p, g, group, momentum)
465
- p.grad = g
466
-
467
- # Expand expert params by splitting on dim 0.
468
- names, params = _expand_expert_params(names, params, self.expert_keys)
469
-
470
- param_dtensors = []
471
- name_dtensors = []
472
-
473
- param_tensors = []
474
- name_tensors = []
475
-
476
- param_dtensors_small = []
477
- name_dtensors_small = []
478
-
479
- if self.use_distributed_muon:
480
- self.distributed_muon(names=names,
481
- params=params,
482
- group=group,
483
- lr=lr,
484
- weight_decay=weight_decay,
485
- qk_logits=qk_logits)
486
- return
487
-
488
- # For simplicity, we use distributed Muon for small parameters
489
- # whose number of elements is below a threshold.
490
- for n, p in zip(names, params):
491
- if p is None or p.grad is None:
492
- continue
493
- if isinstance(p.data, DTensor):
494
- if all(
495
- isinstance(placement, Replicate)
496
- for placement in p.placements):
497
- param_tensors.append(p)
498
- name_tensors.append(n)
499
- elif p.data.numel() <= self.small_param_numel_threshold:
500
- param_dtensors_small.append(p)
501
- name_dtensors_small.append(n)
502
- else:
503
- param_dtensors.append(p)
504
- name_dtensors.append(n)
505
- elif isinstance(p.data, torch.Tensor):
506
- param_tensors.append(p)
507
- name_tensors.append(n)
508
- else:
509
- raise TypeError(f"Unsupported parameter type: {type(p.data)}")
510
-
511
- logger.debug(
512
- f"[Muon] {len(param_dtensors)} DTensors, {len(param_tensors)} Tensors, "
513
- f"{len(param_dtensors_small)} Small DTensors")
514
-
515
- def group_dtensors(dtensors, names):
516
- # To support different placements, we group parameters by placements
517
- # and run parallel Muon on each group.
518
-
519
- placement_to_params = defaultdict(lambda: ([], []))
520
-
521
- assert len(dtensors) == len(names)
522
- for p, n in zip(dtensors, names):
523
- placement_to_params[tuple([p.placements,
524
- p.device_mesh])][0].append(n)
525
- placement_to_params[tuple([p.placements,
526
- p.device_mesh])][1].append(p)
527
- return placement_to_params
528
-
529
- if len(param_dtensors_small) > 0:
530
- if not dist.is_initialized():
531
- raise RuntimeError(
532
- "Parallel Muon requires torch.distributed to be initialized."
533
- )
534
-
535
- self.distributed_muon(
536
- params=param_dtensors_small,
537
- names=name_dtensors_small,
538
- group=group,
539
- lr=lr,
540
- weight_decay=weight_decay,
541
- qk_logits=qk_logits,
542
- )
543
-
544
- if len(param_dtensors) > 0:
545
- if not dist.is_initialized():
546
- raise RuntimeError(
547
- "Parallel Muon requires torch.distributed to be initialized."
548
- )
549
-
550
- dtensor_group = group_dtensors(param_dtensors, name_dtensors)
551
- for _, (names, params) in dtensor_group.items():
552
- self.parallel(
553
- names,
554
- params,
555
- group,
556
- lr=lr,
557
- weight_decay=weight_decay,
558
- qk_logits=qk_logits,
559
- )
560
-
561
- if len(param_tensors) > 0:
562
- self.base(
563
- name_tensors,
564
- param_tensors,
565
- group,
566
- lr=lr,
567
- weight_decay=weight_decay,
568
- qk_logits=qk_logits,
569
- )
570
-
571
- @torch.no_grad
572
- def step(self, closure=None, qk_logits=None):
573
- """Perform a single optimization step.
574
-
575
- Args:
576
- closure (Callable, optional): A closure that reevaluates the model
577
- and returns the loss.
578
- qk_logits (dict[int, Tensor], optional): A dictionary mapping layer indices
579
- to 1D tensors of shape (num_heads,), representing the maximum
580
- QK logits across all tokens, computed as
581
- (1 / sqrt(head_dim)) * (Q @ K^T).
582
- """
583
- loss = None
584
- if closure is not None:
585
- with torch.enable_grad():
586
- loss = closure()
587
-
588
- for group in self.param_groups:
589
- if group["use_muon"]:
590
- self._step_muon(group, qk_logits=qk_logits)
591
- else:
592
- step_adamw(self.state, group)
593
-
594
- return loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu126-x86_64-linux/newton_schulz.py DELETED
@@ -1,50 +0,0 @@
1
- import torch
2
-
3
- from .matmul_transpose_triton import matmul_transpose_assign
4
-
5
- COMM_DTYPE = torch.bfloat16
6
- DEFAULT_CHUNK_SIZE_RATIO = 4
7
-
8
-
9
- # This code snippet is a modified version adapted from the following GitHub repositories:
10
- # https://github.com/KellerJordan/Muon/blob/master/muon.py
11
- # Muon's Newton–Schulz iteration causes high variance in singular values
12
- # Idea: give each iteration its own 3 coefficients and optimize them via gradient descent.
13
- @torch.no_grad()
14
- # matmul_transpose_assign from : https://github.com/nil0x9/flash-muon
15
- def _zeropower_via_newtonschulz5(G, steps):
16
- """
17
- Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a
18
- quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose
19
- of minimizing steps, it turns out to be empirically effective to keep increasing the slope at
20
- zero even beyond the point where the iteration no longer converges all the way to one everywhere
21
- on the interval. This iteration therefore does not produce UV^T but rather something like US'V^T
22
- where S' is diagonal with S_{ii}' ~ Uniform(0.5, 1.5), which turns out not to hurt model
23
- performance at all relative to UV^T, where USV^T = G is the SVD.
24
- """
25
- assert len(G.shape) == 2
26
- assert G.dtype == COMM_DTYPE
27
- X = G # no manual typecast
28
-
29
- if G.size(0) > G.size(1):
30
- X = X.T
31
- # Ensure spectral norm is at most 1
32
- X = X / (X.norm() + 1e-7)
33
- buf1 = torch.empty(X.size(0), X.size(0), dtype=X.dtype, device=X.device)
34
- buf2 = torch.empty(X.size(0), X.size(0), dtype=X.dtype, device=X.device)
35
- # Perform the NS iterations
36
- for a, b, c in [
37
- (4.0848, -6.8946, 2.9270),
38
- (3.9505, -6.3029, 2.6377),
39
- (3.7418, -5.5913, 2.3037),
40
- (2.8769, -3.1427, 1.2046),
41
- (2.8366, -3.0525, 1.2012),
42
- ]:
43
- matmul_transpose_assign(X, buf1)
44
- matmul_transpose_assign(buf1, buf2)
45
- buf1.mul_(b).add_(buf2, alpha=c)
46
- X = torch.addmm(X, buf1, X, alpha=1.0, beta=a)
47
-
48
- if G.size(0) > G.size(1):
49
- X = X.T
50
- return X
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu126-x86_64-linux/optimizer/__init__.py DELETED
@@ -1,26 +0,0 @@
1
- import ctypes
2
- import sys
3
-
4
- import importlib
5
- from pathlib import Path
6
- from types import ModuleType
7
-
8
- def _import_from_path(file_path: Path) -> ModuleType:
9
- # We cannot use the module name as-is, after adding it to `sys.modules`,
10
- # it would also be used for other imports. So, we make a module name that
11
- # depends on the path for it to be unique using the hex-encoded hash of
12
- # the path.
13
- path_hash = "{:x}".format(ctypes.c_size_t(hash(file_path.absolute())).value)
14
- module_name = path_hash
15
- spec = importlib.util.spec_from_file_location(module_name, file_path)
16
- if spec is None:
17
- raise ImportError(f"Cannot load spec for {module_name} from {file_path}")
18
- module = importlib.util.module_from_spec(spec)
19
- if module is None:
20
- raise ImportError(f"Cannot load module {module_name} from spec")
21
- sys.modules[module_name] = module
22
- spec.loader.exec_module(module) # type: ignore
23
- return module
24
-
25
-
26
- globals().update(vars(_import_from_path(Path(__file__).parent.parent / "__init__.py")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu126-x86_64-linux/pipeline.py DELETED
@@ -1,390 +0,0 @@
1
- import logging
2
- from typing import Generator
3
-
4
- import torch
5
- import torch.distributed as dist
6
- from torch.distributed.tensor import DTensor
7
- from torch.profiler import record_function
8
-
9
- from .core import _muon_state, adjust_lr_for_muon, update_p
10
- from .newton_schulz import COMM_DTYPE, _zeropower_via_newtonschulz5
11
- from .qk_clip import compute_scales
12
-
13
- logger = logging.getLogger(__name__)
14
-
15
- # ======================================================================
16
- # Stage helpers
17
- # ======================================================================
18
-
19
-
20
- def _launch_gather(
21
- params: list[DTensor],
22
- owned_params: list[DTensor],
23
- param_to_state: dict[int, _muon_state],
24
- rank: int,
25
- num_ranks: int,
26
- process_group: dist.ProcessGroup,
27
- ) -> tuple[dist.Work, torch.Tensor, dict[int, torch.Tensor | None], list[int]]:
28
- """Allocate gather buffers, build send/recv, and launch async all-to-all.
29
-
30
- Returns:
31
- work: Async operation handle.
32
- recv_buf: Flat receive buffer (needed by ``_complete_gather``).
33
- gathered_grads: ``{id(p): empty_tensor}`` for owned params,
34
- ``None`` for non-owned.
35
- recv_counts: Per-source-rank element counts.
36
- """
37
- # Allocate gathered-grad buffers
38
- gathered_grads: dict[int, torch.Tensor | None] = {}
39
- for p in params:
40
- state = param_to_state[id(p)]
41
- if rank == state.worker_rank:
42
- gathered_grads[id(p)] = torch.empty(p.shape,
43
- dtype=COMM_DTYPE,
44
- device="cuda")
45
- else:
46
- gathered_grads[id(p)] = None
47
-
48
- # Build send buffer
49
- per_dst: list[list[torch.Tensor]] = [[] for _ in range(num_ranks)]
50
- send_counts = [0] * num_ranks
51
-
52
- for p in params:
53
- state = param_to_state[id(p)]
54
- dst = state.worker_rank
55
- assert dst < num_ranks
56
- shard_elems = state.rank_numels[rank]
57
- g = p.grad
58
- g = g.to_local().to(COMM_DTYPE).contiguous()
59
- assert g.numel() == shard_elems
60
- per_dst[dst].append(g.view(-1))
61
- send_counts[dst] += shard_elems
62
-
63
- assert any(
64
- len(v) > 0 for v in
65
- per_dst), "At least one destination rank must receive a sharded tensor"
66
- per_dst_flat = [t for dst in per_dst for t in dst]
67
- send_buf = torch.cat(per_dst_flat, dim=0)
68
-
69
- # Build recv buffer
70
- recv_counts = [0] * num_ranks
71
- for src in range(num_ranks):
72
- total = 0
73
- for p in owned_params:
74
- state = param_to_state[id(p)]
75
- assert state.worker_rank == rank
76
- total += state.rank_numels[src]
77
- recv_counts[src] = total
78
-
79
- recv_buf = torch.empty(sum(recv_counts), dtype=COMM_DTYPE, device="cuda")
80
-
81
- # Launch async all-to-all
82
- logger.debug(f"send_buf size: {send_buf.numel()}, "
83
- f"recv_buf size: {recv_buf.numel()}, "
84
- f"recv_counts: {recv_counts}, "
85
- f"send_counts: {send_counts}, "
86
- f"process_group: {str(process_group)}")
87
- work = dist.all_to_all_single(
88
- recv_buf,
89
- send_buf,
90
- output_split_sizes=recv_counts,
91
- input_split_sizes=send_counts,
92
- group=process_group,
93
- async_op=True,
94
- )
95
-
96
- return work, recv_buf, gathered_grads, recv_counts
97
-
98
-
99
- def _complete_gather(
100
- recv_buf: torch.Tensor,
101
- recv_counts: list[int],
102
- owned_params: list[DTensor],
103
- gathered_grads: dict[int, torch.Tensor | None],
104
- param_to_state: dict[int, _muon_state],
105
- rank: int,
106
- ) -> None:
107
- """Reconstruct gathered grads from the recv buffer (in-place)."""
108
- off = 0
109
- for src in range(len(recv_counts)):
110
- if recv_counts[src] == 0:
111
- continue
112
-
113
- block = recv_counts[src]
114
- inner_off = 0
115
- for p in owned_params:
116
- state = param_to_state[id(p)]
117
- assert state.worker_rank == rank
118
-
119
- indices = state.rank_indices[src]
120
-
121
- shard_view = gathered_grads[id(p)][indices]
122
- n = shard_view.numel()
123
- assert n > 0
124
-
125
- sg = recv_buf.narrow(0, off + inner_off, n)
126
- sg = sg.reshape(shard_view.shape)
127
- gathered_grads[id(p)][indices] = sg
128
-
129
- inner_off += n
130
- assert inner_off == block
131
- off += block
132
-
133
-
134
- def _compute_ns(
135
- owned_params: list[DTensor],
136
- gathered_grads: dict[int, torch.Tensor | None],
137
- ns_steps: int,
138
- ) -> dict[int, torch.Tensor | None]:
139
- """Run Newton-Schulz orthogonalization on owned parameters.
140
-
141
- Returns:
142
- computed_us: ``{id(p): orthogonalized_update}`` for owned params.
143
- """
144
- computed_us: dict[int, torch.Tensor | None] = {}
145
- for p in owned_params:
146
- u = _zeropower_via_newtonschulz5(gathered_grads[id(p)], ns_steps)
147
- gathered_grads[id(p)] = None # free gathered grad
148
- computed_us[id(p)] = u
149
- return computed_us
150
-
151
-
152
- def _launch_scatter(
153
- params: list[DTensor],
154
- owned_params: list[DTensor],
155
- param_to_state: dict[int, _muon_state],
156
- rank: int,
157
- num_ranks: int,
158
- process_group: dist.ProcessGroup,
159
- computed_us: dict[int, torch.Tensor | None],
160
- ) -> tuple[dist.Work, torch.Tensor, dict[int, torch.Tensor], list[int]]:
161
- """Allocate scatter buffers, build send/recv, and launch async all-to-all.
162
-
163
- Returns:
164
- work: Async operation handle.
165
- recv_buf: Flat receive buffer (needed by ``_complete_scatter``).
166
- scattered_us: ``{id(p): empty_local_tensor}`` for all params.
167
- recv_counts: Per-source-rank element counts.
168
- """
169
- # Allocate scattered-u buffers
170
- scattered_us: dict[int, torch.Tensor] = {}
171
- for p in params:
172
- scattered_us[id(p)] = torch.empty_like(p.to_local(), dtype=COMM_DTYPE)
173
-
174
- # Build send buffer (from computed_us on owner ranks)
175
- per_dst: list[list[torch.Tensor]] = [[] for _ in range(num_ranks)]
176
- send_counts = [0] * num_ranks
177
-
178
- if owned_params:
179
- for p in owned_params:
180
- state = param_to_state[id(p)]
181
-
182
- assert computed_us[id(p)] is not None
183
- u_full = computed_us[id(p)].to(COMM_DTYPE).contiguous()
184
-
185
- total_sent = 0
186
- for dst_rank in range(num_ranks):
187
- indices = state.rank_indices[dst_rank]
188
- su = u_full[indices].flatten()
189
-
190
- n = su.numel()
191
- assert n > 0
192
-
193
- per_dst[dst_rank].append(su)
194
- send_counts[dst_rank] += n
195
- total_sent += n
196
-
197
- assert total_sent == u_full.numel()
198
-
199
- lengths = [len(v) for v in per_dst]
200
- if all(l > 0 for l in lengths):
201
- assert all(
202
- l == lengths[0] for l in lengths
203
- ), "All destination ranks must have the same number of sharded tensor"
204
- per_dst_flat = [t for dst in per_dst for t in dst]
205
- send_buf = torch.cat(per_dst_flat, dim=0)
206
- else:
207
- send_buf = torch.empty(0, dtype=COMM_DTYPE, device="cuda")
208
-
209
- # Build recv buffer
210
- recv_counts = [0] * num_ranks
211
- for src in range(num_ranks):
212
- total = 0
213
- for p in params:
214
- state = param_to_state[id(p)]
215
- if state.worker_rank != src:
216
- continue
217
- total += state.rank_numels[rank]
218
- recv_counts[src] = total
219
-
220
- recv_total = sum(recv_counts)
221
- assert recv_total > 0
222
- recv_buf = torch.empty(recv_total, dtype=COMM_DTYPE, device="cuda")
223
-
224
- # Launch async all-to-all
225
- work = dist.all_to_all_single(
226
- recv_buf,
227
- send_buf,
228
- output_split_sizes=recv_counts,
229
- input_split_sizes=send_counts,
230
- group=process_group,
231
- async_op=True,
232
- )
233
-
234
- return work, recv_buf, scattered_us, recv_counts
235
-
236
-
237
- def _complete_scatter(
238
- recv_buf: torch.Tensor,
239
- recv_counts: list[int],
240
- params: list[DTensor],
241
- param_to_state: dict[int, _muon_state],
242
- rank: int,
243
- scattered_us: dict[int, torch.Tensor],
244
- ) -> None:
245
- """Copy recv buffer into scattered_us (in-place)."""
246
- off = 0
247
- for src in range(len(recv_counts)):
248
- block = recv_counts[src]
249
- if block == 0:
250
- continue
251
-
252
- inner_off = 0
253
- for p in params:
254
- state = param_to_state[id(p)]
255
- if state.worker_rank != src:
256
- continue
257
- n = state.rank_numels[rank]
258
- assert n > 0
259
-
260
- flat_local = recv_buf.narrow(0, off + inner_off,
261
- n).view_as(p.to_local())
262
- scattered_us[id(p)].copy_(flat_local)
263
-
264
- inner_off += n
265
-
266
- assert inner_off == block
267
- off += block
268
-
269
-
270
- def _update_params(
271
- params: list[DTensor],
272
- param_to_state: dict[int, _muon_state],
273
- rank: int,
274
- scattered_us: dict[int, torch.Tensor],
275
- lr: float,
276
- weight_decay: float,
277
- ) -> None:
278
- """Apply weight decay, Muon update, and optional QK clipping."""
279
- for p in params:
280
- state = param_to_state[id(p)]
281
- u_dtensor = DTensor.from_local(
282
- scattered_us[id(p)],
283
- placements=p.placements,
284
- device_mesh=p.device_mesh,
285
- )
286
-
287
- adjusted_lr = adjust_lr_for_muon(lr, p.shape)
288
- update_p(p, u_dtensor, lr, adjusted_lr, weight_decay)
289
-
290
- # QK clipping – applied directly on the local tensor to
291
- # avoid DTensor sharding-propagation issues with _StridedShard.
292
- scales_full = compute_scales(
293
- p,
294
- state.qk_clip_state) if state.qk_clip_state is not None else None
295
- if scales_full is not None:
296
- ratio = p.shape[0] // scales_full.shape[0]
297
- idx0 = state.rank_indices[rank][0]
298
- if isinstance(idx0, slice):
299
- start = idx0.start or 0
300
- idx0 = torch.arange(start,
301
- idx0.stop,
302
- device=scales_full.device)
303
- row_scales = scales_full[idx0 // ratio]
304
- p._local_tensor.mul_(row_scales.view(-1, 1))
305
-
306
-
307
- # ======================================================================
308
- # Main generator – thin orchestrator that wires stages together.
309
- # ======================================================================
310
-
311
-
312
- @torch.no_grad()
313
- def muon_chunk_pipeline(
314
- params: list[DTensor],
315
- param_to_state: dict[int, _muon_state],
316
- rank: int,
317
- ns_steps: int,
318
- lr: float,
319
- weight_decay: float,
320
- none_grad: bool,
321
- ) -> Generator[None, None, None]:
322
- """Process one chunk of parameters through the full Muon pipeline.
323
-
324
- Stages: gather -> compute (Newton-Schulz) -> scatter -> update.
325
-
326
- Each ``yield`` lets :func:`run_pipeline` interleave other chunks so
327
- that communication and computation overlap across chunks. Async
328
- communication is launched via ``async_op=True`` and completed after
329
- the yield with ``work.wait()``.
330
-
331
- Overlap happens because :func:`run_pipeline` admits one new chunk
332
- per iteration (staggered admission). While chunk *N* does NS
333
- compute on the default CUDA stream, chunk *N+1*'s async all-to-all
334
- runs concurrently on the NCCL stream — no separate ``comm_stream``
335
- is required.
336
-
337
- Yields exactly **2** times:
338
-
339
- 1. After launching async all-to-all gather.
340
- 2. After launching async all-to-all scatter.
341
- """
342
- process_group = param_to_state[id(params[0])].process_group
343
- num_ranks = dist.get_world_size(group=process_group)
344
- owned_params = [
345
- p for p in params if param_to_state[id(p)].worker_rank == rank
346
- ]
347
-
348
- # Stages 1-2: launch async gather.
349
- with record_function("muon::launch_gather"):
350
- work, recv_buf, gathered_grads, recv_counts = _launch_gather(
351
- params, owned_params, param_to_state, rank, num_ranks,
352
- process_group)
353
-
354
- if none_grad:
355
- for p in params:
356
- p.grad = None
357
-
358
- yield # --- YIELD 1: other chunks can launch their gather ---
359
-
360
- with record_function("muon::wait_gather"):
361
- work.wait()
362
- _complete_gather(recv_buf, recv_counts, owned_params, gathered_grads,
363
- param_to_state, rank)
364
- del recv_buf
365
-
366
- # Stage 3: Newton-Schulz orthogonalization.
367
- with record_function("muon::newton_schulz"):
368
- computed_us = _compute_ns(owned_params, gathered_grads, ns_steps)
369
- gathered_grads.clear()
370
-
371
- # Stages 4-5: launch async scatter.
372
- with record_function("muon::launch_scatter"):
373
- work, recv_buf, scattered_us, recv_counts = _launch_scatter(
374
- params, owned_params, param_to_state, rank, num_ranks,
375
- process_group, computed_us)
376
- computed_us.clear()
377
-
378
- yield # --- YIELD 2: other chunks can launch their scatter ---
379
-
380
- with record_function("muon::wait_scatter"):
381
- work.wait()
382
- _complete_scatter(recv_buf, recv_counts, params, param_to_state, rank,
383
- scattered_us)
384
- del recv_buf
385
-
386
- # Stage 6: apply parameter updates.
387
- with record_function("muon::update_params"):
388
- _update_params(params, param_to_state, rank, scattered_us, lr,
389
- weight_decay)
390
- scattered_us.clear()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu126-x86_64-linux/qk_clip.py DELETED
@@ -1,129 +0,0 @@
1
- import logging
2
- import math
3
- from dataclasses import dataclass
4
-
5
- import torch
6
- from torch.distributed.tensor import DTensor
7
-
8
- logger = logging.getLogger(__name__)
9
-
10
-
11
- def parse_qk_layer(name: str) -> tuple[str | None, int]:
12
- """
13
- Parse a parameter name to check if it is a query/key projection layer
14
- ('wq', 'wk', 'q_proj', 'k_proj') and return (kind, layer_index).
15
-
16
- Returns:
17
- (kind, layer_idx) or (None, -1) if not matched.
18
-
19
- Example:
20
- 'model.3.attn.wq.weight' -> ('wq', 3)
21
- 'model.5.attn.wk.weight' -> ('wk', 5)
22
- 'model.2.attn.q_proj.weight' -> ('q_proj', 2)
23
- 'model.7.attn.k_proj.weight' -> ('k_proj', 7)
24
- 'model.4.attn.v_proj.weight' -> (None, -1)
25
- """
26
- parts = name.split('.')
27
- if len(parts) < 3:
28
- return None, -1
29
-
30
- kind = parts[-2]
31
-
32
- layer_idx = -1
33
- for part in reversed(parts):
34
- if part.isdigit():
35
- layer_idx = int(part)
36
- break
37
-
38
- if kind in ('wq', 'wk', 'q_proj', 'k_proj'):
39
- return kind, layer_idx
40
-
41
- return None, -1
42
-
43
-
44
- @dataclass
45
- class QKClipInfo:
46
- """Per-parameter dynamic info computed from config + runtime logits."""
47
- kind: str | None # 'wq'/'q_proj' or 'wk'/'k_proj' or None
48
- indices: list[int] # which heads to consider for clipping
49
- head_dim: int # from config
50
- threshold: float # from config
51
- logit: torch.Tensor | None
52
-
53
-
54
- def get_qk_clip_info(clip_config, n, qk_logits):
55
- """Extract QK clipping info for a named parameter.
56
-
57
- Args:
58
- clip_config: QK clipping configuration dict (or None).
59
- n: Parameter name string.
60
- qk_logits: Dict mapping layer indices to logit tensors (or None).
61
-
62
- Returns:
63
- QKClipInfo instance with clipping configuration for this parameter.
64
- """
65
- if clip_config is None:
66
- return None
67
-
68
- head_dim = clip_config.get('head_dim')
69
- threshold = clip_config.get('threshold')
70
- kind, layer_idx = parse_qk_layer(n)
71
-
72
- logit, indices = None, []
73
- if qk_logits is not None and kind is not None:
74
- logit = qk_logits[layer_idx]
75
- indices_key = 'q_indices' if 'q' in kind else 'k_indices'
76
- indices = clip_config.get(indices_key, []) or []
77
-
78
- if isinstance(logit, DTensor):
79
- # In TP settings, qk_logits may be DTensor
80
- # We convert it to full tensor here for simplicity
81
- logit = logit.full_tensor()
82
-
83
- return QKClipInfo(
84
- kind=kind,
85
- indices=indices,
86
- head_dim=head_dim,
87
- threshold=threshold,
88
- logit=logit,
89
- )
90
-
91
-
92
- def compute_scales(p, qk_clip_state):
93
- """Compute per-head scaling factors for QK clipping.
94
-
95
- Returns scales tensor if any head exceeds threshold, else None.
96
- """
97
- kind = qk_clip_state.kind
98
- indices = qk_clip_state.indices
99
- head_dim = qk_clip_state.head_dim
100
- threshold = qk_clip_state.threshold
101
- logit = qk_clip_state.logit
102
-
103
- H_global = p.shape[0] // head_dim
104
- scales_full = torch.ones(H_global, device=p.data.device)
105
- scaling = 0
106
-
107
- for logit_idx, head_idx in enumerate(indices):
108
- v_ele = float(logit[logit_idx])
109
- if v_ele > threshold:
110
- new_scale = math.sqrt(threshold / v_ele)
111
- if new_scale < scales_full[head_idx]:
112
- scales_full[head_idx] = new_scale
113
- logger.info(
114
- f"[{kind}] Head {head_idx} exceeded threshold "
115
- f"(value={v_ele:.4f}, threshold={threshold:.4f}) -> applying scale={new_scale:.4f}"
116
- )
117
- scaling += 1
118
-
119
- return scales_full if scaling > 0 else None
120
-
121
-
122
- def qk_clip(p, scales, head_dim):
123
- """Apply per-head scaling to a Q/K projection weight matrix."""
124
- if isinstance(p, torch.nn.Parameter):
125
- W = p.data.view(-1, head_dim, p.data.shape[1])
126
- W.mul_(scales.view(-1, 1, 1))
127
- else:
128
- W = p.view(-1, head_dim, p.shape[1])
129
- W.mul_(scales.view(-1, 1, 1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/adamw.py DELETED
@@ -1,154 +0,0 @@
1
- from collections import defaultdict
2
- from typing import cast
3
-
4
- import torch
5
- from torch.distributed.tensor import DTensor
6
-
7
-
8
- def fused_adamw(
9
- params: list[torch.Tensor],
10
- grads: list[torch.Tensor],
11
- exp_avgs: list[torch.Tensor],
12
- exp_avg_sqs: list[torch.Tensor],
13
- max_exp_avg_sqs: list[torch.Tensor],
14
- state_steps: list[torch.Tensor],
15
- amsgrad: bool,
16
- beta1: float,
17
- beta2: float,
18
- lr: float | torch.Tensor,
19
- weight_decay: float,
20
- eps: float,
21
- maximize: bool,
22
- ) -> None:
23
- if not params:
24
- return
25
-
26
- # We only shuffle around the lr when it is a Tensor and on CUDA, otherwise, we prefer
27
- # treating it as a scalar.
28
- lr_dict: dict | None = ({
29
- lr.device: lr
30
- } if isinstance(lr, torch.Tensor) and str(lr.device) != "cpu" else None)
31
- grouped_tensors = torch.optim.Optimizer._group_tensors_by_device_and_dtype(
32
- [params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs,
33
- state_steps] # type: ignore[list-item]
34
- )
35
- for (device, _), (
36
- (
37
- device_params_,
38
- device_grads_,
39
- device_exp_avgs_,
40
- device_exp_avg_sqs_,
41
- device_max_exp_avg_sqs,
42
- device_state_steps_,
43
- ),
44
- _,
45
- ) in grouped_tensors.items():
46
- device_params = cast(list[torch.Tensor], device_params_)
47
- device_grads = cast(list[torch.Tensor], device_grads_)
48
- device_exp_avgs = cast(list[torch.Tensor], device_exp_avgs_)
49
- device_exp_avg_sqs = cast(list[torch.Tensor], device_exp_avg_sqs_)
50
- device_state_steps = cast(list[torch.Tensor], device_state_steps_)
51
-
52
- if lr_dict is not None and device not in lr_dict:
53
- lr_dict[device] = lr.to(
54
- device=device, non_blocking=True) # type: ignore[union-attr]
55
- lr = lr_dict[device]
56
- torch._foreach_add_(device_state_steps, 1)
57
- func = torch._fused_adamw_
58
- func(
59
- device_params,
60
- device_grads,
61
- device_exp_avgs,
62
- device_exp_avg_sqs,
63
- device_max_exp_avg_sqs, # type: ignore[arg-type]
64
- device_state_steps,
65
- amsgrad=amsgrad,
66
- lr=lr, # type: ignore[arg-type]
67
- beta1=beta1,
68
- beta2=beta2,
69
- weight_decay=weight_decay,
70
- eps=eps,
71
- maximize=maximize,
72
- )
73
-
74
-
75
- def step_adamw_params(optimizer_state, params, group):
76
- """Run fused AdamW on a list of parameters sharing the same placement.
77
-
78
- Args:
79
- optimizer_state: The optimizer's state dict (self.state in Muon).
80
- params: List of parameters to update.
81
- group: Parameter group dict with lr, adamw_betas, adamw_eps, weight_decay.
82
- """
83
- params_with_grads = []
84
- grads = []
85
- moment1 = []
86
- moment2 = []
87
- max_exp_avg_sqs = []
88
- state_steps = []
89
- lr = group["lr"]
90
- beta1, beta2 = group["adamw_betas"]
91
- eps = group["adamw_eps"]
92
- weight_decay = group["weight_decay"]
93
-
94
- for p in params:
95
- g = p.grad
96
- if g is None:
97
- continue
98
- state = optimizer_state[p]
99
- params_with_grads.append(p)
100
- grads.append(g)
101
- if "step" not in state:
102
- state["step"] = (torch.zeros((),
103
- dtype=torch.float32,
104
- device=p.device))
105
- state["moment1"] = torch.zeros_like(g)
106
- state["moment2"] = torch.zeros_like(g)
107
- moment1.append(state["moment1"])
108
- moment2.append(state["moment2"])
109
- if not isinstance(state["step"], torch.Tensor):
110
- step_tensor = torch.tensor(state["step"],
111
- dtype=torch.float32,
112
- device=p.device)
113
- else:
114
- step_tensor = state["step"]
115
- state_steps.append(step_tensor)
116
-
117
- fused_adamw(
118
- params_with_grads,
119
- grads,
120
- moment1,
121
- moment2,
122
- max_exp_avg_sqs,
123
- state_steps,
124
- amsgrad=False,
125
- beta1=beta1,
126
- beta2=beta2,
127
- lr=lr,
128
- weight_decay=weight_decay,
129
- eps=eps,
130
- maximize=False,
131
- )
132
-
133
-
134
- def step_adamw(optimizer_state, group):
135
- """Dispatch AdamW step, grouping parameters by type and placement.
136
-
137
- Args:
138
- optimizer_state: The optimizer's state dict (self.state in Muon).
139
- group: Parameter group dict.
140
- """
141
- params = group["params"]
142
-
143
- # group params with its type and placement
144
- placement_to_params: dict[tuple, list[torch.Tensor]] = defaultdict(list)
145
- for p in params:
146
- match p:
147
- case DTensor():
148
- placement_to_params[tuple([p.placements,
149
- p.device_mesh])].append(p)
150
- case torch.Tensor():
151
- placement_to_params[tuple([torch.Tensor, None])].append(p)
152
-
153
- for group_params in placement_to_params.values():
154
- step_adamw_params(optimizer_state, group_params, group)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/async_utils.py DELETED
@@ -1,77 +0,0 @@
1
- import logging
2
- from typing import Generator
3
-
4
- logger = logging.getLogger(__name__)
5
-
6
-
7
- class _Task:
8
- """Internal: wraps a generator, advances one yield at a time."""
9
-
10
- def __init__(self, generator: Generator[None, None, None], index: int):
11
- self._generator = generator
12
- self._index = index
13
- self._steps_completed = 0
14
- self.step() # run to first yield
15
-
16
- def step(self) -> bool:
17
- try:
18
- next(self._generator)
19
- self._steps_completed += 1
20
- logger.debug("pipeline[%d] completed stage %d", self._index,
21
- self._steps_completed)
22
- return True
23
- except StopIteration:
24
- logger.debug("pipeline[%d] finished after %d stages", self._index,
25
- self._steps_completed)
26
- return False
27
-
28
- def close(self):
29
- self._generator.close()
30
-
31
-
32
- def run_pipeline(
33
- pipelines: Generator[Generator[None, None, None], None, None],
34
- max_concurrent: int,
35
- ) -> None:
36
- """Run generator-based pipelines with bounded concurrency.
37
-
38
- Each pipeline is a generator that yields at stage boundaries.
39
- The runtime interleaves pipelines so communication and computation
40
- overlap across chunks.
41
- """
42
- if max_concurrent <= 0:
43
- raise ValueError(f"max_concurrent must be > 0, got {max_concurrent}")
44
-
45
- have_new = True
46
- task_index = 0
47
- previous_tasks: list[_Task] = []
48
-
49
- try:
50
- while have_new or previous_tasks:
51
- running_tasks: list[_Task] = []
52
-
53
- # Admit one new pipeline per iteration (staggered admission).
54
- # Admitting one at a time ensures that while chunk N does NS
55
- # compute on the default stream, chunk N+1's NCCL all-to-all
56
- # runs concurrently on the NCCL stream — creating real
57
- # communication/computation overlap on the GPU.
58
- if have_new and len(previous_tasks) < max_concurrent:
59
- try:
60
- gen = next(pipelines)
61
- task = _Task(gen, task_index)
62
- task_index += 1
63
- running_tasks.append(task)
64
- except StopIteration:
65
- have_new = False
66
-
67
- # Advance every previously-yielded task by one step.
68
- for task in previous_tasks:
69
- if task.step():
70
- running_tasks.append(task)
71
-
72
- previous_tasks = running_tasks
73
- except BaseException:
74
- # Clean up all in-flight generators to release GPU resources.
75
- for task in previous_tasks:
76
- task.close()
77
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/core.py DELETED
@@ -1,116 +0,0 @@
1
- import math
2
- from dataclasses import dataclass
3
-
4
- import torch
5
- import torch.distributed as dist
6
- from torch.distributed import ProcessGroup
7
- from torch.distributed.tensor import DTensor
8
-
9
-
10
- @dataclass
11
- class _muon_state:
12
- worker_rank: int
13
- process_group: ProcessGroup
14
- rank_indices: dict[int, tuple] # local_rank -> per-dim indices
15
- rank_numels: dict[int, int] # local_rank -> numel
16
- name: str
17
- qk_clip_state: torch.Tensor | None = None
18
-
19
-
20
- def update_g(optimizer_state, p, g, group, momentum):
21
- """Apply momentum update to gradient.
22
-
23
- Args:
24
- optimizer_state: The optimizer's state dict (self.state in Muon).
25
- p: Parameter tensor.
26
- g: Gradient tensor.
27
- group: Parameter group dict.
28
- momentum: Momentum coefficient.
29
-
30
- Returns:
31
- Momentum-updated gradient tensor.
32
- """
33
- state = optimizer_state[p]
34
- buf = state.setdefault("momentum_buffer", torch.zeros_like(g))
35
- torch.add(g, buf, alpha=momentum, out=buf)
36
- if group["nesterov"]:
37
- g.add_(buf, alpha=momentum)
38
- return g
39
- return buf
40
-
41
-
42
- def update_p(p, u, lr, adjusted_lr, weight_decay):
43
- """Apply weight decay and orthogonalized update to parameter.
44
-
45
- Args:
46
- p: Parameter (torch.nn.Parameter or DTensor).
47
- u: Orthogonalized update tensor.
48
- lr: Base learning rate.
49
- adjusted_lr: Size-adjusted learning rate.
50
- weight_decay: Weight decay coefficient.
51
- """
52
- if isinstance(p, torch.nn.Parameter):
53
- # apply weight decay
54
- p.data.mul_(1 - lr * weight_decay)
55
- # apply update
56
- p.data.add_(u, alpha=-adjusted_lr)
57
- else:
58
- p.mul_(1 - lr * weight_decay)
59
- p.add_(u, alpha=-adjusted_lr)
60
-
61
-
62
- def adjust_lr_for_muon(lr, param_shape):
63
- """Scale learning rate based on parameter matrix dimensions.
64
-
65
- Args:
66
- lr: Base learning rate.
67
- param_shape: Shape of the parameter tensor.
68
-
69
- Returns:
70
- Adjusted learning rate.
71
- """
72
- A, B = param_shape[:2]
73
- # We adjust the learning rate and weight decay based on the size of the parameter matrix
74
- # as described in the paper
75
- adjusted_ratio = 0.2 * math.sqrt(max(A, B))
76
- adjusted_lr = lr * adjusted_ratio
77
- return adjusted_lr
78
-
79
-
80
- def default_is_muon(name, x, expert_keys=None):
81
- skip_keys = ["embed_tokens", "lm_head", "tok_embeddings", "output"]
82
- if any(key in name for key in skip_keys):
83
- return False
84
- effective_ndim = x.ndim
85
- if expert_keys and any(key in name for key in expert_keys):
86
- effective_ndim -= 1
87
- return effective_ndim >= 2
88
-
89
-
90
- def get_default_muon_param_groups(model, is_muon_func=None, expert_keys=None):
91
- if is_muon_func is None:
92
- is_muon_func = lambda n, x: default_is_muon(n, x, expert_keys)
93
-
94
- muon_params, muon_names = [], []
95
- non_muon_params = []
96
-
97
- for n, p in model.named_parameters():
98
- if not p.requires_grad:
99
- continue
100
- if is_muon_func(n, p):
101
- muon_params.append(p)
102
- muon_names.append(n)
103
- else:
104
- non_muon_params.append(p)
105
-
106
- return [
107
- {
108
- "params": muon_params,
109
- "names": muon_names,
110
- "use_muon": True,
111
- },
112
- {
113
- "params": non_muon_params,
114
- "use_muon": False,
115
- },
116
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/distributed/utils.py DELETED
@@ -1,234 +0,0 @@
1
- import torch
2
- import torch.distributed as dist
3
- from torch.distributed import ProcessGroup
4
- from torch.distributed.device_mesh import DeviceMesh
5
- from torch.distributed.tensor import DTensor
6
- from torch.distributed.tensor.placement_types import (Placement, Shard,
7
- _StridedShard)
8
-
9
-
10
- def _is_shard(placement: Placement) -> bool:
11
- """Check if a placement is a shard type (Shard or _StridedShard).
12
-
13
- In PyTorch 2.10+, _StridedShard no longer inherits from Shard, so
14
- ``placement.is_shard()`` returns False for _StridedShard. This helper
15
- handles both old and new hierarchies.
16
- """
17
- return isinstance(placement, (Shard, _StridedShard))
18
-
19
-
20
- def get_slices_of_dtensor(
21
- target: DTensor | torch.Tensor,
22
- local_rank: int,
23
- shard_mesh: DeviceMesh,
24
- shard_placements: tuple[Placement],
25
- ) -> tuple[slice | torch.Tensor, ...]:
26
- """
27
- Get per-dimension indices for a given rank's shard of the target tensor.
28
-
29
- Uses ``Shard.local_shard_size_and_offset`` and
30
- ``_StridedShard.local_shard_size_and_offset`` for correct handling of
31
- both contiguous and strided (non-contiguous) sharding.
32
-
33
- Args:
34
- target (DTensor | torch.Tensor): The target tensor (for its shape).
35
- local_rank (int): The local rank within the shard group.
36
- shard_mesh (DeviceMesh): The shard mesh (only shard dimensions).
37
- shard_placements (tuple[Placement]): The shard placements.
38
-
39
- Returns:
40
- A tuple of indices (one per tensor dim). Each element is either:
41
- - A ``slice`` (for contiguous or unsharded dims)
42
- - A 1-D ``torch.LongTensor`` of indices (for strided sharding)
43
- """
44
-
45
- # find the global rank of the local rank in the shard mesh
46
- rank = sorted(shard_mesh.mesh.flatten().tolist())[local_rank]
47
-
48
- rank_coords = (shard_mesh.mesh == rank).nonzero()
49
-
50
- assert len(rank_coords) == 1
51
- rank_coords = tuple(rank_coords[0].tolist())
52
-
53
- assert len(rank_coords) == len(shard_placements)
54
-
55
- # Track per-shard-dim indices.
56
- # None means "not yet sharded on this dim".
57
- dim_indices: dict[int, torch.Tensor] = {}
58
-
59
- # Caution: Assuming replicate-to-shard of the shard mesh goes with
60
- # left-to-right sharding. This is ensured by the sorting logic of
61
- # construct_shard_mesh function.
62
- for mesh_dim_idx, (rank_coord, placement) in enumerate(
63
- zip(rank_coords, shard_placements)):
64
- assert _is_shard(placement)
65
-
66
- num_chunks = shard_mesh.mesh.shape[mesh_dim_idx]
67
- shard_dim = placement.dim
68
-
69
- # Current effective size on this dim (may already be sub-sharded)
70
- if shard_dim in dim_indices:
71
- curr_size = len(dim_indices[shard_dim])
72
- else:
73
- curr_size = target.size()[shard_dim]
74
-
75
- if curr_size % num_chunks != 0:
76
- raise NotImplementedError(
77
- f"Dimension size {curr_size} is not divisible "
78
- f"by number of ranks {num_chunks} for shard "
79
- f"placement on dim {shard_dim}. (shape: {target.shape})")
80
-
81
- # Compute indices for this level of sharding
82
- if isinstance(placement, _StridedShard):
83
- _shard_size, offsets = _StridedShard.local_shard_size_and_offset(
84
- placement,
85
- curr_size,
86
- num_chunks,
87
- rank_coord,
88
- return_first_offset=False)
89
- new_indices = torch.tensor(offsets, dtype=torch.long)
90
- else:
91
- shard_size, offset = Shard.local_shard_size_and_offset(
92
- curr_size, num_chunks, rank_coord)
93
- new_indices = torch.arange(offset,
94
- offset + shard_size,
95
- dtype=torch.long)
96
-
97
- # Compose with previous indices on this dim
98
- if shard_dim in dim_indices:
99
- dim_indices[shard_dim] = dim_indices[shard_dim][new_indices]
100
- else:
101
- dim_indices[shard_dim] = new_indices
102
-
103
- # Build result tuple
104
- result: list[slice | torch.Tensor] = []
105
- for d in range(len(target.size())):
106
- if d not in dim_indices:
107
- result.append(slice(None))
108
- else:
109
- indices = dim_indices[d]
110
- # Convert contiguous indices to slice for efficiency
111
- if len(indices) > 0:
112
- start = indices[0].item()
113
- expected = torch.arange(start,
114
- start + len(indices),
115
- dtype=torch.long)
116
- if torch.equal(indices, expected):
117
- result.append(slice(start, start + len(indices)))
118
- else:
119
- result.append(indices)
120
- else:
121
- result.append(slice(0, 0))
122
-
123
- return tuple(result)
124
-
125
-
126
- _ranks_to_dist_cache: dict[tuple[int, ...], tuple[DeviceMesh,
127
- ProcessGroup]] = dict()
128
-
129
-
130
- def construct_shard_mesh(
131
- placements: tuple[Placement],
132
- mesh: DeviceMesh,
133
- ) -> tuple[DeviceMesh, ProcessGroup, tuple[Placement, ...]]:
134
- """Construct shard sub-mesh and ProcessGroup for all-to-all communication.
135
-
136
- Given a DTensor's placements and device mesh, extracts the "shard group"
137
- — the set of ranks that together hold all shards of the same replica —
138
- and creates a ProcessGroup for all-to-all among them.
139
-
140
- Steps:
141
- 1. Sort placements: Replicate first, then Shard by (dim, granularity).
142
- 2. Permute the mesh tensor to match the sorted order.
143
- 3. Collapse Replicate dims → list of shard sub-meshes (one per replica).
144
- 4. Create/retrieve a cached ProcessGroup for the current rank's sub-mesh.
145
-
146
- Example — 8 GPUs, mesh shape (2, 2, 2),
147
- placements ``[Shard(0), Replicate, _StridedShard(0)]``::
148
-
149
- Step 1 — Sort: [Replicate, _StridedShard(0), Shard(0)]
150
- Permutation: [1, 2, 0]
151
-
152
- Step 2 — Permute mesh dims by [1, 2, 0]:
153
- Original: Permuted:
154
- [[[0,1],[2,3]], [[[0,2],[1,3]],
155
- [[4,5],[6,7]]] [[4,6],[5,7]]]
156
-
157
- Step 3 — Unbind replicate dim (dim 0), giving 2 shard sub-meshes:
158
- sub-mesh 0 = [[0,2],[1,3]] (replica group 0)
159
- sub-mesh 1 = [[4,6],[5,7]] (replica group 1)
160
- shard_placements = (_StridedShard(0), Shard(0))
161
-
162
- Step 4 — Rank 0 → ProcessGroup([0,1,4,5])
163
- Rank 2 → ProcessGroup([2,3,6,7])
164
-
165
- Returns:
166
- ``(shard_mesh, process_group, shard_placements)``
167
- """
168
- my_rank = dist.get_rank()
169
- assert mesh.mesh.device.type == 'cpu'
170
-
171
- # -- Fast path: 1D all-shard mesh → reuse existing PG. ----------------
172
- # This avoids a non-collective dist.new_group() call, which would
173
- # deadlock when only a subset of ranks call this function (e.g. expert
174
- # DTensors on a TP submesh where ranks 0-3 and 4-7 call separately).
175
- if mesh.ndim == 1 and len(placements) == 1 and _is_shard(placements[0]):
176
- key = (*mesh.mesh.shape, *mesh.mesh.flatten().tolist())
177
- if key not in _ranks_to_dist_cache:
178
- _ranks_to_dist_cache[key] = (mesh, mesh.get_group())
179
- return (*_ranks_to_dist_cache[key], tuple(placements))
180
-
181
- mesh_tensor = mesh.mesh.clone()
182
-
183
- # -- Step 1: Sort placements (Replicate first, then Shard by dim). ------
184
- # _StridedShard comes BEFORE regular Shard on the same dim so that
185
- # get_slices_of_dtensor applies the outer sharding first, matching
186
- # DTensor's left-to-right (outer-to-inner) composition order.
187
- def _sort_key(item):
188
- index, placement = item
189
- assert not placement.is_partial(), "Partial placement not supported"
190
- if placement.is_replicate():
191
- return (-1, 0, index)
192
- assert _is_shard(placement), f"Unsupported: {type(placement)}"
193
- split = (-1 / placement.split_factor if isinstance(
194
- placement, _StridedShard) else 0)
195
- return (placement.dim, split, index)
196
-
197
- indexed = sorted(enumerate(placements), key=_sort_key)
198
- perm, sorted_placements = zip(*indexed)
199
-
200
- # -- Step 2: Permute mesh to match sorted placement order. --------------
201
- sorted_mesh = mesh_tensor.permute(perm)
202
-
203
- # -- Step 3: Collapse replicate dims → list of shard sub-meshes. --------
204
- # E.g. mesh (2, 3, 4, 4) with [R, R, S(0), S(1)] → 6 sub-meshes of (4, 4)
205
- num_rep = sum(1 for p in sorted_placements if p.is_replicate())
206
- if num_rep > 0:
207
- if num_rep > 1:
208
- sorted_mesh = sorted_mesh.flatten(0, num_rep - 1)
209
- shard_meshes = list(torch.unbind(sorted_mesh, dim=0))
210
- else:
211
- shard_meshes = [sorted_mesh]
212
- shard_placements = sorted_placements[num_rep:]
213
- assert len(shard_placements) == len(set(shard_placements))
214
-
215
- # -- Step 4: Create/retrieve ProcessGroup for current rank's sub-mesh. --
216
- # All ranks must call dist.new_group in the same order, even though each
217
- # rank only joins one group.
218
- def _cache_key(t: torch.Tensor) -> tuple:
219
- return (*t.shape, *t.flatten().tolist())
220
-
221
- my_key = None
222
- for sm in shard_meshes:
223
- key = _cache_key(sm)
224
- if (my_rank == sm).any().item():
225
- assert my_key is None, "Rank appears in multiple shard groups"
226
- my_key = key
227
- if key not in _ranks_to_dist_cache:
228
- pg = dist.new_group(sm.flatten().tolist())
229
- _ranks_to_dist_cache[key] = (
230
- DeviceMesh(device_type="cuda", mesh=sm),
231
- pg,
232
- )
233
-
234
- return (*_ranks_to_dist_cache[my_key], shard_placements)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/matmul_transpose_triton.py DELETED
@@ -1,121 +0,0 @@
1
- # MIT License
2
- #
3
- # Copyright (c) 2025 Tianyang Lin
4
- #
5
- # Permission is hereby granted, free of charge, to any person obtaining a copy
6
- # of this software and associated documentation files (the "Software"), to deal
7
- # in the Software without restriction, including without limitation the rights
8
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- # copies of the Software, and to permit persons to whom the Software is
10
- # furnished to do so, subject to the following conditions:
11
- #
12
- # The above copyright notice and this permission notice shall be included in all
13
- # copies or substantial portions of the Software.
14
- #
15
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- # SOFTWARE.
22
-
23
- import torch
24
- import triton
25
- import triton.language as tl
26
-
27
-
28
- def get_autotune_config():
29
- return [
30
- triton.Config(
31
- {
32
- 'BLOCK_SIZE_M': blk_m,
33
- 'BLOCK_SIZE_K': blk_k,
34
- 'GROUP_SIZE_M': grp_sz
35
- },
36
- num_stages=n_stages,
37
- num_warps=n_warps) for blk_m in [32, 64, 128]
38
- for blk_k in [32, 64] for grp_sz in [8] for n_stages in [3, 4, 5]
39
- for n_warps in [4, 8]
40
- ]
41
-
42
-
43
- @triton.autotune(
44
- configs=get_autotune_config(),
45
- key=['M', 'K'],
46
- )
47
- @triton.jit
48
- def mmt_kernel(x, y, M, K, stride_xm, stride_xk, stride_ym, stride_yn,
49
- BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
50
- GROUP_SIZE_M: tl.constexpr):
51
- """
52
- Core kernel jit function of matmul_transpose that computes y = x @ x.T
53
- The code is a simple adaptation from the triton `matmul` tutorial:
54
- https://triton-lang.org/main/getting-started/tutorials/03-matrix-multiplication.html
55
- """
56
- pid = tl.program_id(axis=0)
57
- num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
58
- num_pid_n = tl.cdiv(M, BLOCK_SIZE_M)
59
- num_pid_in_group = GROUP_SIZE_M * num_pid_n
60
- group_id = pid // num_pid_in_group
61
- first_pid_m = group_id * GROUP_SIZE_M
62
- group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
63
- pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
64
- pid_n = (pid % num_pid_in_group) // group_size_m
65
- if pid_m > pid_n:
66
- return
67
-
68
- offs_xm = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
69
- offs_xn = (pid_n * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
70
- offs_k = tl.arange(0, BLOCK_SIZE_K)
71
- # we use a & b ptrs to denote different rows of x.
72
- a_ptrs = x + (offs_xm[:, None] * stride_xm + offs_k[None, :] * stride_xk)
73
- b_ptrs = x + (offs_xn[:, None] * stride_xm + offs_k[None, :] * stride_xk)
74
-
75
- accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_M), dtype=tl.float32)
76
-
77
- for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
78
- a = tl.load(a_ptrs,
79
- mask=offs_k[None, :] < K - k * BLOCK_SIZE_K,
80
- other=0.0)
81
- b = tl.load(b_ptrs,
82
- mask=offs_k[None, :] < K - k * BLOCK_SIZE_K,
83
- other=0.0)
84
- accumulator = tl.dot(a, tl.permute(b, (1, 0)), accumulator)
85
- a_ptrs += BLOCK_SIZE_K * stride_xk
86
- b_ptrs += BLOCK_SIZE_K * stride_xk
87
- # use dtype.element_ty to accommodate different input datatypes as in cpp templates
88
- # https://github.com/triton-lang/triton/issues/2252
89
- c = accumulator.to(x.dtype.element_ty)
90
-
91
- offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
92
- offs_cn = pid_n * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
93
- c_ptrs = y + stride_ym * offs_cm[:, None] + stride_yn * offs_cn[None, :]
94
- c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < M)
95
- tl.store(c_ptrs, c, mask=c_mask)
96
-
97
- # transpose and copy
98
- if pid_m < pid_n:
99
- ct_ptrs = y + stride_ym * offs_cn[:,
100
- None] + stride_yn * offs_cm[None, :]
101
- ct_mask = (offs_cn[:, None] < M) & (offs_cm[None, :] < M)
102
- tl.store(ct_ptrs, tl.permute(c, (1, 0)), mask=ct_mask)
103
-
104
-
105
- def matmul_transpose_assign(d_in, d_out):
106
- assert d_in.is_cuda, "Input `d_in` must be a CUDA tensor"
107
- assert d_out.is_cuda, "Input `d_out` must be a CUDA tensor"
108
- assert d_in.device == d_out.device, "Inputs `d_in` and `d_out` must be on the same CUDA device"
109
- assert d_in.dtype == d_out.dtype, "Inputs must have the same data type"
110
- assert d_in.ndim == 2, "Input `d_in` must be a 2D tensor"
111
- assert d_out.ndim == 2, "Input `d_out` must be a 2D tensor"
112
- assert d_in.size(0) == d_out.size(0) == d_out.size(0), \
113
- "First dimension of `d_in` must match first and second dimension of `d_out`"
114
-
115
- d_in = d_in.contiguous()
116
- M, K = d_in.shape
117
- grid = lambda META: (triton.cdiv(M, META['BLOCK_SIZE_M']) * triton.cdiv(
118
- M, META['BLOCK_SIZE_M']), )
119
- with torch.cuda.device(d_in.device.index):
120
- mmt_kernel[grid](d_in, d_out, M, K, d_in.stride(0), d_in.stride(1),
121
- d_out.stride(0), d_out.stride(1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/metadata.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "python-depends": []
3
- }
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/muon.py DELETED
@@ -1,594 +0,0 @@
1
- import logging
2
- import types
3
- from collections import defaultdict
4
- from typing import Any
5
-
6
- import torch
7
- import torch.distributed as dist
8
- from torch.distributed.tensor import DTensor, Replicate, Shard
9
- from torch.profiler import record_function
10
-
11
- from .adamw import step_adamw
12
- from .async_utils import run_pipeline
13
- from .core import (_muon_state, adjust_lr_for_muon,
14
- get_default_muon_param_groups, update_g, update_p)
15
- from .distributed.utils import (_is_shard, construct_shard_mesh,
16
- get_slices_of_dtensor)
17
- from .newton_schulz import (COMM_DTYPE, DEFAULT_CHUNK_SIZE_RATIO,
18
- _zeropower_via_newtonschulz5)
19
- from .pipeline import muon_chunk_pipeline
20
- from .qk_clip import compute_scales, get_qk_clip_info, qk_clip
21
-
22
- logger = logging.getLogger(__name__)
23
-
24
-
25
- def _expand_expert_params(names, params, expert_keys):
26
- """Expand expert params by splitting on dim 0 (expert dimension).
27
-
28
- Params whose name matches any key in ``expert_keys`` are treated as
29
- expert-parallel tensors. Their outermost dimension is the expert
30
- dimension: an ``(E, out, in)`` tensor becomes ``E`` separate 2D
31
- ``nn.Parameter`` views so that in-place updates propagate back to
32
- the original storage.
33
-
34
- Non-expert params with ``ndim > 2`` trigger an ``AssertionError`` —
35
- if they are expert params, their key must be added to ``expert_keys``.
36
-
37
- The grad must already be set on each expert param (e.g. after momentum).
38
-
39
- For DTensor expert params, placements that shard on dim 0 (expert dim)
40
- are consumed by the split. Non-dim-0 shard placements (e.g. TP) are
41
- preserved: each 2D slice is wrapped as a DTensor on the corresponding
42
- submesh so the parallel pipeline handles the TP communication.
43
- """
44
- expanded_names = []
45
- expanded_params = []
46
-
47
- for n, p in zip(names, params):
48
- is_expert = expert_keys and any(key in n for key in expert_keys)
49
- is_dtensor = isinstance(p.data, DTensor)
50
-
51
- if not is_expert:
52
- assert p.data.ndim <= 2, (
53
- f"Param {n} has ndim={p.data.ndim} but does not match "
54
- f"expert_keys={expert_keys}. If this is an expert param, "
55
- f"add its key to expert_keys.")
56
- expanded_names.append(n)
57
- expanded_params.append(p)
58
- continue
59
-
60
- g = p.grad
61
- assert g is not None, (
62
- f"Expert param {n} must have grad set before expansion")
63
-
64
- tp_mesh = None
65
- tp_placements_2d = None
66
-
67
- if is_dtensor:
68
- local_data = p.to_local()
69
- local_grad = g.to_local() if isinstance(g, DTensor) else g
70
-
71
- # Find non-dim-0 shard placements (e.g. TP sharding).
72
- # After splitting on dim 0, Shard(k) becomes Shard(k-1).
73
- tp_dim_indices = []
74
- tp_placements_2d = []
75
- for i, pl in enumerate(p.placements):
76
- if _is_shard(pl) and pl.dim != 0:
77
- tp_dim_indices.append(i)
78
- tp_placements_2d.append(Shard(pl.dim - 1))
79
-
80
- if tp_dim_indices:
81
- tp_dim_names = tuple(p.device_mesh.mesh_dim_names[i]
82
- for i in tp_dim_indices)
83
- if len(tp_dim_names) == 1:
84
- tp_mesh = p.device_mesh[tp_dim_names[0]]
85
- else:
86
- tp_mesh = p.device_mesh[tp_dim_names]
87
- else:
88
- local_data = p.data
89
- local_grad = g
90
-
91
- # Expand: split dim 0, reshape each slice to 2D.
92
- num_local_experts = local_data.shape[0]
93
- for i in range(num_local_experts):
94
- slice_data = local_data[i]
95
- slice_grad = local_grad[i]
96
-
97
- if tp_mesh is not None:
98
- # Wrap as DTensor on TP submesh so the pipeline handles
99
- # TP communication (gather/scatter across TP ranks).
100
- dt_data = DTensor.from_local(slice_data,
101
- device_mesh=tp_mesh,
102
- placements=tp_placements_2d)
103
- dt_grad = DTensor.from_local(slice_grad,
104
- device_mesh=tp_mesh,
105
- placements=tp_placements_2d)
106
- expert_param = torch.nn.Parameter(dt_data, requires_grad=False)
107
- expert_param.grad = dt_grad
108
- else:
109
- expert_param = torch.nn.Parameter(slice_data,
110
- requires_grad=False)
111
- expert_param.grad = slice_grad
112
-
113
- expanded_names.append(f"{n}[{i}]")
114
- expanded_params.append(expert_param)
115
-
116
- p.grad = None # allow expert grad storage to be freed after pipeline
117
-
118
- return expanded_names, expanded_params
119
-
120
-
121
- class Muon(torch.optim.Optimizer):
122
- """
123
- Muon - MomentUm Orthogonalized by Newton-schulz
124
-
125
- Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-
126
- processing step, in which each 2D parameter's update is replaced with the nearest orthogonal
127
- matrix. To efficiently orthogonalize each update, we use a Newton-Schulz iteration, which has
128
- the advantage that it can be stably run in bfloat16 on the GPU.
129
-
130
- Some warnings:
131
- - We believe this optimizer is unlikely to work well for training with small batch size.
132
- - We believe it may not work well for finetuning pretrained models, but we haven't tested this.
133
-
134
- Arguments:
135
- model: The model to be optimized by Muon.
136
- is_muon_func: A function that takes a parameter and its name, and returns whether the parameter should be optimized by Muon.
137
- lr: The learning rate. The updates will have spectral norm of `lr`. (0.02 is a good default)
138
- momentum: The momentum used by the internal SGD. (0.95 is a good default)
139
- nesterov: Whether to use Nesterov-style momentum in the internal SGD. (recommended)
140
- ns_steps: The number of Newton-Schulz iterations to run. (6 is probably always enough)
141
- weight_decay: The weight decay for Muon and AdamW.
142
- Parameters that are {0, 1}-D or are detected as being the embed or lm_head will be optimized by AdamW instead.
143
- adamw_lr: The learning rate for the internal AdamW.
144
- adamw_betas: The betas for the internal AdamW.
145
- adamw_eps: The epsilon for the internal AdamW.
146
- none_grad: Whether to set p.grad to None after gathering the gradients. This can save memory.
147
- debug: Whether to print debug information.
148
- clip_info : Configuration for QK clipping. Expected keys:
149
- - "q_indices" (list[int]): Indices of query heads to consider.
150
- - "k_indices" (list[int]): Indices of key heads to consider.
151
- - "head_dim" (int): Dimensionality of each attention head.
152
- - "threshold" (float): Threshold value; heads whose QK logits exceed
153
- this value will be scaled down.
154
- Default is:
155
- {
156
- "q_indices": [],
157
- "k_indices": [],
158
- "head_dim": 128,
159
- "threshold": 100
160
- }
161
- warmup_step : How many all2all gather, compute operations are launched in advance
162
- before the corresponding all2all scatter steps begin.
163
- A higher warmup_step increases memory usage but can improve
164
- performance by overlapping communication.
165
- Parallel muon only.
166
- chunk_size : Batch size of parameters to process in each
167
- all2all gather/compute/scatter step.
168
- Use shard ranks * DEFAULT_CHUNK_SIZE_RATIO when -1 is specified.
169
- use_distributed_muon: Use distributed muon by Liu et al. (2024).
170
- For testing purpose only.
171
- small_param_numel_threshold: Threshold for classifying parameters as small and falling back to distributed Muon
172
- expert_keys: List of strings to identify expert-parallel parameters.
173
- If any key appears in a parameter's name, its outermost
174
- dimension is treated as the expert dimension and expanded
175
- into per-expert 2D params for Muon. For example,
176
- ``expert_keys=["experts"]`` matches any param whose name
177
- contains "experts". 3D+ params not matched by any key
178
- will raise an error.
179
- """
180
-
181
- def __init__(self,
182
- params,
183
- lr=1e-3,
184
- momentum=0.95,
185
- nesterov=True,
186
- ns_steps=5,
187
- weight_decay=0.1,
188
- adamw_betas=(0.9, 0.95),
189
- adamw_eps=1e-8,
190
- none_grad=True,
191
- debug=False,
192
- clip_config=None,
193
- warmup_step=5,
194
- chunk_size=-1,
195
- use_distributed_muon=False,
196
- small_param_numel_threshold=65536,
197
- expert_keys=None):
198
- defaults = dict(
199
- lr=lr,
200
- weight_decay=weight_decay,
201
- momentum=momentum,
202
- nesterov=nesterov,
203
- ns_steps=ns_steps,
204
- adamw_betas=adamw_betas,
205
- adamw_eps=adamw_eps,
206
- none_grad=none_grad,
207
- use_muon=True,
208
- )
209
- error_message = "The key 'use_muon' is not set in parameter group {idx}. Assuming all parameters in the group will use muon optimization, which may lead to unexpected behavior."
210
- instruction_code = "\n\n please follow this code snippet \n```optimizer = get_kernel('motif-technologies/optimizer')\n\n\nparams = optimizer.muon.get_default_muon_param_groups(model)\n\noptim = optimizer.Muon(params, ...)```"
211
-
212
- if isinstance(params, types.GeneratorType):
213
- raise ValueError(error_message.format(idx=0) + instruction_code)
214
- for _idx, param_group in enumerate(params):
215
- if param_group.get("use_muon", None) is None:
216
- raise ValueError(
217
- error_message.format(idx=_idx) + instruction_code)
218
-
219
- super().__init__(params, defaults)
220
-
221
- self.debug = debug
222
- self.clip_config = clip_config if clip_config is not None else {
223
- "q_indices": [],
224
- "k_indices": [],
225
- "head_dim": 128,
226
- "threshold": 100,
227
- }
228
- self.warmup_step = warmup_step
229
- self.chunk_size = chunk_size
230
- self.use_distributed_muon = use_distributed_muon
231
- self.small_param_numel_threshold = small_param_numel_threshold
232
- self.expert_keys = expert_keys
233
-
234
- def _calc_flops(self, G, steps):
235
- assert len(G.shape) == 2
236
- M, N = G.shape
237
- if M > N:
238
- M, N = N, M
239
-
240
- return steps * ((M**3) * 2 + (M**2 * N) * 4 + M * N * 2 + M**2 * 3)
241
-
242
- def get_shard_mesh(self, p):
243
- """
244
- Get the shard mesh for a parameter p on the given rank.
245
- """
246
- assert isinstance(
247
- p, DTensor), "Parallel Muon only supports DTensor parameters."
248
-
249
- shard_mesh, shard_pg, shard_placements = construct_shard_mesh(
250
- p.placements, p.device_mesh)
251
-
252
- return shard_mesh, shard_pg, shard_placements
253
-
254
- def init_state_and_assign_params(self, names, params, group, qk_logits):
255
- param_to_state = {}
256
- param_to_flops = {}
257
-
258
- total_flops = 0
259
- for p in params:
260
- g = p.grad
261
- if g is None:
262
- continue
263
- assert g.ndim == 2, "Muon only supports 2D parameters."
264
-
265
- flops = self._calc_flops(g, group["ns_steps"])
266
- param_to_flops[id(p)] = flops
267
- total_flops += flops
268
-
269
- if self.debug:
270
- logger.debug("Total TFLOPs for Muon: %.2f TFLOPs",
271
- total_flops / 1e12)
272
-
273
- paired = list(zip(names, params))
274
-
275
- paired_sorted = sorted(paired,
276
- key=lambda x: param_to_flops[id(x[1])],
277
- reverse=True)
278
-
279
- names_sorted, params_sorted = zip(*paired_sorted)
280
- ordered_names = list(names_sorted)
281
- ordered_params = list(params_sorted)
282
-
283
- round_robin = 0
284
- mesh = ordered_params[0].device_mesh
285
- placements = ordered_params[0].placements
286
-
287
- shard_mesh, shard_pg, shard_placements = self.get_shard_mesh(
288
- ordered_params[0])
289
- shard_mesh_flattened = shard_mesh.mesh.flatten()
290
- num_ranks = dist.get_world_size(group=shard_pg)
291
-
292
- for n, p in zip(ordered_names, ordered_params):
293
- if mesh != p.device_mesh:
294
- raise ValueError("All parameters must be on the same mesh.")
295
- if placements != p.placements:
296
- raise ValueError("All parameters must have same placements.")
297
-
298
- worker_rank = shard_mesh_flattened[round_robin].item() % num_ranks
299
- round_robin = (round_robin + 1) % len(shard_mesh_flattened)
300
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
301
-
302
- # Precompute per-rank indices and numels for all-to-all.
303
- rank_indices: dict[int, tuple] = {}
304
- rank_numels: dict[int, int] = {}
305
- for r in range(num_ranks):
306
- indices = get_slices_of_dtensor(p, r, shard_mesh,
307
- shard_placements)
308
- rank_indices[r] = indices
309
- numel = 1
310
- for idx, dim_size in zip(indices, p.shape):
311
- if isinstance(idx, slice):
312
- start, stop, step = idx.indices(dim_size)
313
- numel *= max(0, (stop - start + (step - 1)) // step)
314
- else:
315
- numel *= len(idx)
316
- rank_numels[r] = numel
317
-
318
- param_to_state[id(p)] = _muon_state(
319
- worker_rank=worker_rank,
320
- process_group=shard_pg,
321
- rank_indices=rank_indices,
322
- rank_numels=rank_numels,
323
- name=n,
324
- qk_clip_state=qk_clip_state,
325
- )
326
-
327
- return param_to_state, ordered_params
328
-
329
- def base(self, names, params, group, lr, weight_decay, qk_logits):
330
- # Momentum is already applied by _step_muon before this method.
331
- for n, p in zip(names, params):
332
- g = p.grad
333
- if g is None:
334
- continue
335
-
336
- u = _zeropower_via_newtonschulz5(g.to(COMM_DTYPE),
337
- steps=group["ns_steps"])
338
-
339
- adjusted_lr = adjust_lr_for_muon(lr, p.shape)
340
- update_p(p, u, lr, adjusted_lr, weight_decay)
341
-
342
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
343
-
344
- scales_full = compute_scales(
345
- p, qk_clip_state) if qk_clip_state is not None else None
346
- if scales_full is not None:
347
- qk_clip(p, scales_full, qk_clip_state.head_dim)
348
-
349
- def distributed_muon(
350
- self,
351
- names: list[str],
352
- params: list[torch.nn.Parameter],
353
- group: dict[str, Any],
354
- lr: float,
355
- weight_decay: float,
356
- qk_logits: list[torch.Tensor | DTensor] | None,
357
- ):
358
- """ Implementation of Distributed Muon by Liu et al. """
359
-
360
- # Momentum is already applied by _step_muon before this method.
361
- for n, p in zip(names, params):
362
- g = p.grad
363
- if g is None:
364
- continue
365
-
366
- # Gather G
367
- if isinstance(p.data, DTensor):
368
- g_full = g.full_tensor()
369
- p_full = p.data.full_tensor()
370
- else:
371
- g_full = g
372
- p_full = p
373
-
374
- u_full = _zeropower_via_newtonschulz5(g_full.to(COMM_DTYPE),
375
- steps=group["ns_steps"])
376
-
377
- adjusted_lr = adjust_lr_for_muon(lr, p_full.shape)
378
- update_p(p_full, u_full, lr, adjusted_lr, weight_decay)
379
-
380
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
381
-
382
- scales_full = compute_scales(
383
- p_full, qk_clip_state) if qk_clip_state is not None else None
384
-
385
- if scales_full is not None:
386
- qk_clip(p_full, scales_full, qk_clip_state.head_dim)
387
-
388
- if isinstance(p.data, DTensor):
389
- ndims = len(p.device_mesh.mesh.shape)
390
- p_replicate = DTensor.from_local(
391
- p_full,
392
- device_mesh=p.device_mesh,
393
- placements=[Replicate() for _ in range(ndims)],
394
- )
395
-
396
- p_sharded = p_replicate.redistribute(
397
- device_mesh=p.device_mesh,
398
- placements=p.placements,
399
- )
400
-
401
- p.copy_(p_sharded)
402
-
403
- def parallel(self, names, params, group, lr, weight_decay, qk_logits):
404
- """
405
- Perform a parallel optimization step using Muon.
406
-
407
- Parameters are chunked and each chunk is processed by a
408
- :func:`muon_chunk_pipeline` generator. :func:`run_pipeline`
409
- interleaves multiple chunks so that communication and computation
410
- overlap across chunks (the same overlap previously achieved by the
411
- warmup + main-loop index scheduling).
412
- """
413
-
414
- # Momentum is already applied by _step_muon before this method.
415
-
416
- param_to_state, ordered_params = self.init_state_and_assign_params(
417
- names, params, group, qk_logits)
418
-
419
- # Compute local rank for this group's shard process group.
420
- shard_pg = param_to_state[id(ordered_params[0])].process_group
421
- rank = dist.get_rank(group=shard_pg)
422
-
423
- if self.chunk_size == -1:
424
- shard_ranks = dist.get_world_size(param_to_state[id(
425
- ordered_params[0])].process_group)
426
- chunk_size = shard_ranks * DEFAULT_CHUNK_SIZE_RATIO
427
- elif self.chunk_size > 0:
428
- chunk_size = self.chunk_size
429
- else:
430
- raise ValueError("chunk_size must be -1 or a positive integer.")
431
-
432
- def pipelines():
433
- for start in range(0, len(ordered_params), chunk_size):
434
- chunk = ordered_params[start:start + chunk_size]
435
- if chunk:
436
- yield muon_chunk_pipeline(
437
- params=chunk,
438
- param_to_state=param_to_state,
439
- rank=rank,
440
- ns_steps=group["ns_steps"],
441
- lr=lr,
442
- weight_decay=weight_decay,
443
- none_grad=group["none_grad"],
444
- )
445
-
446
- with record_function("muon::barrier"):
447
- dist.barrier()
448
- with record_function("muon::pipeline"):
449
- run_pipeline(pipelines(), max_concurrent=self.warmup_step + 1)
450
-
451
- def _step_muon(self, group, qk_logits=None):
452
- params = group["params"]
453
- lr = group["lr"]
454
- weight_decay = group["weight_decay"]
455
- momentum = group["momentum"]
456
- names = group["names"]
457
-
458
- # Apply momentum to all params before routing/expansion.
459
- with record_function("muon::momentum"):
460
- for n, p in zip(names, params):
461
- g = p.grad
462
- if g is None:
463
- continue
464
- g = update_g(self.state, p, g, group, momentum)
465
- p.grad = g
466
-
467
- # Expand expert params by splitting on dim 0.
468
- names, params = _expand_expert_params(names, params, self.expert_keys)
469
-
470
- param_dtensors = []
471
- name_dtensors = []
472
-
473
- param_tensors = []
474
- name_tensors = []
475
-
476
- param_dtensors_small = []
477
- name_dtensors_small = []
478
-
479
- if self.use_distributed_muon:
480
- self.distributed_muon(names=names,
481
- params=params,
482
- group=group,
483
- lr=lr,
484
- weight_decay=weight_decay,
485
- qk_logits=qk_logits)
486
- return
487
-
488
- # For simplicity, we use distributed Muon for small parameters
489
- # whose number of elements is below a threshold.
490
- for n, p in zip(names, params):
491
- if p is None or p.grad is None:
492
- continue
493
- if isinstance(p.data, DTensor):
494
- if all(
495
- isinstance(placement, Replicate)
496
- for placement in p.placements):
497
- param_tensors.append(p)
498
- name_tensors.append(n)
499
- elif p.data.numel() <= self.small_param_numel_threshold:
500
- param_dtensors_small.append(p)
501
- name_dtensors_small.append(n)
502
- else:
503
- param_dtensors.append(p)
504
- name_dtensors.append(n)
505
- elif isinstance(p.data, torch.Tensor):
506
- param_tensors.append(p)
507
- name_tensors.append(n)
508
- else:
509
- raise TypeError(f"Unsupported parameter type: {type(p.data)}")
510
-
511
- logger.debug(
512
- f"[Muon] {len(param_dtensors)} DTensors, {len(param_tensors)} Tensors, "
513
- f"{len(param_dtensors_small)} Small DTensors")
514
-
515
- def group_dtensors(dtensors, names):
516
- # To support different placements, we group parameters by placements
517
- # and run parallel Muon on each group.
518
-
519
- placement_to_params = defaultdict(lambda: ([], []))
520
-
521
- assert len(dtensors) == len(names)
522
- for p, n in zip(dtensors, names):
523
- placement_to_params[tuple([p.placements,
524
- p.device_mesh])][0].append(n)
525
- placement_to_params[tuple([p.placements,
526
- p.device_mesh])][1].append(p)
527
- return placement_to_params
528
-
529
- if len(param_dtensors_small) > 0:
530
- if not dist.is_initialized():
531
- raise RuntimeError(
532
- "Parallel Muon requires torch.distributed to be initialized."
533
- )
534
-
535
- self.distributed_muon(
536
- params=param_dtensors_small,
537
- names=name_dtensors_small,
538
- group=group,
539
- lr=lr,
540
- weight_decay=weight_decay,
541
- qk_logits=qk_logits,
542
- )
543
-
544
- if len(param_dtensors) > 0:
545
- if not dist.is_initialized():
546
- raise RuntimeError(
547
- "Parallel Muon requires torch.distributed to be initialized."
548
- )
549
-
550
- dtensor_group = group_dtensors(param_dtensors, name_dtensors)
551
- for _, (names, params) in dtensor_group.items():
552
- self.parallel(
553
- names,
554
- params,
555
- group,
556
- lr=lr,
557
- weight_decay=weight_decay,
558
- qk_logits=qk_logits,
559
- )
560
-
561
- if len(param_tensors) > 0:
562
- self.base(
563
- name_tensors,
564
- param_tensors,
565
- group,
566
- lr=lr,
567
- weight_decay=weight_decay,
568
- qk_logits=qk_logits,
569
- )
570
-
571
- @torch.no_grad
572
- def step(self, closure=None, qk_logits=None):
573
- """Perform a single optimization step.
574
-
575
- Args:
576
- closure (Callable, optional): A closure that reevaluates the model
577
- and returns the loss.
578
- qk_logits (dict[int, Tensor], optional): A dictionary mapping layer indices
579
- to 1D tensors of shape (num_heads,), representing the maximum
580
- QK logits across all tokens, computed as
581
- (1 / sqrt(head_dim)) * (Q @ K^T).
582
- """
583
- loss = None
584
- if closure is not None:
585
- with torch.enable_grad():
586
- loss = closure()
587
-
588
- for group in self.param_groups:
589
- if group["use_muon"]:
590
- self._step_muon(group, qk_logits=qk_logits)
591
- else:
592
- step_adamw(self.state, group)
593
-
594
- return loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/newton_schulz.py DELETED
@@ -1,50 +0,0 @@
1
- import torch
2
-
3
- from .matmul_transpose_triton import matmul_transpose_assign
4
-
5
- COMM_DTYPE = torch.bfloat16
6
- DEFAULT_CHUNK_SIZE_RATIO = 4
7
-
8
-
9
- # This code snippet is a modified version adapted from the following GitHub repositories:
10
- # https://github.com/KellerJordan/Muon/blob/master/muon.py
11
- # Muon's Newton–Schulz iteration causes high variance in singular values
12
- # Idea: give each iteration its own 3 coefficients and optimize them via gradient descent.
13
- @torch.no_grad()
14
- # matmul_transpose_assign from : https://github.com/nil0x9/flash-muon
15
- def _zeropower_via_newtonschulz5(G, steps):
16
- """
17
- Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a
18
- quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose
19
- of minimizing steps, it turns out to be empirically effective to keep increasing the slope at
20
- zero even beyond the point where the iteration no longer converges all the way to one everywhere
21
- on the interval. This iteration therefore does not produce UV^T but rather something like US'V^T
22
- where S' is diagonal with S_{ii}' ~ Uniform(0.5, 1.5), which turns out not to hurt model
23
- performance at all relative to UV^T, where USV^T = G is the SVD.
24
- """
25
- assert len(G.shape) == 2
26
- assert G.dtype == COMM_DTYPE
27
- X = G # no manual typecast
28
-
29
- if G.size(0) > G.size(1):
30
- X = X.T
31
- # Ensure spectral norm is at most 1
32
- X = X / (X.norm() + 1e-7)
33
- buf1 = torch.empty(X.size(0), X.size(0), dtype=X.dtype, device=X.device)
34
- buf2 = torch.empty(X.size(0), X.size(0), dtype=X.dtype, device=X.device)
35
- # Perform the NS iterations
36
- for a, b, c in [
37
- (4.0848, -6.8946, 2.9270),
38
- (3.9505, -6.3029, 2.6377),
39
- (3.7418, -5.5913, 2.3037),
40
- (2.8769, -3.1427, 1.2046),
41
- (2.8366, -3.0525, 1.2012),
42
- ]:
43
- matmul_transpose_assign(X, buf1)
44
- matmul_transpose_assign(buf1, buf2)
45
- buf1.mul_(b).add_(buf2, alpha=c)
46
- X = torch.addmm(X, buf1, X, alpha=1.0, beta=a)
47
-
48
- if G.size(0) > G.size(1):
49
- X = X.T
50
- return X
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/optimizer/__init__.py DELETED
@@ -1,26 +0,0 @@
1
- import ctypes
2
- import sys
3
-
4
- import importlib
5
- from pathlib import Path
6
- from types import ModuleType
7
-
8
- def _import_from_path(file_path: Path) -> ModuleType:
9
- # We cannot use the module name as-is, after adding it to `sys.modules`,
10
- # it would also be used for other imports. So, we make a module name that
11
- # depends on the path for it to be unique using the hex-encoded hash of
12
- # the path.
13
- path_hash = "{:x}".format(ctypes.c_size_t(hash(file_path.absolute())).value)
14
- module_name = path_hash
15
- spec = importlib.util.spec_from_file_location(module_name, file_path)
16
- if spec is None:
17
- raise ImportError(f"Cannot load spec for {module_name} from {file_path}")
18
- module = importlib.util.module_from_spec(spec)
19
- if module is None:
20
- raise ImportError(f"Cannot load module {module_name} from spec")
21
- sys.modules[module_name] = module
22
- spec.loader.exec_module(module) # type: ignore
23
- return module
24
-
25
-
26
- globals().update(vars(_import_from_path(Path(__file__).parent.parent / "__init__.py")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/pipeline.py DELETED
@@ -1,390 +0,0 @@
1
- import logging
2
- from typing import Generator
3
-
4
- import torch
5
- import torch.distributed as dist
6
- from torch.distributed.tensor import DTensor
7
- from torch.profiler import record_function
8
-
9
- from .core import _muon_state, adjust_lr_for_muon, update_p
10
- from .newton_schulz import COMM_DTYPE, _zeropower_via_newtonschulz5
11
- from .qk_clip import compute_scales
12
-
13
- logger = logging.getLogger(__name__)
14
-
15
- # ======================================================================
16
- # Stage helpers
17
- # ======================================================================
18
-
19
-
20
- def _launch_gather(
21
- params: list[DTensor],
22
- owned_params: list[DTensor],
23
- param_to_state: dict[int, _muon_state],
24
- rank: int,
25
- num_ranks: int,
26
- process_group: dist.ProcessGroup,
27
- ) -> tuple[dist.Work, torch.Tensor, dict[int, torch.Tensor | None], list[int]]:
28
- """Allocate gather buffers, build send/recv, and launch async all-to-all.
29
-
30
- Returns:
31
- work: Async operation handle.
32
- recv_buf: Flat receive buffer (needed by ``_complete_gather``).
33
- gathered_grads: ``{id(p): empty_tensor}`` for owned params,
34
- ``None`` for non-owned.
35
- recv_counts: Per-source-rank element counts.
36
- """
37
- # Allocate gathered-grad buffers
38
- gathered_grads: dict[int, torch.Tensor | None] = {}
39
- for p in params:
40
- state = param_to_state[id(p)]
41
- if rank == state.worker_rank:
42
- gathered_grads[id(p)] = torch.empty(p.shape,
43
- dtype=COMM_DTYPE,
44
- device="cuda")
45
- else:
46
- gathered_grads[id(p)] = None
47
-
48
- # Build send buffer
49
- per_dst: list[list[torch.Tensor]] = [[] for _ in range(num_ranks)]
50
- send_counts = [0] * num_ranks
51
-
52
- for p in params:
53
- state = param_to_state[id(p)]
54
- dst = state.worker_rank
55
- assert dst < num_ranks
56
- shard_elems = state.rank_numels[rank]
57
- g = p.grad
58
- g = g.to_local().to(COMM_DTYPE).contiguous()
59
- assert g.numel() == shard_elems
60
- per_dst[dst].append(g.view(-1))
61
- send_counts[dst] += shard_elems
62
-
63
- assert any(
64
- len(v) > 0 for v in
65
- per_dst), "At least one destination rank must receive a sharded tensor"
66
- per_dst_flat = [t for dst in per_dst for t in dst]
67
- send_buf = torch.cat(per_dst_flat, dim=0)
68
-
69
- # Build recv buffer
70
- recv_counts = [0] * num_ranks
71
- for src in range(num_ranks):
72
- total = 0
73
- for p in owned_params:
74
- state = param_to_state[id(p)]
75
- assert state.worker_rank == rank
76
- total += state.rank_numels[src]
77
- recv_counts[src] = total
78
-
79
- recv_buf = torch.empty(sum(recv_counts), dtype=COMM_DTYPE, device="cuda")
80
-
81
- # Launch async all-to-all
82
- logger.debug(f"send_buf size: {send_buf.numel()}, "
83
- f"recv_buf size: {recv_buf.numel()}, "
84
- f"recv_counts: {recv_counts}, "
85
- f"send_counts: {send_counts}, "
86
- f"process_group: {str(process_group)}")
87
- work = dist.all_to_all_single(
88
- recv_buf,
89
- send_buf,
90
- output_split_sizes=recv_counts,
91
- input_split_sizes=send_counts,
92
- group=process_group,
93
- async_op=True,
94
- )
95
-
96
- return work, recv_buf, gathered_grads, recv_counts
97
-
98
-
99
- def _complete_gather(
100
- recv_buf: torch.Tensor,
101
- recv_counts: list[int],
102
- owned_params: list[DTensor],
103
- gathered_grads: dict[int, torch.Tensor | None],
104
- param_to_state: dict[int, _muon_state],
105
- rank: int,
106
- ) -> None:
107
- """Reconstruct gathered grads from the recv buffer (in-place)."""
108
- off = 0
109
- for src in range(len(recv_counts)):
110
- if recv_counts[src] == 0:
111
- continue
112
-
113
- block = recv_counts[src]
114
- inner_off = 0
115
- for p in owned_params:
116
- state = param_to_state[id(p)]
117
- assert state.worker_rank == rank
118
-
119
- indices = state.rank_indices[src]
120
-
121
- shard_view = gathered_grads[id(p)][indices]
122
- n = shard_view.numel()
123
- assert n > 0
124
-
125
- sg = recv_buf.narrow(0, off + inner_off, n)
126
- sg = sg.reshape(shard_view.shape)
127
- gathered_grads[id(p)][indices] = sg
128
-
129
- inner_off += n
130
- assert inner_off == block
131
- off += block
132
-
133
-
134
- def _compute_ns(
135
- owned_params: list[DTensor],
136
- gathered_grads: dict[int, torch.Tensor | None],
137
- ns_steps: int,
138
- ) -> dict[int, torch.Tensor | None]:
139
- """Run Newton-Schulz orthogonalization on owned parameters.
140
-
141
- Returns:
142
- computed_us: ``{id(p): orthogonalized_update}`` for owned params.
143
- """
144
- computed_us: dict[int, torch.Tensor | None] = {}
145
- for p in owned_params:
146
- u = _zeropower_via_newtonschulz5(gathered_grads[id(p)], ns_steps)
147
- gathered_grads[id(p)] = None # free gathered grad
148
- computed_us[id(p)] = u
149
- return computed_us
150
-
151
-
152
- def _launch_scatter(
153
- params: list[DTensor],
154
- owned_params: list[DTensor],
155
- param_to_state: dict[int, _muon_state],
156
- rank: int,
157
- num_ranks: int,
158
- process_group: dist.ProcessGroup,
159
- computed_us: dict[int, torch.Tensor | None],
160
- ) -> tuple[dist.Work, torch.Tensor, dict[int, torch.Tensor], list[int]]:
161
- """Allocate scatter buffers, build send/recv, and launch async all-to-all.
162
-
163
- Returns:
164
- work: Async operation handle.
165
- recv_buf: Flat receive buffer (needed by ``_complete_scatter``).
166
- scattered_us: ``{id(p): empty_local_tensor}`` for all params.
167
- recv_counts: Per-source-rank element counts.
168
- """
169
- # Allocate scattered-u buffers
170
- scattered_us: dict[int, torch.Tensor] = {}
171
- for p in params:
172
- scattered_us[id(p)] = torch.empty_like(p.to_local(), dtype=COMM_DTYPE)
173
-
174
- # Build send buffer (from computed_us on owner ranks)
175
- per_dst: list[list[torch.Tensor]] = [[] for _ in range(num_ranks)]
176
- send_counts = [0] * num_ranks
177
-
178
- if owned_params:
179
- for p in owned_params:
180
- state = param_to_state[id(p)]
181
-
182
- assert computed_us[id(p)] is not None
183
- u_full = computed_us[id(p)].to(COMM_DTYPE).contiguous()
184
-
185
- total_sent = 0
186
- for dst_rank in range(num_ranks):
187
- indices = state.rank_indices[dst_rank]
188
- su = u_full[indices].flatten()
189
-
190
- n = su.numel()
191
- assert n > 0
192
-
193
- per_dst[dst_rank].append(su)
194
- send_counts[dst_rank] += n
195
- total_sent += n
196
-
197
- assert total_sent == u_full.numel()
198
-
199
- lengths = [len(v) for v in per_dst]
200
- if all(l > 0 for l in lengths):
201
- assert all(
202
- l == lengths[0] for l in lengths
203
- ), "All destination ranks must have the same number of sharded tensor"
204
- per_dst_flat = [t for dst in per_dst for t in dst]
205
- send_buf = torch.cat(per_dst_flat, dim=0)
206
- else:
207
- send_buf = torch.empty(0, dtype=COMM_DTYPE, device="cuda")
208
-
209
- # Build recv buffer
210
- recv_counts = [0] * num_ranks
211
- for src in range(num_ranks):
212
- total = 0
213
- for p in params:
214
- state = param_to_state[id(p)]
215
- if state.worker_rank != src:
216
- continue
217
- total += state.rank_numels[rank]
218
- recv_counts[src] = total
219
-
220
- recv_total = sum(recv_counts)
221
- assert recv_total > 0
222
- recv_buf = torch.empty(recv_total, dtype=COMM_DTYPE, device="cuda")
223
-
224
- # Launch async all-to-all
225
- work = dist.all_to_all_single(
226
- recv_buf,
227
- send_buf,
228
- output_split_sizes=recv_counts,
229
- input_split_sizes=send_counts,
230
- group=process_group,
231
- async_op=True,
232
- )
233
-
234
- return work, recv_buf, scattered_us, recv_counts
235
-
236
-
237
- def _complete_scatter(
238
- recv_buf: torch.Tensor,
239
- recv_counts: list[int],
240
- params: list[DTensor],
241
- param_to_state: dict[int, _muon_state],
242
- rank: int,
243
- scattered_us: dict[int, torch.Tensor],
244
- ) -> None:
245
- """Copy recv buffer into scattered_us (in-place)."""
246
- off = 0
247
- for src in range(len(recv_counts)):
248
- block = recv_counts[src]
249
- if block == 0:
250
- continue
251
-
252
- inner_off = 0
253
- for p in params:
254
- state = param_to_state[id(p)]
255
- if state.worker_rank != src:
256
- continue
257
- n = state.rank_numels[rank]
258
- assert n > 0
259
-
260
- flat_local = recv_buf.narrow(0, off + inner_off,
261
- n).view_as(p.to_local())
262
- scattered_us[id(p)].copy_(flat_local)
263
-
264
- inner_off += n
265
-
266
- assert inner_off == block
267
- off += block
268
-
269
-
270
- def _update_params(
271
- params: list[DTensor],
272
- param_to_state: dict[int, _muon_state],
273
- rank: int,
274
- scattered_us: dict[int, torch.Tensor],
275
- lr: float,
276
- weight_decay: float,
277
- ) -> None:
278
- """Apply weight decay, Muon update, and optional QK clipping."""
279
- for p in params:
280
- state = param_to_state[id(p)]
281
- u_dtensor = DTensor.from_local(
282
- scattered_us[id(p)],
283
- placements=p.placements,
284
- device_mesh=p.device_mesh,
285
- )
286
-
287
- adjusted_lr = adjust_lr_for_muon(lr, p.shape)
288
- update_p(p, u_dtensor, lr, adjusted_lr, weight_decay)
289
-
290
- # QK clipping – applied directly on the local tensor to
291
- # avoid DTensor sharding-propagation issues with _StridedShard.
292
- scales_full = compute_scales(
293
- p,
294
- state.qk_clip_state) if state.qk_clip_state is not None else None
295
- if scales_full is not None:
296
- ratio = p.shape[0] // scales_full.shape[0]
297
- idx0 = state.rank_indices[rank][0]
298
- if isinstance(idx0, slice):
299
- start = idx0.start or 0
300
- idx0 = torch.arange(start,
301
- idx0.stop,
302
- device=scales_full.device)
303
- row_scales = scales_full[idx0 // ratio]
304
- p._local_tensor.mul_(row_scales.view(-1, 1))
305
-
306
-
307
- # ======================================================================
308
- # Main generator – thin orchestrator that wires stages together.
309
- # ======================================================================
310
-
311
-
312
- @torch.no_grad()
313
- def muon_chunk_pipeline(
314
- params: list[DTensor],
315
- param_to_state: dict[int, _muon_state],
316
- rank: int,
317
- ns_steps: int,
318
- lr: float,
319
- weight_decay: float,
320
- none_grad: bool,
321
- ) -> Generator[None, None, None]:
322
- """Process one chunk of parameters through the full Muon pipeline.
323
-
324
- Stages: gather -> compute (Newton-Schulz) -> scatter -> update.
325
-
326
- Each ``yield`` lets :func:`run_pipeline` interleave other chunks so
327
- that communication and computation overlap across chunks. Async
328
- communication is launched via ``async_op=True`` and completed after
329
- the yield with ``work.wait()``.
330
-
331
- Overlap happens because :func:`run_pipeline` admits one new chunk
332
- per iteration (staggered admission). While chunk *N* does NS
333
- compute on the default CUDA stream, chunk *N+1*'s async all-to-all
334
- runs concurrently on the NCCL stream — no separate ``comm_stream``
335
- is required.
336
-
337
- Yields exactly **2** times:
338
-
339
- 1. After launching async all-to-all gather.
340
- 2. After launching async all-to-all scatter.
341
- """
342
- process_group = param_to_state[id(params[0])].process_group
343
- num_ranks = dist.get_world_size(group=process_group)
344
- owned_params = [
345
- p for p in params if param_to_state[id(p)].worker_rank == rank
346
- ]
347
-
348
- # Stages 1-2: launch async gather.
349
- with record_function("muon::launch_gather"):
350
- work, recv_buf, gathered_grads, recv_counts = _launch_gather(
351
- params, owned_params, param_to_state, rank, num_ranks,
352
- process_group)
353
-
354
- if none_grad:
355
- for p in params:
356
- p.grad = None
357
-
358
- yield # --- YIELD 1: other chunks can launch their gather ---
359
-
360
- with record_function("muon::wait_gather"):
361
- work.wait()
362
- _complete_gather(recv_buf, recv_counts, owned_params, gathered_grads,
363
- param_to_state, rank)
364
- del recv_buf
365
-
366
- # Stage 3: Newton-Schulz orthogonalization.
367
- with record_function("muon::newton_schulz"):
368
- computed_us = _compute_ns(owned_params, gathered_grads, ns_steps)
369
- gathered_grads.clear()
370
-
371
- # Stages 4-5: launch async scatter.
372
- with record_function("muon::launch_scatter"):
373
- work, recv_buf, scattered_us, recv_counts = _launch_scatter(
374
- params, owned_params, param_to_state, rank, num_ranks,
375
- process_group, computed_us)
376
- computed_us.clear()
377
-
378
- yield # --- YIELD 2: other chunks can launch their scatter ---
379
-
380
- with record_function("muon::wait_scatter"):
381
- work.wait()
382
- _complete_scatter(recv_buf, recv_counts, params, param_to_state, rank,
383
- scattered_us)
384
- del recv_buf
385
-
386
- # Stage 6: apply parameter updates.
387
- with record_function("muon::update_params"):
388
- _update_params(params, param_to_state, rank, scattered_us, lr,
389
- weight_decay)
390
- scattered_us.clear()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu128-x86_64-linux/qk_clip.py DELETED
@@ -1,129 +0,0 @@
1
- import logging
2
- import math
3
- from dataclasses import dataclass
4
-
5
- import torch
6
- from torch.distributed.tensor import DTensor
7
-
8
- logger = logging.getLogger(__name__)
9
-
10
-
11
- def parse_qk_layer(name: str) -> tuple[str | None, int]:
12
- """
13
- Parse a parameter name to check if it is a query/key projection layer
14
- ('wq', 'wk', 'q_proj', 'k_proj') and return (kind, layer_index).
15
-
16
- Returns:
17
- (kind, layer_idx) or (None, -1) if not matched.
18
-
19
- Example:
20
- 'model.3.attn.wq.weight' -> ('wq', 3)
21
- 'model.5.attn.wk.weight' -> ('wk', 5)
22
- 'model.2.attn.q_proj.weight' -> ('q_proj', 2)
23
- 'model.7.attn.k_proj.weight' -> ('k_proj', 7)
24
- 'model.4.attn.v_proj.weight' -> (None, -1)
25
- """
26
- parts = name.split('.')
27
- if len(parts) < 3:
28
- return None, -1
29
-
30
- kind = parts[-2]
31
-
32
- layer_idx = -1
33
- for part in reversed(parts):
34
- if part.isdigit():
35
- layer_idx = int(part)
36
- break
37
-
38
- if kind in ('wq', 'wk', 'q_proj', 'k_proj'):
39
- return kind, layer_idx
40
-
41
- return None, -1
42
-
43
-
44
- @dataclass
45
- class QKClipInfo:
46
- """Per-parameter dynamic info computed from config + runtime logits."""
47
- kind: str | None # 'wq'/'q_proj' or 'wk'/'k_proj' or None
48
- indices: list[int] # which heads to consider for clipping
49
- head_dim: int # from config
50
- threshold: float # from config
51
- logit: torch.Tensor | None
52
-
53
-
54
- def get_qk_clip_info(clip_config, n, qk_logits):
55
- """Extract QK clipping info for a named parameter.
56
-
57
- Args:
58
- clip_config: QK clipping configuration dict (or None).
59
- n: Parameter name string.
60
- qk_logits: Dict mapping layer indices to logit tensors (or None).
61
-
62
- Returns:
63
- QKClipInfo instance with clipping configuration for this parameter.
64
- """
65
- if clip_config is None:
66
- return None
67
-
68
- head_dim = clip_config.get('head_dim')
69
- threshold = clip_config.get('threshold')
70
- kind, layer_idx = parse_qk_layer(n)
71
-
72
- logit, indices = None, []
73
- if qk_logits is not None and kind is not None:
74
- logit = qk_logits[layer_idx]
75
- indices_key = 'q_indices' if 'q' in kind else 'k_indices'
76
- indices = clip_config.get(indices_key, []) or []
77
-
78
- if isinstance(logit, DTensor):
79
- # In TP settings, qk_logits may be DTensor
80
- # We convert it to full tensor here for simplicity
81
- logit = logit.full_tensor()
82
-
83
- return QKClipInfo(
84
- kind=kind,
85
- indices=indices,
86
- head_dim=head_dim,
87
- threshold=threshold,
88
- logit=logit,
89
- )
90
-
91
-
92
- def compute_scales(p, qk_clip_state):
93
- """Compute per-head scaling factors for QK clipping.
94
-
95
- Returns scales tensor if any head exceeds threshold, else None.
96
- """
97
- kind = qk_clip_state.kind
98
- indices = qk_clip_state.indices
99
- head_dim = qk_clip_state.head_dim
100
- threshold = qk_clip_state.threshold
101
- logit = qk_clip_state.logit
102
-
103
- H_global = p.shape[0] // head_dim
104
- scales_full = torch.ones(H_global, device=p.data.device)
105
- scaling = 0
106
-
107
- for logit_idx, head_idx in enumerate(indices):
108
- v_ele = float(logit[logit_idx])
109
- if v_ele > threshold:
110
- new_scale = math.sqrt(threshold / v_ele)
111
- if new_scale < scales_full[head_idx]:
112
- scales_full[head_idx] = new_scale
113
- logger.info(
114
- f"[{kind}] Head {head_idx} exceeded threshold "
115
- f"(value={v_ele:.4f}, threshold={threshold:.4f}) -> applying scale={new_scale:.4f}"
116
- )
117
- scaling += 1
118
-
119
- return scales_full if scaling > 0 else None
120
-
121
-
122
- def qk_clip(p, scales, head_dim):
123
- """Apply per-head scaling to a Q/K projection weight matrix."""
124
- if isinstance(p, torch.nn.Parameter):
125
- W = p.data.view(-1, head_dim, p.data.shape[1])
126
- W.mul_(scales.view(-1, 1, 1))
127
- else:
128
- W = p.view(-1, head_dim, p.shape[1])
129
- W.mul_(scales.view(-1, 1, 1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/adamw.py DELETED
@@ -1,154 +0,0 @@
1
- from collections import defaultdict
2
- from typing import cast
3
-
4
- import torch
5
- from torch.distributed.tensor import DTensor
6
-
7
-
8
- def fused_adamw(
9
- params: list[torch.Tensor],
10
- grads: list[torch.Tensor],
11
- exp_avgs: list[torch.Tensor],
12
- exp_avg_sqs: list[torch.Tensor],
13
- max_exp_avg_sqs: list[torch.Tensor],
14
- state_steps: list[torch.Tensor],
15
- amsgrad: bool,
16
- beta1: float,
17
- beta2: float,
18
- lr: float | torch.Tensor,
19
- weight_decay: float,
20
- eps: float,
21
- maximize: bool,
22
- ) -> None:
23
- if not params:
24
- return
25
-
26
- # We only shuffle around the lr when it is a Tensor and on CUDA, otherwise, we prefer
27
- # treating it as a scalar.
28
- lr_dict: dict | None = ({
29
- lr.device: lr
30
- } if isinstance(lr, torch.Tensor) and str(lr.device) != "cpu" else None)
31
- grouped_tensors = torch.optim.Optimizer._group_tensors_by_device_and_dtype(
32
- [params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs,
33
- state_steps] # type: ignore[list-item]
34
- )
35
- for (device, _), (
36
- (
37
- device_params_,
38
- device_grads_,
39
- device_exp_avgs_,
40
- device_exp_avg_sqs_,
41
- device_max_exp_avg_sqs,
42
- device_state_steps_,
43
- ),
44
- _,
45
- ) in grouped_tensors.items():
46
- device_params = cast(list[torch.Tensor], device_params_)
47
- device_grads = cast(list[torch.Tensor], device_grads_)
48
- device_exp_avgs = cast(list[torch.Tensor], device_exp_avgs_)
49
- device_exp_avg_sqs = cast(list[torch.Tensor], device_exp_avg_sqs_)
50
- device_state_steps = cast(list[torch.Tensor], device_state_steps_)
51
-
52
- if lr_dict is not None and device not in lr_dict:
53
- lr_dict[device] = lr.to(
54
- device=device, non_blocking=True) # type: ignore[union-attr]
55
- lr = lr_dict[device]
56
- torch._foreach_add_(device_state_steps, 1)
57
- func = torch._fused_adamw_
58
- func(
59
- device_params,
60
- device_grads,
61
- device_exp_avgs,
62
- device_exp_avg_sqs,
63
- device_max_exp_avg_sqs, # type: ignore[arg-type]
64
- device_state_steps,
65
- amsgrad=amsgrad,
66
- lr=lr, # type: ignore[arg-type]
67
- beta1=beta1,
68
- beta2=beta2,
69
- weight_decay=weight_decay,
70
- eps=eps,
71
- maximize=maximize,
72
- )
73
-
74
-
75
- def step_adamw_params(optimizer_state, params, group):
76
- """Run fused AdamW on a list of parameters sharing the same placement.
77
-
78
- Args:
79
- optimizer_state: The optimizer's state dict (self.state in Muon).
80
- params: List of parameters to update.
81
- group: Parameter group dict with lr, adamw_betas, adamw_eps, weight_decay.
82
- """
83
- params_with_grads = []
84
- grads = []
85
- moment1 = []
86
- moment2 = []
87
- max_exp_avg_sqs = []
88
- state_steps = []
89
- lr = group["lr"]
90
- beta1, beta2 = group["adamw_betas"]
91
- eps = group["adamw_eps"]
92
- weight_decay = group["weight_decay"]
93
-
94
- for p in params:
95
- g = p.grad
96
- if g is None:
97
- continue
98
- state = optimizer_state[p]
99
- params_with_grads.append(p)
100
- grads.append(g)
101
- if "step" not in state:
102
- state["step"] = (torch.zeros((),
103
- dtype=torch.float32,
104
- device=p.device))
105
- state["moment1"] = torch.zeros_like(g)
106
- state["moment2"] = torch.zeros_like(g)
107
- moment1.append(state["moment1"])
108
- moment2.append(state["moment2"])
109
- if not isinstance(state["step"], torch.Tensor):
110
- step_tensor = torch.tensor(state["step"],
111
- dtype=torch.float32,
112
- device=p.device)
113
- else:
114
- step_tensor = state["step"]
115
- state_steps.append(step_tensor)
116
-
117
- fused_adamw(
118
- params_with_grads,
119
- grads,
120
- moment1,
121
- moment2,
122
- max_exp_avg_sqs,
123
- state_steps,
124
- amsgrad=False,
125
- beta1=beta1,
126
- beta2=beta2,
127
- lr=lr,
128
- weight_decay=weight_decay,
129
- eps=eps,
130
- maximize=False,
131
- )
132
-
133
-
134
- def step_adamw(optimizer_state, group):
135
- """Dispatch AdamW step, grouping parameters by type and placement.
136
-
137
- Args:
138
- optimizer_state: The optimizer's state dict (self.state in Muon).
139
- group: Parameter group dict.
140
- """
141
- params = group["params"]
142
-
143
- # group params with its type and placement
144
- placement_to_params: dict[tuple, list[torch.Tensor]] = defaultdict(list)
145
- for p in params:
146
- match p:
147
- case DTensor():
148
- placement_to_params[tuple([p.placements,
149
- p.device_mesh])].append(p)
150
- case torch.Tensor():
151
- placement_to_params[tuple([torch.Tensor, None])].append(p)
152
-
153
- for group_params in placement_to_params.values():
154
- step_adamw_params(optimizer_state, group_params, group)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/async_utils.py DELETED
@@ -1,77 +0,0 @@
1
- import logging
2
- from typing import Generator
3
-
4
- logger = logging.getLogger(__name__)
5
-
6
-
7
- class _Task:
8
- """Internal: wraps a generator, advances one yield at a time."""
9
-
10
- def __init__(self, generator: Generator[None, None, None], index: int):
11
- self._generator = generator
12
- self._index = index
13
- self._steps_completed = 0
14
- self.step() # run to first yield
15
-
16
- def step(self) -> bool:
17
- try:
18
- next(self._generator)
19
- self._steps_completed += 1
20
- logger.debug("pipeline[%d] completed stage %d", self._index,
21
- self._steps_completed)
22
- return True
23
- except StopIteration:
24
- logger.debug("pipeline[%d] finished after %d stages", self._index,
25
- self._steps_completed)
26
- return False
27
-
28
- def close(self):
29
- self._generator.close()
30
-
31
-
32
- def run_pipeline(
33
- pipelines: Generator[Generator[None, None, None], None, None],
34
- max_concurrent: int,
35
- ) -> None:
36
- """Run generator-based pipelines with bounded concurrency.
37
-
38
- Each pipeline is a generator that yields at stage boundaries.
39
- The runtime interleaves pipelines so communication and computation
40
- overlap across chunks.
41
- """
42
- if max_concurrent <= 0:
43
- raise ValueError(f"max_concurrent must be > 0, got {max_concurrent}")
44
-
45
- have_new = True
46
- task_index = 0
47
- previous_tasks: list[_Task] = []
48
-
49
- try:
50
- while have_new or previous_tasks:
51
- running_tasks: list[_Task] = []
52
-
53
- # Admit one new pipeline per iteration (staggered admission).
54
- # Admitting one at a time ensures that while chunk N does NS
55
- # compute on the default stream, chunk N+1's NCCL all-to-all
56
- # runs concurrently on the NCCL stream — creating real
57
- # communication/computation overlap on the GPU.
58
- if have_new and len(previous_tasks) < max_concurrent:
59
- try:
60
- gen = next(pipelines)
61
- task = _Task(gen, task_index)
62
- task_index += 1
63
- running_tasks.append(task)
64
- except StopIteration:
65
- have_new = False
66
-
67
- # Advance every previously-yielded task by one step.
68
- for task in previous_tasks:
69
- if task.step():
70
- running_tasks.append(task)
71
-
72
- previous_tasks = running_tasks
73
- except BaseException:
74
- # Clean up all in-flight generators to release GPU resources.
75
- for task in previous_tasks:
76
- task.close()
77
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/core.py DELETED
@@ -1,116 +0,0 @@
1
- import math
2
- from dataclasses import dataclass
3
-
4
- import torch
5
- import torch.distributed as dist
6
- from torch.distributed import ProcessGroup
7
- from torch.distributed.tensor import DTensor
8
-
9
-
10
- @dataclass
11
- class _muon_state:
12
- worker_rank: int
13
- process_group: ProcessGroup
14
- rank_indices: dict[int, tuple] # local_rank -> per-dim indices
15
- rank_numels: dict[int, int] # local_rank -> numel
16
- name: str
17
- qk_clip_state: torch.Tensor | None = None
18
-
19
-
20
- def update_g(optimizer_state, p, g, group, momentum):
21
- """Apply momentum update to gradient.
22
-
23
- Args:
24
- optimizer_state: The optimizer's state dict (self.state in Muon).
25
- p: Parameter tensor.
26
- g: Gradient tensor.
27
- group: Parameter group dict.
28
- momentum: Momentum coefficient.
29
-
30
- Returns:
31
- Momentum-updated gradient tensor.
32
- """
33
- state = optimizer_state[p]
34
- buf = state.setdefault("momentum_buffer", torch.zeros_like(g))
35
- torch.add(g, buf, alpha=momentum, out=buf)
36
- if group["nesterov"]:
37
- g.add_(buf, alpha=momentum)
38
- return g
39
- return buf
40
-
41
-
42
- def update_p(p, u, lr, adjusted_lr, weight_decay):
43
- """Apply weight decay and orthogonalized update to parameter.
44
-
45
- Args:
46
- p: Parameter (torch.nn.Parameter or DTensor).
47
- u: Orthogonalized update tensor.
48
- lr: Base learning rate.
49
- adjusted_lr: Size-adjusted learning rate.
50
- weight_decay: Weight decay coefficient.
51
- """
52
- if isinstance(p, torch.nn.Parameter):
53
- # apply weight decay
54
- p.data.mul_(1 - lr * weight_decay)
55
- # apply update
56
- p.data.add_(u, alpha=-adjusted_lr)
57
- else:
58
- p.mul_(1 - lr * weight_decay)
59
- p.add_(u, alpha=-adjusted_lr)
60
-
61
-
62
- def adjust_lr_for_muon(lr, param_shape):
63
- """Scale learning rate based on parameter matrix dimensions.
64
-
65
- Args:
66
- lr: Base learning rate.
67
- param_shape: Shape of the parameter tensor.
68
-
69
- Returns:
70
- Adjusted learning rate.
71
- """
72
- A, B = param_shape[:2]
73
- # We adjust the learning rate and weight decay based on the size of the parameter matrix
74
- # as described in the paper
75
- adjusted_ratio = 0.2 * math.sqrt(max(A, B))
76
- adjusted_lr = lr * adjusted_ratio
77
- return adjusted_lr
78
-
79
-
80
- def default_is_muon(name, x, expert_keys=None):
81
- skip_keys = ["embed_tokens", "lm_head", "tok_embeddings", "output"]
82
- if any(key in name for key in skip_keys):
83
- return False
84
- effective_ndim = x.ndim
85
- if expert_keys and any(key in name for key in expert_keys):
86
- effective_ndim -= 1
87
- return effective_ndim >= 2
88
-
89
-
90
- def get_default_muon_param_groups(model, is_muon_func=None, expert_keys=None):
91
- if is_muon_func is None:
92
- is_muon_func = lambda n, x: default_is_muon(n, x, expert_keys)
93
-
94
- muon_params, muon_names = [], []
95
- non_muon_params = []
96
-
97
- for n, p in model.named_parameters():
98
- if not p.requires_grad:
99
- continue
100
- if is_muon_func(n, p):
101
- muon_params.append(p)
102
- muon_names.append(n)
103
- else:
104
- non_muon_params.append(p)
105
-
106
- return [
107
- {
108
- "params": muon_params,
109
- "names": muon_names,
110
- "use_muon": True,
111
- },
112
- {
113
- "params": non_muon_params,
114
- "use_muon": False,
115
- },
116
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/distributed/utils.py DELETED
@@ -1,234 +0,0 @@
1
- import torch
2
- import torch.distributed as dist
3
- from torch.distributed import ProcessGroup
4
- from torch.distributed.device_mesh import DeviceMesh
5
- from torch.distributed.tensor import DTensor
6
- from torch.distributed.tensor.placement_types import (Placement, Shard,
7
- _StridedShard)
8
-
9
-
10
- def _is_shard(placement: Placement) -> bool:
11
- """Check if a placement is a shard type (Shard or _StridedShard).
12
-
13
- In PyTorch 2.10+, _StridedShard no longer inherits from Shard, so
14
- ``placement.is_shard()`` returns False for _StridedShard. This helper
15
- handles both old and new hierarchies.
16
- """
17
- return isinstance(placement, (Shard, _StridedShard))
18
-
19
-
20
- def get_slices_of_dtensor(
21
- target: DTensor | torch.Tensor,
22
- local_rank: int,
23
- shard_mesh: DeviceMesh,
24
- shard_placements: tuple[Placement],
25
- ) -> tuple[slice | torch.Tensor, ...]:
26
- """
27
- Get per-dimension indices for a given rank's shard of the target tensor.
28
-
29
- Uses ``Shard.local_shard_size_and_offset`` and
30
- ``_StridedShard.local_shard_size_and_offset`` for correct handling of
31
- both contiguous and strided (non-contiguous) sharding.
32
-
33
- Args:
34
- target (DTensor | torch.Tensor): The target tensor (for its shape).
35
- local_rank (int): The local rank within the shard group.
36
- shard_mesh (DeviceMesh): The shard mesh (only shard dimensions).
37
- shard_placements (tuple[Placement]): The shard placements.
38
-
39
- Returns:
40
- A tuple of indices (one per tensor dim). Each element is either:
41
- - A ``slice`` (for contiguous or unsharded dims)
42
- - A 1-D ``torch.LongTensor`` of indices (for strided sharding)
43
- """
44
-
45
- # find the global rank of the local rank in the shard mesh
46
- rank = sorted(shard_mesh.mesh.flatten().tolist())[local_rank]
47
-
48
- rank_coords = (shard_mesh.mesh == rank).nonzero()
49
-
50
- assert len(rank_coords) == 1
51
- rank_coords = tuple(rank_coords[0].tolist())
52
-
53
- assert len(rank_coords) == len(shard_placements)
54
-
55
- # Track per-shard-dim indices.
56
- # None means "not yet sharded on this dim".
57
- dim_indices: dict[int, torch.Tensor] = {}
58
-
59
- # Caution: Assuming replicate-to-shard of the shard mesh goes with
60
- # left-to-right sharding. This is ensured by the sorting logic of
61
- # construct_shard_mesh function.
62
- for mesh_dim_idx, (rank_coord, placement) in enumerate(
63
- zip(rank_coords, shard_placements)):
64
- assert _is_shard(placement)
65
-
66
- num_chunks = shard_mesh.mesh.shape[mesh_dim_idx]
67
- shard_dim = placement.dim
68
-
69
- # Current effective size on this dim (may already be sub-sharded)
70
- if shard_dim in dim_indices:
71
- curr_size = len(dim_indices[shard_dim])
72
- else:
73
- curr_size = target.size()[shard_dim]
74
-
75
- if curr_size % num_chunks != 0:
76
- raise NotImplementedError(
77
- f"Dimension size {curr_size} is not divisible "
78
- f"by number of ranks {num_chunks} for shard "
79
- f"placement on dim {shard_dim}. (shape: {target.shape})")
80
-
81
- # Compute indices for this level of sharding
82
- if isinstance(placement, _StridedShard):
83
- _shard_size, offsets = _StridedShard.local_shard_size_and_offset(
84
- placement,
85
- curr_size,
86
- num_chunks,
87
- rank_coord,
88
- return_first_offset=False)
89
- new_indices = torch.tensor(offsets, dtype=torch.long)
90
- else:
91
- shard_size, offset = Shard.local_shard_size_and_offset(
92
- curr_size, num_chunks, rank_coord)
93
- new_indices = torch.arange(offset,
94
- offset + shard_size,
95
- dtype=torch.long)
96
-
97
- # Compose with previous indices on this dim
98
- if shard_dim in dim_indices:
99
- dim_indices[shard_dim] = dim_indices[shard_dim][new_indices]
100
- else:
101
- dim_indices[shard_dim] = new_indices
102
-
103
- # Build result tuple
104
- result: list[slice | torch.Tensor] = []
105
- for d in range(len(target.size())):
106
- if d not in dim_indices:
107
- result.append(slice(None))
108
- else:
109
- indices = dim_indices[d]
110
- # Convert contiguous indices to slice for efficiency
111
- if len(indices) > 0:
112
- start = indices[0].item()
113
- expected = torch.arange(start,
114
- start + len(indices),
115
- dtype=torch.long)
116
- if torch.equal(indices, expected):
117
- result.append(slice(start, start + len(indices)))
118
- else:
119
- result.append(indices)
120
- else:
121
- result.append(slice(0, 0))
122
-
123
- return tuple(result)
124
-
125
-
126
- _ranks_to_dist_cache: dict[tuple[int, ...], tuple[DeviceMesh,
127
- ProcessGroup]] = dict()
128
-
129
-
130
- def construct_shard_mesh(
131
- placements: tuple[Placement],
132
- mesh: DeviceMesh,
133
- ) -> tuple[DeviceMesh, ProcessGroup, tuple[Placement, ...]]:
134
- """Construct shard sub-mesh and ProcessGroup for all-to-all communication.
135
-
136
- Given a DTensor's placements and device mesh, extracts the "shard group"
137
- — the set of ranks that together hold all shards of the same replica —
138
- and creates a ProcessGroup for all-to-all among them.
139
-
140
- Steps:
141
- 1. Sort placements: Replicate first, then Shard by (dim, granularity).
142
- 2. Permute the mesh tensor to match the sorted order.
143
- 3. Collapse Replicate dims → list of shard sub-meshes (one per replica).
144
- 4. Create/retrieve a cached ProcessGroup for the current rank's sub-mesh.
145
-
146
- Example — 8 GPUs, mesh shape (2, 2, 2),
147
- placements ``[Shard(0), Replicate, _StridedShard(0)]``::
148
-
149
- Step 1 — Sort: [Replicate, _StridedShard(0), Shard(0)]
150
- Permutation: [1, 2, 0]
151
-
152
- Step 2 — Permute mesh dims by [1, 2, 0]:
153
- Original: Permuted:
154
- [[[0,1],[2,3]], [[[0,2],[1,3]],
155
- [[4,5],[6,7]]] [[4,6],[5,7]]]
156
-
157
- Step 3 — Unbind replicate dim (dim 0), giving 2 shard sub-meshes:
158
- sub-mesh 0 = [[0,2],[1,3]] (replica group 0)
159
- sub-mesh 1 = [[4,6],[5,7]] (replica group 1)
160
- shard_placements = (_StridedShard(0), Shard(0))
161
-
162
- Step 4 — Rank 0 → ProcessGroup([0,1,4,5])
163
- Rank 2 → ProcessGroup([2,3,6,7])
164
-
165
- Returns:
166
- ``(shard_mesh, process_group, shard_placements)``
167
- """
168
- my_rank = dist.get_rank()
169
- assert mesh.mesh.device.type == 'cpu'
170
-
171
- # -- Fast path: 1D all-shard mesh → reuse existing PG. ----------------
172
- # This avoids a non-collective dist.new_group() call, which would
173
- # deadlock when only a subset of ranks call this function (e.g. expert
174
- # DTensors on a TP submesh where ranks 0-3 and 4-7 call separately).
175
- if mesh.ndim == 1 and len(placements) == 1 and _is_shard(placements[0]):
176
- key = (*mesh.mesh.shape, *mesh.mesh.flatten().tolist())
177
- if key not in _ranks_to_dist_cache:
178
- _ranks_to_dist_cache[key] = (mesh, mesh.get_group())
179
- return (*_ranks_to_dist_cache[key], tuple(placements))
180
-
181
- mesh_tensor = mesh.mesh.clone()
182
-
183
- # -- Step 1: Sort placements (Replicate first, then Shard by dim). ------
184
- # _StridedShard comes BEFORE regular Shard on the same dim so that
185
- # get_slices_of_dtensor applies the outer sharding first, matching
186
- # DTensor's left-to-right (outer-to-inner) composition order.
187
- def _sort_key(item):
188
- index, placement = item
189
- assert not placement.is_partial(), "Partial placement not supported"
190
- if placement.is_replicate():
191
- return (-1, 0, index)
192
- assert _is_shard(placement), f"Unsupported: {type(placement)}"
193
- split = (-1 / placement.split_factor if isinstance(
194
- placement, _StridedShard) else 0)
195
- return (placement.dim, split, index)
196
-
197
- indexed = sorted(enumerate(placements), key=_sort_key)
198
- perm, sorted_placements = zip(*indexed)
199
-
200
- # -- Step 2: Permute mesh to match sorted placement order. --------------
201
- sorted_mesh = mesh_tensor.permute(perm)
202
-
203
- # -- Step 3: Collapse replicate dims → list of shard sub-meshes. --------
204
- # E.g. mesh (2, 3, 4, 4) with [R, R, S(0), S(1)] → 6 sub-meshes of (4, 4)
205
- num_rep = sum(1 for p in sorted_placements if p.is_replicate())
206
- if num_rep > 0:
207
- if num_rep > 1:
208
- sorted_mesh = sorted_mesh.flatten(0, num_rep - 1)
209
- shard_meshes = list(torch.unbind(sorted_mesh, dim=0))
210
- else:
211
- shard_meshes = [sorted_mesh]
212
- shard_placements = sorted_placements[num_rep:]
213
- assert len(shard_placements) == len(set(shard_placements))
214
-
215
- # -- Step 4: Create/retrieve ProcessGroup for current rank's sub-mesh. --
216
- # All ranks must call dist.new_group in the same order, even though each
217
- # rank only joins one group.
218
- def _cache_key(t: torch.Tensor) -> tuple:
219
- return (*t.shape, *t.flatten().tolist())
220
-
221
- my_key = None
222
- for sm in shard_meshes:
223
- key = _cache_key(sm)
224
- if (my_rank == sm).any().item():
225
- assert my_key is None, "Rank appears in multiple shard groups"
226
- my_key = key
227
- if key not in _ranks_to_dist_cache:
228
- pg = dist.new_group(sm.flatten().tolist())
229
- _ranks_to_dist_cache[key] = (
230
- DeviceMesh(device_type="cuda", mesh=sm),
231
- pg,
232
- )
233
-
234
- return (*_ranks_to_dist_cache[my_key], shard_placements)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/matmul_transpose_triton.py DELETED
@@ -1,121 +0,0 @@
1
- # MIT License
2
- #
3
- # Copyright (c) 2025 Tianyang Lin
4
- #
5
- # Permission is hereby granted, free of charge, to any person obtaining a copy
6
- # of this software and associated documentation files (the "Software"), to deal
7
- # in the Software without restriction, including without limitation the rights
8
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- # copies of the Software, and to permit persons to whom the Software is
10
- # furnished to do so, subject to the following conditions:
11
- #
12
- # The above copyright notice and this permission notice shall be included in all
13
- # copies or substantial portions of the Software.
14
- #
15
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- # SOFTWARE.
22
-
23
- import torch
24
- import triton
25
- import triton.language as tl
26
-
27
-
28
- def get_autotune_config():
29
- return [
30
- triton.Config(
31
- {
32
- 'BLOCK_SIZE_M': blk_m,
33
- 'BLOCK_SIZE_K': blk_k,
34
- 'GROUP_SIZE_M': grp_sz
35
- },
36
- num_stages=n_stages,
37
- num_warps=n_warps) for blk_m in [32, 64, 128]
38
- for blk_k in [32, 64] for grp_sz in [8] for n_stages in [3, 4, 5]
39
- for n_warps in [4, 8]
40
- ]
41
-
42
-
43
- @triton.autotune(
44
- configs=get_autotune_config(),
45
- key=['M', 'K'],
46
- )
47
- @triton.jit
48
- def mmt_kernel(x, y, M, K, stride_xm, stride_xk, stride_ym, stride_yn,
49
- BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
50
- GROUP_SIZE_M: tl.constexpr):
51
- """
52
- Core kernel jit function of matmul_transpose that computes y = x @ x.T
53
- The code is a simple adaptation from the triton `matmul` tutorial:
54
- https://triton-lang.org/main/getting-started/tutorials/03-matrix-multiplication.html
55
- """
56
- pid = tl.program_id(axis=0)
57
- num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
58
- num_pid_n = tl.cdiv(M, BLOCK_SIZE_M)
59
- num_pid_in_group = GROUP_SIZE_M * num_pid_n
60
- group_id = pid // num_pid_in_group
61
- first_pid_m = group_id * GROUP_SIZE_M
62
- group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
63
- pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
64
- pid_n = (pid % num_pid_in_group) // group_size_m
65
- if pid_m > pid_n:
66
- return
67
-
68
- offs_xm = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
69
- offs_xn = (pid_n * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
70
- offs_k = tl.arange(0, BLOCK_SIZE_K)
71
- # we use a & b ptrs to denote different rows of x.
72
- a_ptrs = x + (offs_xm[:, None] * stride_xm + offs_k[None, :] * stride_xk)
73
- b_ptrs = x + (offs_xn[:, None] * stride_xm + offs_k[None, :] * stride_xk)
74
-
75
- accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_M), dtype=tl.float32)
76
-
77
- for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
78
- a = tl.load(a_ptrs,
79
- mask=offs_k[None, :] < K - k * BLOCK_SIZE_K,
80
- other=0.0)
81
- b = tl.load(b_ptrs,
82
- mask=offs_k[None, :] < K - k * BLOCK_SIZE_K,
83
- other=0.0)
84
- accumulator = tl.dot(a, tl.permute(b, (1, 0)), accumulator)
85
- a_ptrs += BLOCK_SIZE_K * stride_xk
86
- b_ptrs += BLOCK_SIZE_K * stride_xk
87
- # use dtype.element_ty to accommodate different input datatypes as in cpp templates
88
- # https://github.com/triton-lang/triton/issues/2252
89
- c = accumulator.to(x.dtype.element_ty)
90
-
91
- offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
92
- offs_cn = pid_n * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
93
- c_ptrs = y + stride_ym * offs_cm[:, None] + stride_yn * offs_cn[None, :]
94
- c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < M)
95
- tl.store(c_ptrs, c, mask=c_mask)
96
-
97
- # transpose and copy
98
- if pid_m < pid_n:
99
- ct_ptrs = y + stride_ym * offs_cn[:,
100
- None] + stride_yn * offs_cm[None, :]
101
- ct_mask = (offs_cn[:, None] < M) & (offs_cm[None, :] < M)
102
- tl.store(ct_ptrs, tl.permute(c, (1, 0)), mask=ct_mask)
103
-
104
-
105
- def matmul_transpose_assign(d_in, d_out):
106
- assert d_in.is_cuda, "Input `d_in` must be a CUDA tensor"
107
- assert d_out.is_cuda, "Input `d_out` must be a CUDA tensor"
108
- assert d_in.device == d_out.device, "Inputs `d_in` and `d_out` must be on the same CUDA device"
109
- assert d_in.dtype == d_out.dtype, "Inputs must have the same data type"
110
- assert d_in.ndim == 2, "Input `d_in` must be a 2D tensor"
111
- assert d_out.ndim == 2, "Input `d_out` must be a 2D tensor"
112
- assert d_in.size(0) == d_out.size(0) == d_out.size(0), \
113
- "First dimension of `d_in` must match first and second dimension of `d_out`"
114
-
115
- d_in = d_in.contiguous()
116
- M, K = d_in.shape
117
- grid = lambda META: (triton.cdiv(M, META['BLOCK_SIZE_M']) * triton.cdiv(
118
- M, META['BLOCK_SIZE_M']), )
119
- with torch.cuda.device(d_in.device.index):
120
- mmt_kernel[grid](d_in, d_out, M, K, d_in.stride(0), d_in.stride(1),
121
- d_out.stride(0), d_out.stride(1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/metadata.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "python-depends": []
3
- }
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/muon.py DELETED
@@ -1,594 +0,0 @@
1
- import logging
2
- import types
3
- from collections import defaultdict
4
- from typing import Any
5
-
6
- import torch
7
- import torch.distributed as dist
8
- from torch.distributed.tensor import DTensor, Replicate, Shard
9
- from torch.profiler import record_function
10
-
11
- from .adamw import step_adamw
12
- from .async_utils import run_pipeline
13
- from .core import (_muon_state, adjust_lr_for_muon,
14
- get_default_muon_param_groups, update_g, update_p)
15
- from .distributed.utils import (_is_shard, construct_shard_mesh,
16
- get_slices_of_dtensor)
17
- from .newton_schulz import (COMM_DTYPE, DEFAULT_CHUNK_SIZE_RATIO,
18
- _zeropower_via_newtonschulz5)
19
- from .pipeline import muon_chunk_pipeline
20
- from .qk_clip import compute_scales, get_qk_clip_info, qk_clip
21
-
22
- logger = logging.getLogger(__name__)
23
-
24
-
25
- def _expand_expert_params(names, params, expert_keys):
26
- """Expand expert params by splitting on dim 0 (expert dimension).
27
-
28
- Params whose name matches any key in ``expert_keys`` are treated as
29
- expert-parallel tensors. Their outermost dimension is the expert
30
- dimension: an ``(E, out, in)`` tensor becomes ``E`` separate 2D
31
- ``nn.Parameter`` views so that in-place updates propagate back to
32
- the original storage.
33
-
34
- Non-expert params with ``ndim > 2`` trigger an ``AssertionError`` —
35
- if they are expert params, their key must be added to ``expert_keys``.
36
-
37
- The grad must already be set on each expert param (e.g. after momentum).
38
-
39
- For DTensor expert params, placements that shard on dim 0 (expert dim)
40
- are consumed by the split. Non-dim-0 shard placements (e.g. TP) are
41
- preserved: each 2D slice is wrapped as a DTensor on the corresponding
42
- submesh so the parallel pipeline handles the TP communication.
43
- """
44
- expanded_names = []
45
- expanded_params = []
46
-
47
- for n, p in zip(names, params):
48
- is_expert = expert_keys and any(key in n for key in expert_keys)
49
- is_dtensor = isinstance(p.data, DTensor)
50
-
51
- if not is_expert:
52
- assert p.data.ndim <= 2, (
53
- f"Param {n} has ndim={p.data.ndim} but does not match "
54
- f"expert_keys={expert_keys}. If this is an expert param, "
55
- f"add its key to expert_keys.")
56
- expanded_names.append(n)
57
- expanded_params.append(p)
58
- continue
59
-
60
- g = p.grad
61
- assert g is not None, (
62
- f"Expert param {n} must have grad set before expansion")
63
-
64
- tp_mesh = None
65
- tp_placements_2d = None
66
-
67
- if is_dtensor:
68
- local_data = p.to_local()
69
- local_grad = g.to_local() if isinstance(g, DTensor) else g
70
-
71
- # Find non-dim-0 shard placements (e.g. TP sharding).
72
- # After splitting on dim 0, Shard(k) becomes Shard(k-1).
73
- tp_dim_indices = []
74
- tp_placements_2d = []
75
- for i, pl in enumerate(p.placements):
76
- if _is_shard(pl) and pl.dim != 0:
77
- tp_dim_indices.append(i)
78
- tp_placements_2d.append(Shard(pl.dim - 1))
79
-
80
- if tp_dim_indices:
81
- tp_dim_names = tuple(p.device_mesh.mesh_dim_names[i]
82
- for i in tp_dim_indices)
83
- if len(tp_dim_names) == 1:
84
- tp_mesh = p.device_mesh[tp_dim_names[0]]
85
- else:
86
- tp_mesh = p.device_mesh[tp_dim_names]
87
- else:
88
- local_data = p.data
89
- local_grad = g
90
-
91
- # Expand: split dim 0, reshape each slice to 2D.
92
- num_local_experts = local_data.shape[0]
93
- for i in range(num_local_experts):
94
- slice_data = local_data[i]
95
- slice_grad = local_grad[i]
96
-
97
- if tp_mesh is not None:
98
- # Wrap as DTensor on TP submesh so the pipeline handles
99
- # TP communication (gather/scatter across TP ranks).
100
- dt_data = DTensor.from_local(slice_data,
101
- device_mesh=tp_mesh,
102
- placements=tp_placements_2d)
103
- dt_grad = DTensor.from_local(slice_grad,
104
- device_mesh=tp_mesh,
105
- placements=tp_placements_2d)
106
- expert_param = torch.nn.Parameter(dt_data, requires_grad=False)
107
- expert_param.grad = dt_grad
108
- else:
109
- expert_param = torch.nn.Parameter(slice_data,
110
- requires_grad=False)
111
- expert_param.grad = slice_grad
112
-
113
- expanded_names.append(f"{n}[{i}]")
114
- expanded_params.append(expert_param)
115
-
116
- p.grad = None # allow expert grad storage to be freed after pipeline
117
-
118
- return expanded_names, expanded_params
119
-
120
-
121
- class Muon(torch.optim.Optimizer):
122
- """
123
- Muon - MomentUm Orthogonalized by Newton-schulz
124
-
125
- Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-
126
- processing step, in which each 2D parameter's update is replaced with the nearest orthogonal
127
- matrix. To efficiently orthogonalize each update, we use a Newton-Schulz iteration, which has
128
- the advantage that it can be stably run in bfloat16 on the GPU.
129
-
130
- Some warnings:
131
- - We believe this optimizer is unlikely to work well for training with small batch size.
132
- - We believe it may not work well for finetuning pretrained models, but we haven't tested this.
133
-
134
- Arguments:
135
- model: The model to be optimized by Muon.
136
- is_muon_func: A function that takes a parameter and its name, and returns whether the parameter should be optimized by Muon.
137
- lr: The learning rate. The updates will have spectral norm of `lr`. (0.02 is a good default)
138
- momentum: The momentum used by the internal SGD. (0.95 is a good default)
139
- nesterov: Whether to use Nesterov-style momentum in the internal SGD. (recommended)
140
- ns_steps: The number of Newton-Schulz iterations to run. (6 is probably always enough)
141
- weight_decay: The weight decay for Muon and AdamW.
142
- Parameters that are {0, 1}-D or are detected as being the embed or lm_head will be optimized by AdamW instead.
143
- adamw_lr: The learning rate for the internal AdamW.
144
- adamw_betas: The betas for the internal AdamW.
145
- adamw_eps: The epsilon for the internal AdamW.
146
- none_grad: Whether to set p.grad to None after gathering the gradients. This can save memory.
147
- debug: Whether to print debug information.
148
- clip_info : Configuration for QK clipping. Expected keys:
149
- - "q_indices" (list[int]): Indices of query heads to consider.
150
- - "k_indices" (list[int]): Indices of key heads to consider.
151
- - "head_dim" (int): Dimensionality of each attention head.
152
- - "threshold" (float): Threshold value; heads whose QK logits exceed
153
- this value will be scaled down.
154
- Default is:
155
- {
156
- "q_indices": [],
157
- "k_indices": [],
158
- "head_dim": 128,
159
- "threshold": 100
160
- }
161
- warmup_step : How many all2all gather, compute operations are launched in advance
162
- before the corresponding all2all scatter steps begin.
163
- A higher warmup_step increases memory usage but can improve
164
- performance by overlapping communication.
165
- Parallel muon only.
166
- chunk_size : Batch size of parameters to process in each
167
- all2all gather/compute/scatter step.
168
- Use shard ranks * DEFAULT_CHUNK_SIZE_RATIO when -1 is specified.
169
- use_distributed_muon: Use distributed muon by Liu et al. (2024).
170
- For testing purpose only.
171
- small_param_numel_threshold: Threshold for classifying parameters as small and falling back to distributed Muon
172
- expert_keys: List of strings to identify expert-parallel parameters.
173
- If any key appears in a parameter's name, its outermost
174
- dimension is treated as the expert dimension and expanded
175
- into per-expert 2D params for Muon. For example,
176
- ``expert_keys=["experts"]`` matches any param whose name
177
- contains "experts". 3D+ params not matched by any key
178
- will raise an error.
179
- """
180
-
181
- def __init__(self,
182
- params,
183
- lr=1e-3,
184
- momentum=0.95,
185
- nesterov=True,
186
- ns_steps=5,
187
- weight_decay=0.1,
188
- adamw_betas=(0.9, 0.95),
189
- adamw_eps=1e-8,
190
- none_grad=True,
191
- debug=False,
192
- clip_config=None,
193
- warmup_step=5,
194
- chunk_size=-1,
195
- use_distributed_muon=False,
196
- small_param_numel_threshold=65536,
197
- expert_keys=None):
198
- defaults = dict(
199
- lr=lr,
200
- weight_decay=weight_decay,
201
- momentum=momentum,
202
- nesterov=nesterov,
203
- ns_steps=ns_steps,
204
- adamw_betas=adamw_betas,
205
- adamw_eps=adamw_eps,
206
- none_grad=none_grad,
207
- use_muon=True,
208
- )
209
- error_message = "The key 'use_muon' is not set in parameter group {idx}. Assuming all parameters in the group will use muon optimization, which may lead to unexpected behavior."
210
- instruction_code = "\n\n please follow this code snippet \n```optimizer = get_kernel('motif-technologies/optimizer')\n\n\nparams = optimizer.muon.get_default_muon_param_groups(model)\n\noptim = optimizer.Muon(params, ...)```"
211
-
212
- if isinstance(params, types.GeneratorType):
213
- raise ValueError(error_message.format(idx=0) + instruction_code)
214
- for _idx, param_group in enumerate(params):
215
- if param_group.get("use_muon", None) is None:
216
- raise ValueError(
217
- error_message.format(idx=_idx) + instruction_code)
218
-
219
- super().__init__(params, defaults)
220
-
221
- self.debug = debug
222
- self.clip_config = clip_config if clip_config is not None else {
223
- "q_indices": [],
224
- "k_indices": [],
225
- "head_dim": 128,
226
- "threshold": 100,
227
- }
228
- self.warmup_step = warmup_step
229
- self.chunk_size = chunk_size
230
- self.use_distributed_muon = use_distributed_muon
231
- self.small_param_numel_threshold = small_param_numel_threshold
232
- self.expert_keys = expert_keys
233
-
234
- def _calc_flops(self, G, steps):
235
- assert len(G.shape) == 2
236
- M, N = G.shape
237
- if M > N:
238
- M, N = N, M
239
-
240
- return steps * ((M**3) * 2 + (M**2 * N) * 4 + M * N * 2 + M**2 * 3)
241
-
242
- def get_shard_mesh(self, p):
243
- """
244
- Get the shard mesh for a parameter p on the given rank.
245
- """
246
- assert isinstance(
247
- p, DTensor), "Parallel Muon only supports DTensor parameters."
248
-
249
- shard_mesh, shard_pg, shard_placements = construct_shard_mesh(
250
- p.placements, p.device_mesh)
251
-
252
- return shard_mesh, shard_pg, shard_placements
253
-
254
- def init_state_and_assign_params(self, names, params, group, qk_logits):
255
- param_to_state = {}
256
- param_to_flops = {}
257
-
258
- total_flops = 0
259
- for p in params:
260
- g = p.grad
261
- if g is None:
262
- continue
263
- assert g.ndim == 2, "Muon only supports 2D parameters."
264
-
265
- flops = self._calc_flops(g, group["ns_steps"])
266
- param_to_flops[id(p)] = flops
267
- total_flops += flops
268
-
269
- if self.debug:
270
- logger.debug("Total TFLOPs for Muon: %.2f TFLOPs",
271
- total_flops / 1e12)
272
-
273
- paired = list(zip(names, params))
274
-
275
- paired_sorted = sorted(paired,
276
- key=lambda x: param_to_flops[id(x[1])],
277
- reverse=True)
278
-
279
- names_sorted, params_sorted = zip(*paired_sorted)
280
- ordered_names = list(names_sorted)
281
- ordered_params = list(params_sorted)
282
-
283
- round_robin = 0
284
- mesh = ordered_params[0].device_mesh
285
- placements = ordered_params[0].placements
286
-
287
- shard_mesh, shard_pg, shard_placements = self.get_shard_mesh(
288
- ordered_params[0])
289
- shard_mesh_flattened = shard_mesh.mesh.flatten()
290
- num_ranks = dist.get_world_size(group=shard_pg)
291
-
292
- for n, p in zip(ordered_names, ordered_params):
293
- if mesh != p.device_mesh:
294
- raise ValueError("All parameters must be on the same mesh.")
295
- if placements != p.placements:
296
- raise ValueError("All parameters must have same placements.")
297
-
298
- worker_rank = shard_mesh_flattened[round_robin].item() % num_ranks
299
- round_robin = (round_robin + 1) % len(shard_mesh_flattened)
300
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
301
-
302
- # Precompute per-rank indices and numels for all-to-all.
303
- rank_indices: dict[int, tuple] = {}
304
- rank_numels: dict[int, int] = {}
305
- for r in range(num_ranks):
306
- indices = get_slices_of_dtensor(p, r, shard_mesh,
307
- shard_placements)
308
- rank_indices[r] = indices
309
- numel = 1
310
- for idx, dim_size in zip(indices, p.shape):
311
- if isinstance(idx, slice):
312
- start, stop, step = idx.indices(dim_size)
313
- numel *= max(0, (stop - start + (step - 1)) // step)
314
- else:
315
- numel *= len(idx)
316
- rank_numels[r] = numel
317
-
318
- param_to_state[id(p)] = _muon_state(
319
- worker_rank=worker_rank,
320
- process_group=shard_pg,
321
- rank_indices=rank_indices,
322
- rank_numels=rank_numels,
323
- name=n,
324
- qk_clip_state=qk_clip_state,
325
- )
326
-
327
- return param_to_state, ordered_params
328
-
329
- def base(self, names, params, group, lr, weight_decay, qk_logits):
330
- # Momentum is already applied by _step_muon before this method.
331
- for n, p in zip(names, params):
332
- g = p.grad
333
- if g is None:
334
- continue
335
-
336
- u = _zeropower_via_newtonschulz5(g.to(COMM_DTYPE),
337
- steps=group["ns_steps"])
338
-
339
- adjusted_lr = adjust_lr_for_muon(lr, p.shape)
340
- update_p(p, u, lr, adjusted_lr, weight_decay)
341
-
342
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
343
-
344
- scales_full = compute_scales(
345
- p, qk_clip_state) if qk_clip_state is not None else None
346
- if scales_full is not None:
347
- qk_clip(p, scales_full, qk_clip_state.head_dim)
348
-
349
- def distributed_muon(
350
- self,
351
- names: list[str],
352
- params: list[torch.nn.Parameter],
353
- group: dict[str, Any],
354
- lr: float,
355
- weight_decay: float,
356
- qk_logits: list[torch.Tensor | DTensor] | None,
357
- ):
358
- """ Implementation of Distributed Muon by Liu et al. """
359
-
360
- # Momentum is already applied by _step_muon before this method.
361
- for n, p in zip(names, params):
362
- g = p.grad
363
- if g is None:
364
- continue
365
-
366
- # Gather G
367
- if isinstance(p.data, DTensor):
368
- g_full = g.full_tensor()
369
- p_full = p.data.full_tensor()
370
- else:
371
- g_full = g
372
- p_full = p
373
-
374
- u_full = _zeropower_via_newtonschulz5(g_full.to(COMM_DTYPE),
375
- steps=group["ns_steps"])
376
-
377
- adjusted_lr = adjust_lr_for_muon(lr, p_full.shape)
378
- update_p(p_full, u_full, lr, adjusted_lr, weight_decay)
379
-
380
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
381
-
382
- scales_full = compute_scales(
383
- p_full, qk_clip_state) if qk_clip_state is not None else None
384
-
385
- if scales_full is not None:
386
- qk_clip(p_full, scales_full, qk_clip_state.head_dim)
387
-
388
- if isinstance(p.data, DTensor):
389
- ndims = len(p.device_mesh.mesh.shape)
390
- p_replicate = DTensor.from_local(
391
- p_full,
392
- device_mesh=p.device_mesh,
393
- placements=[Replicate() for _ in range(ndims)],
394
- )
395
-
396
- p_sharded = p_replicate.redistribute(
397
- device_mesh=p.device_mesh,
398
- placements=p.placements,
399
- )
400
-
401
- p.copy_(p_sharded)
402
-
403
- def parallel(self, names, params, group, lr, weight_decay, qk_logits):
404
- """
405
- Perform a parallel optimization step using Muon.
406
-
407
- Parameters are chunked and each chunk is processed by a
408
- :func:`muon_chunk_pipeline` generator. :func:`run_pipeline`
409
- interleaves multiple chunks so that communication and computation
410
- overlap across chunks (the same overlap previously achieved by the
411
- warmup + main-loop index scheduling).
412
- """
413
-
414
- # Momentum is already applied by _step_muon before this method.
415
-
416
- param_to_state, ordered_params = self.init_state_and_assign_params(
417
- names, params, group, qk_logits)
418
-
419
- # Compute local rank for this group's shard process group.
420
- shard_pg = param_to_state[id(ordered_params[0])].process_group
421
- rank = dist.get_rank(group=shard_pg)
422
-
423
- if self.chunk_size == -1:
424
- shard_ranks = dist.get_world_size(param_to_state[id(
425
- ordered_params[0])].process_group)
426
- chunk_size = shard_ranks * DEFAULT_CHUNK_SIZE_RATIO
427
- elif self.chunk_size > 0:
428
- chunk_size = self.chunk_size
429
- else:
430
- raise ValueError("chunk_size must be -1 or a positive integer.")
431
-
432
- def pipelines():
433
- for start in range(0, len(ordered_params), chunk_size):
434
- chunk = ordered_params[start:start + chunk_size]
435
- if chunk:
436
- yield muon_chunk_pipeline(
437
- params=chunk,
438
- param_to_state=param_to_state,
439
- rank=rank,
440
- ns_steps=group["ns_steps"],
441
- lr=lr,
442
- weight_decay=weight_decay,
443
- none_grad=group["none_grad"],
444
- )
445
-
446
- with record_function("muon::barrier"):
447
- dist.barrier()
448
- with record_function("muon::pipeline"):
449
- run_pipeline(pipelines(), max_concurrent=self.warmup_step + 1)
450
-
451
- def _step_muon(self, group, qk_logits=None):
452
- params = group["params"]
453
- lr = group["lr"]
454
- weight_decay = group["weight_decay"]
455
- momentum = group["momentum"]
456
- names = group["names"]
457
-
458
- # Apply momentum to all params before routing/expansion.
459
- with record_function("muon::momentum"):
460
- for n, p in zip(names, params):
461
- g = p.grad
462
- if g is None:
463
- continue
464
- g = update_g(self.state, p, g, group, momentum)
465
- p.grad = g
466
-
467
- # Expand expert params by splitting on dim 0.
468
- names, params = _expand_expert_params(names, params, self.expert_keys)
469
-
470
- param_dtensors = []
471
- name_dtensors = []
472
-
473
- param_tensors = []
474
- name_tensors = []
475
-
476
- param_dtensors_small = []
477
- name_dtensors_small = []
478
-
479
- if self.use_distributed_muon:
480
- self.distributed_muon(names=names,
481
- params=params,
482
- group=group,
483
- lr=lr,
484
- weight_decay=weight_decay,
485
- qk_logits=qk_logits)
486
- return
487
-
488
- # For simplicity, we use distributed Muon for small parameters
489
- # whose number of elements is below a threshold.
490
- for n, p in zip(names, params):
491
- if p is None or p.grad is None:
492
- continue
493
- if isinstance(p.data, DTensor):
494
- if all(
495
- isinstance(placement, Replicate)
496
- for placement in p.placements):
497
- param_tensors.append(p)
498
- name_tensors.append(n)
499
- elif p.data.numel() <= self.small_param_numel_threshold:
500
- param_dtensors_small.append(p)
501
- name_dtensors_small.append(n)
502
- else:
503
- param_dtensors.append(p)
504
- name_dtensors.append(n)
505
- elif isinstance(p.data, torch.Tensor):
506
- param_tensors.append(p)
507
- name_tensors.append(n)
508
- else:
509
- raise TypeError(f"Unsupported parameter type: {type(p.data)}")
510
-
511
- logger.debug(
512
- f"[Muon] {len(param_dtensors)} DTensors, {len(param_tensors)} Tensors, "
513
- f"{len(param_dtensors_small)} Small DTensors")
514
-
515
- def group_dtensors(dtensors, names):
516
- # To support different placements, we group parameters by placements
517
- # and run parallel Muon on each group.
518
-
519
- placement_to_params = defaultdict(lambda: ([], []))
520
-
521
- assert len(dtensors) == len(names)
522
- for p, n in zip(dtensors, names):
523
- placement_to_params[tuple([p.placements,
524
- p.device_mesh])][0].append(n)
525
- placement_to_params[tuple([p.placements,
526
- p.device_mesh])][1].append(p)
527
- return placement_to_params
528
-
529
- if len(param_dtensors_small) > 0:
530
- if not dist.is_initialized():
531
- raise RuntimeError(
532
- "Parallel Muon requires torch.distributed to be initialized."
533
- )
534
-
535
- self.distributed_muon(
536
- params=param_dtensors_small,
537
- names=name_dtensors_small,
538
- group=group,
539
- lr=lr,
540
- weight_decay=weight_decay,
541
- qk_logits=qk_logits,
542
- )
543
-
544
- if len(param_dtensors) > 0:
545
- if not dist.is_initialized():
546
- raise RuntimeError(
547
- "Parallel Muon requires torch.distributed to be initialized."
548
- )
549
-
550
- dtensor_group = group_dtensors(param_dtensors, name_dtensors)
551
- for _, (names, params) in dtensor_group.items():
552
- self.parallel(
553
- names,
554
- params,
555
- group,
556
- lr=lr,
557
- weight_decay=weight_decay,
558
- qk_logits=qk_logits,
559
- )
560
-
561
- if len(param_tensors) > 0:
562
- self.base(
563
- name_tensors,
564
- param_tensors,
565
- group,
566
- lr=lr,
567
- weight_decay=weight_decay,
568
- qk_logits=qk_logits,
569
- )
570
-
571
- @torch.no_grad
572
- def step(self, closure=None, qk_logits=None):
573
- """Perform a single optimization step.
574
-
575
- Args:
576
- closure (Callable, optional): A closure that reevaluates the model
577
- and returns the loss.
578
- qk_logits (dict[int, Tensor], optional): A dictionary mapping layer indices
579
- to 1D tensors of shape (num_heads,), representing the maximum
580
- QK logits across all tokens, computed as
581
- (1 / sqrt(head_dim)) * (Q @ K^T).
582
- """
583
- loss = None
584
- if closure is not None:
585
- with torch.enable_grad():
586
- loss = closure()
587
-
588
- for group in self.param_groups:
589
- if group["use_muon"]:
590
- self._step_muon(group, qk_logits=qk_logits)
591
- else:
592
- step_adamw(self.state, group)
593
-
594
- return loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/newton_schulz.py DELETED
@@ -1,50 +0,0 @@
1
- import torch
2
-
3
- from .matmul_transpose_triton import matmul_transpose_assign
4
-
5
- COMM_DTYPE = torch.bfloat16
6
- DEFAULT_CHUNK_SIZE_RATIO = 4
7
-
8
-
9
- # This code snippet is a modified version adapted from the following GitHub repositories:
10
- # https://github.com/KellerJordan/Muon/blob/master/muon.py
11
- # Muon's Newton–Schulz iteration causes high variance in singular values
12
- # Idea: give each iteration its own 3 coefficients and optimize them via gradient descent.
13
- @torch.no_grad()
14
- # matmul_transpose_assign from : https://github.com/nil0x9/flash-muon
15
- def _zeropower_via_newtonschulz5(G, steps):
16
- """
17
- Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a
18
- quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose
19
- of minimizing steps, it turns out to be empirically effective to keep increasing the slope at
20
- zero even beyond the point where the iteration no longer converges all the way to one everywhere
21
- on the interval. This iteration therefore does not produce UV^T but rather something like US'V^T
22
- where S' is diagonal with S_{ii}' ~ Uniform(0.5, 1.5), which turns out not to hurt model
23
- performance at all relative to UV^T, where USV^T = G is the SVD.
24
- """
25
- assert len(G.shape) == 2
26
- assert G.dtype == COMM_DTYPE
27
- X = G # no manual typecast
28
-
29
- if G.size(0) > G.size(1):
30
- X = X.T
31
- # Ensure spectral norm is at most 1
32
- X = X / (X.norm() + 1e-7)
33
- buf1 = torch.empty(X.size(0), X.size(0), dtype=X.dtype, device=X.device)
34
- buf2 = torch.empty(X.size(0), X.size(0), dtype=X.dtype, device=X.device)
35
- # Perform the NS iterations
36
- for a, b, c in [
37
- (4.0848, -6.8946, 2.9270),
38
- (3.9505, -6.3029, 2.6377),
39
- (3.7418, -5.5913, 2.3037),
40
- (2.8769, -3.1427, 1.2046),
41
- (2.8366, -3.0525, 1.2012),
42
- ]:
43
- matmul_transpose_assign(X, buf1)
44
- matmul_transpose_assign(buf1, buf2)
45
- buf1.mul_(b).add_(buf2, alpha=c)
46
- X = torch.addmm(X, buf1, X, alpha=1.0, beta=a)
47
-
48
- if G.size(0) > G.size(1):
49
- X = X.T
50
- return X
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/optimizer/__init__.py DELETED
@@ -1,26 +0,0 @@
1
- import ctypes
2
- import sys
3
-
4
- import importlib
5
- from pathlib import Path
6
- from types import ModuleType
7
-
8
- def _import_from_path(file_path: Path) -> ModuleType:
9
- # We cannot use the module name as-is, after adding it to `sys.modules`,
10
- # it would also be used for other imports. So, we make a module name that
11
- # depends on the path for it to be unique using the hex-encoded hash of
12
- # the path.
13
- path_hash = "{:x}".format(ctypes.c_size_t(hash(file_path.absolute())).value)
14
- module_name = path_hash
15
- spec = importlib.util.spec_from_file_location(module_name, file_path)
16
- if spec is None:
17
- raise ImportError(f"Cannot load spec for {module_name} from {file_path}")
18
- module = importlib.util.module_from_spec(spec)
19
- if module is None:
20
- raise ImportError(f"Cannot load module {module_name} from spec")
21
- sys.modules[module_name] = module
22
- spec.loader.exec_module(module) # type: ignore
23
- return module
24
-
25
-
26
- globals().update(vars(_import_from_path(Path(__file__).parent.parent / "__init__.py")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/pipeline.py DELETED
@@ -1,390 +0,0 @@
1
- import logging
2
- from typing import Generator
3
-
4
- import torch
5
- import torch.distributed as dist
6
- from torch.distributed.tensor import DTensor
7
- from torch.profiler import record_function
8
-
9
- from .core import _muon_state, adjust_lr_for_muon, update_p
10
- from .newton_schulz import COMM_DTYPE, _zeropower_via_newtonschulz5
11
- from .qk_clip import compute_scales
12
-
13
- logger = logging.getLogger(__name__)
14
-
15
- # ======================================================================
16
- # Stage helpers
17
- # ======================================================================
18
-
19
-
20
- def _launch_gather(
21
- params: list[DTensor],
22
- owned_params: list[DTensor],
23
- param_to_state: dict[int, _muon_state],
24
- rank: int,
25
- num_ranks: int,
26
- process_group: dist.ProcessGroup,
27
- ) -> tuple[dist.Work, torch.Tensor, dict[int, torch.Tensor | None], list[int]]:
28
- """Allocate gather buffers, build send/recv, and launch async all-to-all.
29
-
30
- Returns:
31
- work: Async operation handle.
32
- recv_buf: Flat receive buffer (needed by ``_complete_gather``).
33
- gathered_grads: ``{id(p): empty_tensor}`` for owned params,
34
- ``None`` for non-owned.
35
- recv_counts: Per-source-rank element counts.
36
- """
37
- # Allocate gathered-grad buffers
38
- gathered_grads: dict[int, torch.Tensor | None] = {}
39
- for p in params:
40
- state = param_to_state[id(p)]
41
- if rank == state.worker_rank:
42
- gathered_grads[id(p)] = torch.empty(p.shape,
43
- dtype=COMM_DTYPE,
44
- device="cuda")
45
- else:
46
- gathered_grads[id(p)] = None
47
-
48
- # Build send buffer
49
- per_dst: list[list[torch.Tensor]] = [[] for _ in range(num_ranks)]
50
- send_counts = [0] * num_ranks
51
-
52
- for p in params:
53
- state = param_to_state[id(p)]
54
- dst = state.worker_rank
55
- assert dst < num_ranks
56
- shard_elems = state.rank_numels[rank]
57
- g = p.grad
58
- g = g.to_local().to(COMM_DTYPE).contiguous()
59
- assert g.numel() == shard_elems
60
- per_dst[dst].append(g.view(-1))
61
- send_counts[dst] += shard_elems
62
-
63
- assert any(
64
- len(v) > 0 for v in
65
- per_dst), "At least one destination rank must receive a sharded tensor"
66
- per_dst_flat = [t for dst in per_dst for t in dst]
67
- send_buf = torch.cat(per_dst_flat, dim=0)
68
-
69
- # Build recv buffer
70
- recv_counts = [0] * num_ranks
71
- for src in range(num_ranks):
72
- total = 0
73
- for p in owned_params:
74
- state = param_to_state[id(p)]
75
- assert state.worker_rank == rank
76
- total += state.rank_numels[src]
77
- recv_counts[src] = total
78
-
79
- recv_buf = torch.empty(sum(recv_counts), dtype=COMM_DTYPE, device="cuda")
80
-
81
- # Launch async all-to-all
82
- logger.debug(f"send_buf size: {send_buf.numel()}, "
83
- f"recv_buf size: {recv_buf.numel()}, "
84
- f"recv_counts: {recv_counts}, "
85
- f"send_counts: {send_counts}, "
86
- f"process_group: {str(process_group)}")
87
- work = dist.all_to_all_single(
88
- recv_buf,
89
- send_buf,
90
- output_split_sizes=recv_counts,
91
- input_split_sizes=send_counts,
92
- group=process_group,
93
- async_op=True,
94
- )
95
-
96
- return work, recv_buf, gathered_grads, recv_counts
97
-
98
-
99
- def _complete_gather(
100
- recv_buf: torch.Tensor,
101
- recv_counts: list[int],
102
- owned_params: list[DTensor],
103
- gathered_grads: dict[int, torch.Tensor | None],
104
- param_to_state: dict[int, _muon_state],
105
- rank: int,
106
- ) -> None:
107
- """Reconstruct gathered grads from the recv buffer (in-place)."""
108
- off = 0
109
- for src in range(len(recv_counts)):
110
- if recv_counts[src] == 0:
111
- continue
112
-
113
- block = recv_counts[src]
114
- inner_off = 0
115
- for p in owned_params:
116
- state = param_to_state[id(p)]
117
- assert state.worker_rank == rank
118
-
119
- indices = state.rank_indices[src]
120
-
121
- shard_view = gathered_grads[id(p)][indices]
122
- n = shard_view.numel()
123
- assert n > 0
124
-
125
- sg = recv_buf.narrow(0, off + inner_off, n)
126
- sg = sg.reshape(shard_view.shape)
127
- gathered_grads[id(p)][indices] = sg
128
-
129
- inner_off += n
130
- assert inner_off == block
131
- off += block
132
-
133
-
134
- def _compute_ns(
135
- owned_params: list[DTensor],
136
- gathered_grads: dict[int, torch.Tensor | None],
137
- ns_steps: int,
138
- ) -> dict[int, torch.Tensor | None]:
139
- """Run Newton-Schulz orthogonalization on owned parameters.
140
-
141
- Returns:
142
- computed_us: ``{id(p): orthogonalized_update}`` for owned params.
143
- """
144
- computed_us: dict[int, torch.Tensor | None] = {}
145
- for p in owned_params:
146
- u = _zeropower_via_newtonschulz5(gathered_grads[id(p)], ns_steps)
147
- gathered_grads[id(p)] = None # free gathered grad
148
- computed_us[id(p)] = u
149
- return computed_us
150
-
151
-
152
- def _launch_scatter(
153
- params: list[DTensor],
154
- owned_params: list[DTensor],
155
- param_to_state: dict[int, _muon_state],
156
- rank: int,
157
- num_ranks: int,
158
- process_group: dist.ProcessGroup,
159
- computed_us: dict[int, torch.Tensor | None],
160
- ) -> tuple[dist.Work, torch.Tensor, dict[int, torch.Tensor], list[int]]:
161
- """Allocate scatter buffers, build send/recv, and launch async all-to-all.
162
-
163
- Returns:
164
- work: Async operation handle.
165
- recv_buf: Flat receive buffer (needed by ``_complete_scatter``).
166
- scattered_us: ``{id(p): empty_local_tensor}`` for all params.
167
- recv_counts: Per-source-rank element counts.
168
- """
169
- # Allocate scattered-u buffers
170
- scattered_us: dict[int, torch.Tensor] = {}
171
- for p in params:
172
- scattered_us[id(p)] = torch.empty_like(p.to_local(), dtype=COMM_DTYPE)
173
-
174
- # Build send buffer (from computed_us on owner ranks)
175
- per_dst: list[list[torch.Tensor]] = [[] for _ in range(num_ranks)]
176
- send_counts = [0] * num_ranks
177
-
178
- if owned_params:
179
- for p in owned_params:
180
- state = param_to_state[id(p)]
181
-
182
- assert computed_us[id(p)] is not None
183
- u_full = computed_us[id(p)].to(COMM_DTYPE).contiguous()
184
-
185
- total_sent = 0
186
- for dst_rank in range(num_ranks):
187
- indices = state.rank_indices[dst_rank]
188
- su = u_full[indices].flatten()
189
-
190
- n = su.numel()
191
- assert n > 0
192
-
193
- per_dst[dst_rank].append(su)
194
- send_counts[dst_rank] += n
195
- total_sent += n
196
-
197
- assert total_sent == u_full.numel()
198
-
199
- lengths = [len(v) for v in per_dst]
200
- if all(l > 0 for l in lengths):
201
- assert all(
202
- l == lengths[0] for l in lengths
203
- ), "All destination ranks must have the same number of sharded tensor"
204
- per_dst_flat = [t for dst in per_dst for t in dst]
205
- send_buf = torch.cat(per_dst_flat, dim=0)
206
- else:
207
- send_buf = torch.empty(0, dtype=COMM_DTYPE, device="cuda")
208
-
209
- # Build recv buffer
210
- recv_counts = [0] * num_ranks
211
- for src in range(num_ranks):
212
- total = 0
213
- for p in params:
214
- state = param_to_state[id(p)]
215
- if state.worker_rank != src:
216
- continue
217
- total += state.rank_numels[rank]
218
- recv_counts[src] = total
219
-
220
- recv_total = sum(recv_counts)
221
- assert recv_total > 0
222
- recv_buf = torch.empty(recv_total, dtype=COMM_DTYPE, device="cuda")
223
-
224
- # Launch async all-to-all
225
- work = dist.all_to_all_single(
226
- recv_buf,
227
- send_buf,
228
- output_split_sizes=recv_counts,
229
- input_split_sizes=send_counts,
230
- group=process_group,
231
- async_op=True,
232
- )
233
-
234
- return work, recv_buf, scattered_us, recv_counts
235
-
236
-
237
- def _complete_scatter(
238
- recv_buf: torch.Tensor,
239
- recv_counts: list[int],
240
- params: list[DTensor],
241
- param_to_state: dict[int, _muon_state],
242
- rank: int,
243
- scattered_us: dict[int, torch.Tensor],
244
- ) -> None:
245
- """Copy recv buffer into scattered_us (in-place)."""
246
- off = 0
247
- for src in range(len(recv_counts)):
248
- block = recv_counts[src]
249
- if block == 0:
250
- continue
251
-
252
- inner_off = 0
253
- for p in params:
254
- state = param_to_state[id(p)]
255
- if state.worker_rank != src:
256
- continue
257
- n = state.rank_numels[rank]
258
- assert n > 0
259
-
260
- flat_local = recv_buf.narrow(0, off + inner_off,
261
- n).view_as(p.to_local())
262
- scattered_us[id(p)].copy_(flat_local)
263
-
264
- inner_off += n
265
-
266
- assert inner_off == block
267
- off += block
268
-
269
-
270
- def _update_params(
271
- params: list[DTensor],
272
- param_to_state: dict[int, _muon_state],
273
- rank: int,
274
- scattered_us: dict[int, torch.Tensor],
275
- lr: float,
276
- weight_decay: float,
277
- ) -> None:
278
- """Apply weight decay, Muon update, and optional QK clipping."""
279
- for p in params:
280
- state = param_to_state[id(p)]
281
- u_dtensor = DTensor.from_local(
282
- scattered_us[id(p)],
283
- placements=p.placements,
284
- device_mesh=p.device_mesh,
285
- )
286
-
287
- adjusted_lr = adjust_lr_for_muon(lr, p.shape)
288
- update_p(p, u_dtensor, lr, adjusted_lr, weight_decay)
289
-
290
- # QK clipping – applied directly on the local tensor to
291
- # avoid DTensor sharding-propagation issues with _StridedShard.
292
- scales_full = compute_scales(
293
- p,
294
- state.qk_clip_state) if state.qk_clip_state is not None else None
295
- if scales_full is not None:
296
- ratio = p.shape[0] // scales_full.shape[0]
297
- idx0 = state.rank_indices[rank][0]
298
- if isinstance(idx0, slice):
299
- start = idx0.start or 0
300
- idx0 = torch.arange(start,
301
- idx0.stop,
302
- device=scales_full.device)
303
- row_scales = scales_full[idx0 // ratio]
304
- p._local_tensor.mul_(row_scales.view(-1, 1))
305
-
306
-
307
- # ======================================================================
308
- # Main generator – thin orchestrator that wires stages together.
309
- # ======================================================================
310
-
311
-
312
- @torch.no_grad()
313
- def muon_chunk_pipeline(
314
- params: list[DTensor],
315
- param_to_state: dict[int, _muon_state],
316
- rank: int,
317
- ns_steps: int,
318
- lr: float,
319
- weight_decay: float,
320
- none_grad: bool,
321
- ) -> Generator[None, None, None]:
322
- """Process one chunk of parameters through the full Muon pipeline.
323
-
324
- Stages: gather -> compute (Newton-Schulz) -> scatter -> update.
325
-
326
- Each ``yield`` lets :func:`run_pipeline` interleave other chunks so
327
- that communication and computation overlap across chunks. Async
328
- communication is launched via ``async_op=True`` and completed after
329
- the yield with ``work.wait()``.
330
-
331
- Overlap happens because :func:`run_pipeline` admits one new chunk
332
- per iteration (staggered admission). While chunk *N* does NS
333
- compute on the default CUDA stream, chunk *N+1*'s async all-to-all
334
- runs concurrently on the NCCL stream — no separate ``comm_stream``
335
- is required.
336
-
337
- Yields exactly **2** times:
338
-
339
- 1. After launching async all-to-all gather.
340
- 2. After launching async all-to-all scatter.
341
- """
342
- process_group = param_to_state[id(params[0])].process_group
343
- num_ranks = dist.get_world_size(group=process_group)
344
- owned_params = [
345
- p for p in params if param_to_state[id(p)].worker_rank == rank
346
- ]
347
-
348
- # Stages 1-2: launch async gather.
349
- with record_function("muon::launch_gather"):
350
- work, recv_buf, gathered_grads, recv_counts = _launch_gather(
351
- params, owned_params, param_to_state, rank, num_ranks,
352
- process_group)
353
-
354
- if none_grad:
355
- for p in params:
356
- p.grad = None
357
-
358
- yield # --- YIELD 1: other chunks can launch their gather ---
359
-
360
- with record_function("muon::wait_gather"):
361
- work.wait()
362
- _complete_gather(recv_buf, recv_counts, owned_params, gathered_grads,
363
- param_to_state, rank)
364
- del recv_buf
365
-
366
- # Stage 3: Newton-Schulz orthogonalization.
367
- with record_function("muon::newton_schulz"):
368
- computed_us = _compute_ns(owned_params, gathered_grads, ns_steps)
369
- gathered_grads.clear()
370
-
371
- # Stages 4-5: launch async scatter.
372
- with record_function("muon::launch_scatter"):
373
- work, recv_buf, scattered_us, recv_counts = _launch_scatter(
374
- params, owned_params, param_to_state, rank, num_ranks,
375
- process_group, computed_us)
376
- computed_us.clear()
377
-
378
- yield # --- YIELD 2: other chunks can launch their scatter ---
379
-
380
- with record_function("muon::wait_scatter"):
381
- work.wait()
382
- _complete_scatter(recv_buf, recv_counts, params, param_to_state, rank,
383
- scattered_us)
384
- del recv_buf
385
-
386
- # Stage 6: apply parameter updates.
387
- with record_function("muon::update_params"):
388
- _update_params(params, param_to_state, rank, scattered_us, lr,
389
- weight_decay)
390
- scattered_us.clear()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-cu130-x86_64-linux/qk_clip.py DELETED
@@ -1,129 +0,0 @@
1
- import logging
2
- import math
3
- from dataclasses import dataclass
4
-
5
- import torch
6
- from torch.distributed.tensor import DTensor
7
-
8
- logger = logging.getLogger(__name__)
9
-
10
-
11
- def parse_qk_layer(name: str) -> tuple[str | None, int]:
12
- """
13
- Parse a parameter name to check if it is a query/key projection layer
14
- ('wq', 'wk', 'q_proj', 'k_proj') and return (kind, layer_index).
15
-
16
- Returns:
17
- (kind, layer_idx) or (None, -1) if not matched.
18
-
19
- Example:
20
- 'model.3.attn.wq.weight' -> ('wq', 3)
21
- 'model.5.attn.wk.weight' -> ('wk', 5)
22
- 'model.2.attn.q_proj.weight' -> ('q_proj', 2)
23
- 'model.7.attn.k_proj.weight' -> ('k_proj', 7)
24
- 'model.4.attn.v_proj.weight' -> (None, -1)
25
- """
26
- parts = name.split('.')
27
- if len(parts) < 3:
28
- return None, -1
29
-
30
- kind = parts[-2]
31
-
32
- layer_idx = -1
33
- for part in reversed(parts):
34
- if part.isdigit():
35
- layer_idx = int(part)
36
- break
37
-
38
- if kind in ('wq', 'wk', 'q_proj', 'k_proj'):
39
- return kind, layer_idx
40
-
41
- return None, -1
42
-
43
-
44
- @dataclass
45
- class QKClipInfo:
46
- """Per-parameter dynamic info computed from config + runtime logits."""
47
- kind: str | None # 'wq'/'q_proj' or 'wk'/'k_proj' or None
48
- indices: list[int] # which heads to consider for clipping
49
- head_dim: int # from config
50
- threshold: float # from config
51
- logit: torch.Tensor | None
52
-
53
-
54
- def get_qk_clip_info(clip_config, n, qk_logits):
55
- """Extract QK clipping info for a named parameter.
56
-
57
- Args:
58
- clip_config: QK clipping configuration dict (or None).
59
- n: Parameter name string.
60
- qk_logits: Dict mapping layer indices to logit tensors (or None).
61
-
62
- Returns:
63
- QKClipInfo instance with clipping configuration for this parameter.
64
- """
65
- if clip_config is None:
66
- return None
67
-
68
- head_dim = clip_config.get('head_dim')
69
- threshold = clip_config.get('threshold')
70
- kind, layer_idx = parse_qk_layer(n)
71
-
72
- logit, indices = None, []
73
- if qk_logits is not None and kind is not None:
74
- logit = qk_logits[layer_idx]
75
- indices_key = 'q_indices' if 'q' in kind else 'k_indices'
76
- indices = clip_config.get(indices_key, []) or []
77
-
78
- if isinstance(logit, DTensor):
79
- # In TP settings, qk_logits may be DTensor
80
- # We convert it to full tensor here for simplicity
81
- logit = logit.full_tensor()
82
-
83
- return QKClipInfo(
84
- kind=kind,
85
- indices=indices,
86
- head_dim=head_dim,
87
- threshold=threshold,
88
- logit=logit,
89
- )
90
-
91
-
92
- def compute_scales(p, qk_clip_state):
93
- """Compute per-head scaling factors for QK clipping.
94
-
95
- Returns scales tensor if any head exceeds threshold, else None.
96
- """
97
- kind = qk_clip_state.kind
98
- indices = qk_clip_state.indices
99
- head_dim = qk_clip_state.head_dim
100
- threshold = qk_clip_state.threshold
101
- logit = qk_clip_state.logit
102
-
103
- H_global = p.shape[0] // head_dim
104
- scales_full = torch.ones(H_global, device=p.data.device)
105
- scaling = 0
106
-
107
- for logit_idx, head_idx in enumerate(indices):
108
- v_ele = float(logit[logit_idx])
109
- if v_ele > threshold:
110
- new_scale = math.sqrt(threshold / v_ele)
111
- if new_scale < scales_full[head_idx]:
112
- scales_full[head_idx] = new_scale
113
- logger.info(
114
- f"[{kind}] Head {head_idx} exceeded threshold "
115
- f"(value={v_ele:.4f}, threshold={threshold:.4f}) -> applying scale={new_scale:.4f}"
116
- )
117
- scaling += 1
118
-
119
- return scales_full if scaling > 0 else None
120
-
121
-
122
- def qk_clip(p, scales, head_dim):
123
- """Apply per-head scaling to a Q/K projection weight matrix."""
124
- if isinstance(p, torch.nn.Parameter):
125
- W = p.data.view(-1, head_dim, p.data.shape[1])
126
- W.mul_(scales.view(-1, 1, 1))
127
- else:
128
- W = p.view(-1, head_dim, p.shape[1])
129
- W.mul_(scales.view(-1, 1, 1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-rocm70-x86_64-linux/adamw.py DELETED
@@ -1,154 +0,0 @@
1
- from collections import defaultdict
2
- from typing import cast
3
-
4
- import torch
5
- from torch.distributed.tensor import DTensor
6
-
7
-
8
- def fused_adamw(
9
- params: list[torch.Tensor],
10
- grads: list[torch.Tensor],
11
- exp_avgs: list[torch.Tensor],
12
- exp_avg_sqs: list[torch.Tensor],
13
- max_exp_avg_sqs: list[torch.Tensor],
14
- state_steps: list[torch.Tensor],
15
- amsgrad: bool,
16
- beta1: float,
17
- beta2: float,
18
- lr: float | torch.Tensor,
19
- weight_decay: float,
20
- eps: float,
21
- maximize: bool,
22
- ) -> None:
23
- if not params:
24
- return
25
-
26
- # We only shuffle around the lr when it is a Tensor and on CUDA, otherwise, we prefer
27
- # treating it as a scalar.
28
- lr_dict: dict | None = ({
29
- lr.device: lr
30
- } if isinstance(lr, torch.Tensor) and str(lr.device) != "cpu" else None)
31
- grouped_tensors = torch.optim.Optimizer._group_tensors_by_device_and_dtype(
32
- [params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs,
33
- state_steps] # type: ignore[list-item]
34
- )
35
- for (device, _), (
36
- (
37
- device_params_,
38
- device_grads_,
39
- device_exp_avgs_,
40
- device_exp_avg_sqs_,
41
- device_max_exp_avg_sqs,
42
- device_state_steps_,
43
- ),
44
- _,
45
- ) in grouped_tensors.items():
46
- device_params = cast(list[torch.Tensor], device_params_)
47
- device_grads = cast(list[torch.Tensor], device_grads_)
48
- device_exp_avgs = cast(list[torch.Tensor], device_exp_avgs_)
49
- device_exp_avg_sqs = cast(list[torch.Tensor], device_exp_avg_sqs_)
50
- device_state_steps = cast(list[torch.Tensor], device_state_steps_)
51
-
52
- if lr_dict is not None and device not in lr_dict:
53
- lr_dict[device] = lr.to(
54
- device=device, non_blocking=True) # type: ignore[union-attr]
55
- lr = lr_dict[device]
56
- torch._foreach_add_(device_state_steps, 1)
57
- func = torch._fused_adamw_
58
- func(
59
- device_params,
60
- device_grads,
61
- device_exp_avgs,
62
- device_exp_avg_sqs,
63
- device_max_exp_avg_sqs, # type: ignore[arg-type]
64
- device_state_steps,
65
- amsgrad=amsgrad,
66
- lr=lr, # type: ignore[arg-type]
67
- beta1=beta1,
68
- beta2=beta2,
69
- weight_decay=weight_decay,
70
- eps=eps,
71
- maximize=maximize,
72
- )
73
-
74
-
75
- def step_adamw_params(optimizer_state, params, group):
76
- """Run fused AdamW on a list of parameters sharing the same placement.
77
-
78
- Args:
79
- optimizer_state: The optimizer's state dict (self.state in Muon).
80
- params: List of parameters to update.
81
- group: Parameter group dict with lr, adamw_betas, adamw_eps, weight_decay.
82
- """
83
- params_with_grads = []
84
- grads = []
85
- moment1 = []
86
- moment2 = []
87
- max_exp_avg_sqs = []
88
- state_steps = []
89
- lr = group["lr"]
90
- beta1, beta2 = group["adamw_betas"]
91
- eps = group["adamw_eps"]
92
- weight_decay = group["weight_decay"]
93
-
94
- for p in params:
95
- g = p.grad
96
- if g is None:
97
- continue
98
- state = optimizer_state[p]
99
- params_with_grads.append(p)
100
- grads.append(g)
101
- if "step" not in state:
102
- state["step"] = (torch.zeros((),
103
- dtype=torch.float32,
104
- device=p.device))
105
- state["moment1"] = torch.zeros_like(g)
106
- state["moment2"] = torch.zeros_like(g)
107
- moment1.append(state["moment1"])
108
- moment2.append(state["moment2"])
109
- if not isinstance(state["step"], torch.Tensor):
110
- step_tensor = torch.tensor(state["step"],
111
- dtype=torch.float32,
112
- device=p.device)
113
- else:
114
- step_tensor = state["step"]
115
- state_steps.append(step_tensor)
116
-
117
- fused_adamw(
118
- params_with_grads,
119
- grads,
120
- moment1,
121
- moment2,
122
- max_exp_avg_sqs,
123
- state_steps,
124
- amsgrad=False,
125
- beta1=beta1,
126
- beta2=beta2,
127
- lr=lr,
128
- weight_decay=weight_decay,
129
- eps=eps,
130
- maximize=False,
131
- )
132
-
133
-
134
- def step_adamw(optimizer_state, group):
135
- """Dispatch AdamW step, grouping parameters by type and placement.
136
-
137
- Args:
138
- optimizer_state: The optimizer's state dict (self.state in Muon).
139
- group: Parameter group dict.
140
- """
141
- params = group["params"]
142
-
143
- # group params with its type and placement
144
- placement_to_params: dict[tuple, list[torch.Tensor]] = defaultdict(list)
145
- for p in params:
146
- match p:
147
- case DTensor():
148
- placement_to_params[tuple([p.placements,
149
- p.device_mesh])].append(p)
150
- case torch.Tensor():
151
- placement_to_params[tuple([torch.Tensor, None])].append(p)
152
-
153
- for group_params in placement_to_params.values():
154
- step_adamw_params(optimizer_state, group_params, group)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-rocm70-x86_64-linux/async_utils.py DELETED
@@ -1,77 +0,0 @@
1
- import logging
2
- from typing import Generator
3
-
4
- logger = logging.getLogger(__name__)
5
-
6
-
7
- class _Task:
8
- """Internal: wraps a generator, advances one yield at a time."""
9
-
10
- def __init__(self, generator: Generator[None, None, None], index: int):
11
- self._generator = generator
12
- self._index = index
13
- self._steps_completed = 0
14
- self.step() # run to first yield
15
-
16
- def step(self) -> bool:
17
- try:
18
- next(self._generator)
19
- self._steps_completed += 1
20
- logger.debug("pipeline[%d] completed stage %d", self._index,
21
- self._steps_completed)
22
- return True
23
- except StopIteration:
24
- logger.debug("pipeline[%d] finished after %d stages", self._index,
25
- self._steps_completed)
26
- return False
27
-
28
- def close(self):
29
- self._generator.close()
30
-
31
-
32
- def run_pipeline(
33
- pipelines: Generator[Generator[None, None, None], None, None],
34
- max_concurrent: int,
35
- ) -> None:
36
- """Run generator-based pipelines with bounded concurrency.
37
-
38
- Each pipeline is a generator that yields at stage boundaries.
39
- The runtime interleaves pipelines so communication and computation
40
- overlap across chunks.
41
- """
42
- if max_concurrent <= 0:
43
- raise ValueError(f"max_concurrent must be > 0, got {max_concurrent}")
44
-
45
- have_new = True
46
- task_index = 0
47
- previous_tasks: list[_Task] = []
48
-
49
- try:
50
- while have_new or previous_tasks:
51
- running_tasks: list[_Task] = []
52
-
53
- # Admit one new pipeline per iteration (staggered admission).
54
- # Admitting one at a time ensures that while chunk N does NS
55
- # compute on the default stream, chunk N+1's NCCL all-to-all
56
- # runs concurrently on the NCCL stream — creating real
57
- # communication/computation overlap on the GPU.
58
- if have_new and len(previous_tasks) < max_concurrent:
59
- try:
60
- gen = next(pipelines)
61
- task = _Task(gen, task_index)
62
- task_index += 1
63
- running_tasks.append(task)
64
- except StopIteration:
65
- have_new = False
66
-
67
- # Advance every previously-yielded task by one step.
68
- for task in previous_tasks:
69
- if task.step():
70
- running_tasks.append(task)
71
-
72
- previous_tasks = running_tasks
73
- except BaseException:
74
- # Clean up all in-flight generators to release GPU resources.
75
- for task in previous_tasks:
76
- task.close()
77
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-rocm70-x86_64-linux/core.py DELETED
@@ -1,116 +0,0 @@
1
- import math
2
- from dataclasses import dataclass
3
-
4
- import torch
5
- import torch.distributed as dist
6
- from torch.distributed import ProcessGroup
7
- from torch.distributed.tensor import DTensor
8
-
9
-
10
- @dataclass
11
- class _muon_state:
12
- worker_rank: int
13
- process_group: ProcessGroup
14
- rank_indices: dict[int, tuple] # local_rank -> per-dim indices
15
- rank_numels: dict[int, int] # local_rank -> numel
16
- name: str
17
- qk_clip_state: torch.Tensor | None = None
18
-
19
-
20
- def update_g(optimizer_state, p, g, group, momentum):
21
- """Apply momentum update to gradient.
22
-
23
- Args:
24
- optimizer_state: The optimizer's state dict (self.state in Muon).
25
- p: Parameter tensor.
26
- g: Gradient tensor.
27
- group: Parameter group dict.
28
- momentum: Momentum coefficient.
29
-
30
- Returns:
31
- Momentum-updated gradient tensor.
32
- """
33
- state = optimizer_state[p]
34
- buf = state.setdefault("momentum_buffer", torch.zeros_like(g))
35
- torch.add(g, buf, alpha=momentum, out=buf)
36
- if group["nesterov"]:
37
- g.add_(buf, alpha=momentum)
38
- return g
39
- return buf
40
-
41
-
42
- def update_p(p, u, lr, adjusted_lr, weight_decay):
43
- """Apply weight decay and orthogonalized update to parameter.
44
-
45
- Args:
46
- p: Parameter (torch.nn.Parameter or DTensor).
47
- u: Orthogonalized update tensor.
48
- lr: Base learning rate.
49
- adjusted_lr: Size-adjusted learning rate.
50
- weight_decay: Weight decay coefficient.
51
- """
52
- if isinstance(p, torch.nn.Parameter):
53
- # apply weight decay
54
- p.data.mul_(1 - lr * weight_decay)
55
- # apply update
56
- p.data.add_(u, alpha=-adjusted_lr)
57
- else:
58
- p.mul_(1 - lr * weight_decay)
59
- p.add_(u, alpha=-adjusted_lr)
60
-
61
-
62
- def adjust_lr_for_muon(lr, param_shape):
63
- """Scale learning rate based on parameter matrix dimensions.
64
-
65
- Args:
66
- lr: Base learning rate.
67
- param_shape: Shape of the parameter tensor.
68
-
69
- Returns:
70
- Adjusted learning rate.
71
- """
72
- A, B = param_shape[:2]
73
- # We adjust the learning rate and weight decay based on the size of the parameter matrix
74
- # as described in the paper
75
- adjusted_ratio = 0.2 * math.sqrt(max(A, B))
76
- adjusted_lr = lr * adjusted_ratio
77
- return adjusted_lr
78
-
79
-
80
- def default_is_muon(name, x, expert_keys=None):
81
- skip_keys = ["embed_tokens", "lm_head", "tok_embeddings", "output"]
82
- if any(key in name for key in skip_keys):
83
- return False
84
- effective_ndim = x.ndim
85
- if expert_keys and any(key in name for key in expert_keys):
86
- effective_ndim -= 1
87
- return effective_ndim >= 2
88
-
89
-
90
- def get_default_muon_param_groups(model, is_muon_func=None, expert_keys=None):
91
- if is_muon_func is None:
92
- is_muon_func = lambda n, x: default_is_muon(n, x, expert_keys)
93
-
94
- muon_params, muon_names = [], []
95
- non_muon_params = []
96
-
97
- for n, p in model.named_parameters():
98
- if not p.requires_grad:
99
- continue
100
- if is_muon_func(n, p):
101
- muon_params.append(p)
102
- muon_names.append(n)
103
- else:
104
- non_muon_params.append(p)
105
-
106
- return [
107
- {
108
- "params": muon_params,
109
- "names": muon_names,
110
- "use_muon": True,
111
- },
112
- {
113
- "params": non_muon_params,
114
- "use_muon": False,
115
- },
116
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-rocm70-x86_64-linux/distributed/utils.py DELETED
@@ -1,234 +0,0 @@
1
- import torch
2
- import torch.distributed as dist
3
- from torch.distributed import ProcessGroup
4
- from torch.distributed.device_mesh import DeviceMesh
5
- from torch.distributed.tensor import DTensor
6
- from torch.distributed.tensor.placement_types import (Placement, Shard,
7
- _StridedShard)
8
-
9
-
10
- def _is_shard(placement: Placement) -> bool:
11
- """Check if a placement is a shard type (Shard or _StridedShard).
12
-
13
- In PyTorch 2.10+, _StridedShard no longer inherits from Shard, so
14
- ``placement.is_shard()`` returns False for _StridedShard. This helper
15
- handles both old and new hierarchies.
16
- """
17
- return isinstance(placement, (Shard, _StridedShard))
18
-
19
-
20
- def get_slices_of_dtensor(
21
- target: DTensor | torch.Tensor,
22
- local_rank: int,
23
- shard_mesh: DeviceMesh,
24
- shard_placements: tuple[Placement],
25
- ) -> tuple[slice | torch.Tensor, ...]:
26
- """
27
- Get per-dimension indices for a given rank's shard of the target tensor.
28
-
29
- Uses ``Shard.local_shard_size_and_offset`` and
30
- ``_StridedShard.local_shard_size_and_offset`` for correct handling of
31
- both contiguous and strided (non-contiguous) sharding.
32
-
33
- Args:
34
- target (DTensor | torch.Tensor): The target tensor (for its shape).
35
- local_rank (int): The local rank within the shard group.
36
- shard_mesh (DeviceMesh): The shard mesh (only shard dimensions).
37
- shard_placements (tuple[Placement]): The shard placements.
38
-
39
- Returns:
40
- A tuple of indices (one per tensor dim). Each element is either:
41
- - A ``slice`` (for contiguous or unsharded dims)
42
- - A 1-D ``torch.LongTensor`` of indices (for strided sharding)
43
- """
44
-
45
- # find the global rank of the local rank in the shard mesh
46
- rank = sorted(shard_mesh.mesh.flatten().tolist())[local_rank]
47
-
48
- rank_coords = (shard_mesh.mesh == rank).nonzero()
49
-
50
- assert len(rank_coords) == 1
51
- rank_coords = tuple(rank_coords[0].tolist())
52
-
53
- assert len(rank_coords) == len(shard_placements)
54
-
55
- # Track per-shard-dim indices.
56
- # None means "not yet sharded on this dim".
57
- dim_indices: dict[int, torch.Tensor] = {}
58
-
59
- # Caution: Assuming replicate-to-shard of the shard mesh goes with
60
- # left-to-right sharding. This is ensured by the sorting logic of
61
- # construct_shard_mesh function.
62
- for mesh_dim_idx, (rank_coord, placement) in enumerate(
63
- zip(rank_coords, shard_placements)):
64
- assert _is_shard(placement)
65
-
66
- num_chunks = shard_mesh.mesh.shape[mesh_dim_idx]
67
- shard_dim = placement.dim
68
-
69
- # Current effective size on this dim (may already be sub-sharded)
70
- if shard_dim in dim_indices:
71
- curr_size = len(dim_indices[shard_dim])
72
- else:
73
- curr_size = target.size()[shard_dim]
74
-
75
- if curr_size % num_chunks != 0:
76
- raise NotImplementedError(
77
- f"Dimension size {curr_size} is not divisible "
78
- f"by number of ranks {num_chunks} for shard "
79
- f"placement on dim {shard_dim}. (shape: {target.shape})")
80
-
81
- # Compute indices for this level of sharding
82
- if isinstance(placement, _StridedShard):
83
- _shard_size, offsets = _StridedShard.local_shard_size_and_offset(
84
- placement,
85
- curr_size,
86
- num_chunks,
87
- rank_coord,
88
- return_first_offset=False)
89
- new_indices = torch.tensor(offsets, dtype=torch.long)
90
- else:
91
- shard_size, offset = Shard.local_shard_size_and_offset(
92
- curr_size, num_chunks, rank_coord)
93
- new_indices = torch.arange(offset,
94
- offset + shard_size,
95
- dtype=torch.long)
96
-
97
- # Compose with previous indices on this dim
98
- if shard_dim in dim_indices:
99
- dim_indices[shard_dim] = dim_indices[shard_dim][new_indices]
100
- else:
101
- dim_indices[shard_dim] = new_indices
102
-
103
- # Build result tuple
104
- result: list[slice | torch.Tensor] = []
105
- for d in range(len(target.size())):
106
- if d not in dim_indices:
107
- result.append(slice(None))
108
- else:
109
- indices = dim_indices[d]
110
- # Convert contiguous indices to slice for efficiency
111
- if len(indices) > 0:
112
- start = indices[0].item()
113
- expected = torch.arange(start,
114
- start + len(indices),
115
- dtype=torch.long)
116
- if torch.equal(indices, expected):
117
- result.append(slice(start, start + len(indices)))
118
- else:
119
- result.append(indices)
120
- else:
121
- result.append(slice(0, 0))
122
-
123
- return tuple(result)
124
-
125
-
126
- _ranks_to_dist_cache: dict[tuple[int, ...], tuple[DeviceMesh,
127
- ProcessGroup]] = dict()
128
-
129
-
130
- def construct_shard_mesh(
131
- placements: tuple[Placement],
132
- mesh: DeviceMesh,
133
- ) -> tuple[DeviceMesh, ProcessGroup, tuple[Placement, ...]]:
134
- """Construct shard sub-mesh and ProcessGroup for all-to-all communication.
135
-
136
- Given a DTensor's placements and device mesh, extracts the "shard group"
137
- — the set of ranks that together hold all shards of the same replica —
138
- and creates a ProcessGroup for all-to-all among them.
139
-
140
- Steps:
141
- 1. Sort placements: Replicate first, then Shard by (dim, granularity).
142
- 2. Permute the mesh tensor to match the sorted order.
143
- 3. Collapse Replicate dims → list of shard sub-meshes (one per replica).
144
- 4. Create/retrieve a cached ProcessGroup for the current rank's sub-mesh.
145
-
146
- Example — 8 GPUs, mesh shape (2, 2, 2),
147
- placements ``[Shard(0), Replicate, _StridedShard(0)]``::
148
-
149
- Step 1 — Sort: [Replicate, _StridedShard(0), Shard(0)]
150
- Permutation: [1, 2, 0]
151
-
152
- Step 2 — Permute mesh dims by [1, 2, 0]:
153
- Original: Permuted:
154
- [[[0,1],[2,3]], [[[0,2],[1,3]],
155
- [[4,5],[6,7]]] [[4,6],[5,7]]]
156
-
157
- Step 3 — Unbind replicate dim (dim 0), giving 2 shard sub-meshes:
158
- sub-mesh 0 = [[0,2],[1,3]] (replica group 0)
159
- sub-mesh 1 = [[4,6],[5,7]] (replica group 1)
160
- shard_placements = (_StridedShard(0), Shard(0))
161
-
162
- Step 4 — Rank 0 → ProcessGroup([0,1,4,5])
163
- Rank 2 → ProcessGroup([2,3,6,7])
164
-
165
- Returns:
166
- ``(shard_mesh, process_group, shard_placements)``
167
- """
168
- my_rank = dist.get_rank()
169
- assert mesh.mesh.device.type == 'cpu'
170
-
171
- # -- Fast path: 1D all-shard mesh → reuse existing PG. ----------------
172
- # This avoids a non-collective dist.new_group() call, which would
173
- # deadlock when only a subset of ranks call this function (e.g. expert
174
- # DTensors on a TP submesh where ranks 0-3 and 4-7 call separately).
175
- if mesh.ndim == 1 and len(placements) == 1 and _is_shard(placements[0]):
176
- key = (*mesh.mesh.shape, *mesh.mesh.flatten().tolist())
177
- if key not in _ranks_to_dist_cache:
178
- _ranks_to_dist_cache[key] = (mesh, mesh.get_group())
179
- return (*_ranks_to_dist_cache[key], tuple(placements))
180
-
181
- mesh_tensor = mesh.mesh.clone()
182
-
183
- # -- Step 1: Sort placements (Replicate first, then Shard by dim). ------
184
- # _StridedShard comes BEFORE regular Shard on the same dim so that
185
- # get_slices_of_dtensor applies the outer sharding first, matching
186
- # DTensor's left-to-right (outer-to-inner) composition order.
187
- def _sort_key(item):
188
- index, placement = item
189
- assert not placement.is_partial(), "Partial placement not supported"
190
- if placement.is_replicate():
191
- return (-1, 0, index)
192
- assert _is_shard(placement), f"Unsupported: {type(placement)}"
193
- split = (-1 / placement.split_factor if isinstance(
194
- placement, _StridedShard) else 0)
195
- return (placement.dim, split, index)
196
-
197
- indexed = sorted(enumerate(placements), key=_sort_key)
198
- perm, sorted_placements = zip(*indexed)
199
-
200
- # -- Step 2: Permute mesh to match sorted placement order. --------------
201
- sorted_mesh = mesh_tensor.permute(perm)
202
-
203
- # -- Step 3: Collapse replicate dims → list of shard sub-meshes. --------
204
- # E.g. mesh (2, 3, 4, 4) with [R, R, S(0), S(1)] → 6 sub-meshes of (4, 4)
205
- num_rep = sum(1 for p in sorted_placements if p.is_replicate())
206
- if num_rep > 0:
207
- if num_rep > 1:
208
- sorted_mesh = sorted_mesh.flatten(0, num_rep - 1)
209
- shard_meshes = list(torch.unbind(sorted_mesh, dim=0))
210
- else:
211
- shard_meshes = [sorted_mesh]
212
- shard_placements = sorted_placements[num_rep:]
213
- assert len(shard_placements) == len(set(shard_placements))
214
-
215
- # -- Step 4: Create/retrieve ProcessGroup for current rank's sub-mesh. --
216
- # All ranks must call dist.new_group in the same order, even though each
217
- # rank only joins one group.
218
- def _cache_key(t: torch.Tensor) -> tuple:
219
- return (*t.shape, *t.flatten().tolist())
220
-
221
- my_key = None
222
- for sm in shard_meshes:
223
- key = _cache_key(sm)
224
- if (my_rank == sm).any().item():
225
- assert my_key is None, "Rank appears in multiple shard groups"
226
- my_key = key
227
- if key not in _ranks_to_dist_cache:
228
- pg = dist.new_group(sm.flatten().tolist())
229
- _ranks_to_dist_cache[key] = (
230
- DeviceMesh(device_type="cuda", mesh=sm),
231
- pg,
232
- )
233
-
234
- return (*_ranks_to_dist_cache[my_key], shard_placements)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-rocm70-x86_64-linux/matmul_transpose_triton.py DELETED
@@ -1,121 +0,0 @@
1
- # MIT License
2
- #
3
- # Copyright (c) 2025 Tianyang Lin
4
- #
5
- # Permission is hereby granted, free of charge, to any person obtaining a copy
6
- # of this software and associated documentation files (the "Software"), to deal
7
- # in the Software without restriction, including without limitation the rights
8
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- # copies of the Software, and to permit persons to whom the Software is
10
- # furnished to do so, subject to the following conditions:
11
- #
12
- # The above copyright notice and this permission notice shall be included in all
13
- # copies or substantial portions of the Software.
14
- #
15
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- # SOFTWARE.
22
-
23
- import torch
24
- import triton
25
- import triton.language as tl
26
-
27
-
28
- def get_autotune_config():
29
- return [
30
- triton.Config(
31
- {
32
- 'BLOCK_SIZE_M': blk_m,
33
- 'BLOCK_SIZE_K': blk_k,
34
- 'GROUP_SIZE_M': grp_sz
35
- },
36
- num_stages=n_stages,
37
- num_warps=n_warps) for blk_m in [32, 64, 128]
38
- for blk_k in [32, 64] for grp_sz in [8] for n_stages in [3, 4, 5]
39
- for n_warps in [4, 8]
40
- ]
41
-
42
-
43
- @triton.autotune(
44
- configs=get_autotune_config(),
45
- key=['M', 'K'],
46
- )
47
- @triton.jit
48
- def mmt_kernel(x, y, M, K, stride_xm, stride_xk, stride_ym, stride_yn,
49
- BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
50
- GROUP_SIZE_M: tl.constexpr):
51
- """
52
- Core kernel jit function of matmul_transpose that computes y = x @ x.T
53
- The code is a simple adaptation from the triton `matmul` tutorial:
54
- https://triton-lang.org/main/getting-started/tutorials/03-matrix-multiplication.html
55
- """
56
- pid = tl.program_id(axis=0)
57
- num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
58
- num_pid_n = tl.cdiv(M, BLOCK_SIZE_M)
59
- num_pid_in_group = GROUP_SIZE_M * num_pid_n
60
- group_id = pid // num_pid_in_group
61
- first_pid_m = group_id * GROUP_SIZE_M
62
- group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
63
- pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
64
- pid_n = (pid % num_pid_in_group) // group_size_m
65
- if pid_m > pid_n:
66
- return
67
-
68
- offs_xm = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
69
- offs_xn = (pid_n * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
70
- offs_k = tl.arange(0, BLOCK_SIZE_K)
71
- # we use a & b ptrs to denote different rows of x.
72
- a_ptrs = x + (offs_xm[:, None] * stride_xm + offs_k[None, :] * stride_xk)
73
- b_ptrs = x + (offs_xn[:, None] * stride_xm + offs_k[None, :] * stride_xk)
74
-
75
- accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_M), dtype=tl.float32)
76
-
77
- for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
78
- a = tl.load(a_ptrs,
79
- mask=offs_k[None, :] < K - k * BLOCK_SIZE_K,
80
- other=0.0)
81
- b = tl.load(b_ptrs,
82
- mask=offs_k[None, :] < K - k * BLOCK_SIZE_K,
83
- other=0.0)
84
- accumulator = tl.dot(a, tl.permute(b, (1, 0)), accumulator)
85
- a_ptrs += BLOCK_SIZE_K * stride_xk
86
- b_ptrs += BLOCK_SIZE_K * stride_xk
87
- # use dtype.element_ty to accommodate different input datatypes as in cpp templates
88
- # https://github.com/triton-lang/triton/issues/2252
89
- c = accumulator.to(x.dtype.element_ty)
90
-
91
- offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
92
- offs_cn = pid_n * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
93
- c_ptrs = y + stride_ym * offs_cm[:, None] + stride_yn * offs_cn[None, :]
94
- c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < M)
95
- tl.store(c_ptrs, c, mask=c_mask)
96
-
97
- # transpose and copy
98
- if pid_m < pid_n:
99
- ct_ptrs = y + stride_ym * offs_cn[:,
100
- None] + stride_yn * offs_cm[None, :]
101
- ct_mask = (offs_cn[:, None] < M) & (offs_cm[None, :] < M)
102
- tl.store(ct_ptrs, tl.permute(c, (1, 0)), mask=ct_mask)
103
-
104
-
105
- def matmul_transpose_assign(d_in, d_out):
106
- assert d_in.is_cuda, "Input `d_in` must be a CUDA tensor"
107
- assert d_out.is_cuda, "Input `d_out` must be a CUDA tensor"
108
- assert d_in.device == d_out.device, "Inputs `d_in` and `d_out` must be on the same CUDA device"
109
- assert d_in.dtype == d_out.dtype, "Inputs must have the same data type"
110
- assert d_in.ndim == 2, "Input `d_in` must be a 2D tensor"
111
- assert d_out.ndim == 2, "Input `d_out` must be a 2D tensor"
112
- assert d_in.size(0) == d_out.size(0) == d_out.size(0), \
113
- "First dimension of `d_in` must match first and second dimension of `d_out`"
114
-
115
- d_in = d_in.contiguous()
116
- M, K = d_in.shape
117
- grid = lambda META: (triton.cdiv(M, META['BLOCK_SIZE_M']) * triton.cdiv(
118
- M, META['BLOCK_SIZE_M']), )
119
- with torch.cuda.device(d_in.device.index):
120
- mmt_kernel[grid](d_in, d_out, M, K, d_in.stride(0), d_in.stride(1),
121
- d_out.stride(0), d_out.stride(1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-rocm70-x86_64-linux/metadata.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "python-depends": []
3
- }
 
 
 
 
build/torch210-cxx11-rocm70-x86_64-linux/muon.py DELETED
@@ -1,594 +0,0 @@
1
- import logging
2
- import types
3
- from collections import defaultdict
4
- from typing import Any
5
-
6
- import torch
7
- import torch.distributed as dist
8
- from torch.distributed.tensor import DTensor, Replicate, Shard
9
- from torch.profiler import record_function
10
-
11
- from .adamw import step_adamw
12
- from .async_utils import run_pipeline
13
- from .core import (_muon_state, adjust_lr_for_muon,
14
- get_default_muon_param_groups, update_g, update_p)
15
- from .distributed.utils import (_is_shard, construct_shard_mesh,
16
- get_slices_of_dtensor)
17
- from .newton_schulz import (COMM_DTYPE, DEFAULT_CHUNK_SIZE_RATIO,
18
- _zeropower_via_newtonschulz5)
19
- from .pipeline import muon_chunk_pipeline
20
- from .qk_clip import compute_scales, get_qk_clip_info, qk_clip
21
-
22
- logger = logging.getLogger(__name__)
23
-
24
-
25
- def _expand_expert_params(names, params, expert_keys):
26
- """Expand expert params by splitting on dim 0 (expert dimension).
27
-
28
- Params whose name matches any key in ``expert_keys`` are treated as
29
- expert-parallel tensors. Their outermost dimension is the expert
30
- dimension: an ``(E, out, in)`` tensor becomes ``E`` separate 2D
31
- ``nn.Parameter`` views so that in-place updates propagate back to
32
- the original storage.
33
-
34
- Non-expert params with ``ndim > 2`` trigger an ``AssertionError`` —
35
- if they are expert params, their key must be added to ``expert_keys``.
36
-
37
- The grad must already be set on each expert param (e.g. after momentum).
38
-
39
- For DTensor expert params, placements that shard on dim 0 (expert dim)
40
- are consumed by the split. Non-dim-0 shard placements (e.g. TP) are
41
- preserved: each 2D slice is wrapped as a DTensor on the corresponding
42
- submesh so the parallel pipeline handles the TP communication.
43
- """
44
- expanded_names = []
45
- expanded_params = []
46
-
47
- for n, p in zip(names, params):
48
- is_expert = expert_keys and any(key in n for key in expert_keys)
49
- is_dtensor = isinstance(p.data, DTensor)
50
-
51
- if not is_expert:
52
- assert p.data.ndim <= 2, (
53
- f"Param {n} has ndim={p.data.ndim} but does not match "
54
- f"expert_keys={expert_keys}. If this is an expert param, "
55
- f"add its key to expert_keys.")
56
- expanded_names.append(n)
57
- expanded_params.append(p)
58
- continue
59
-
60
- g = p.grad
61
- assert g is not None, (
62
- f"Expert param {n} must have grad set before expansion")
63
-
64
- tp_mesh = None
65
- tp_placements_2d = None
66
-
67
- if is_dtensor:
68
- local_data = p.to_local()
69
- local_grad = g.to_local() if isinstance(g, DTensor) else g
70
-
71
- # Find non-dim-0 shard placements (e.g. TP sharding).
72
- # After splitting on dim 0, Shard(k) becomes Shard(k-1).
73
- tp_dim_indices = []
74
- tp_placements_2d = []
75
- for i, pl in enumerate(p.placements):
76
- if _is_shard(pl) and pl.dim != 0:
77
- tp_dim_indices.append(i)
78
- tp_placements_2d.append(Shard(pl.dim - 1))
79
-
80
- if tp_dim_indices:
81
- tp_dim_names = tuple(p.device_mesh.mesh_dim_names[i]
82
- for i in tp_dim_indices)
83
- if len(tp_dim_names) == 1:
84
- tp_mesh = p.device_mesh[tp_dim_names[0]]
85
- else:
86
- tp_mesh = p.device_mesh[tp_dim_names]
87
- else:
88
- local_data = p.data
89
- local_grad = g
90
-
91
- # Expand: split dim 0, reshape each slice to 2D.
92
- num_local_experts = local_data.shape[0]
93
- for i in range(num_local_experts):
94
- slice_data = local_data[i]
95
- slice_grad = local_grad[i]
96
-
97
- if tp_mesh is not None:
98
- # Wrap as DTensor on TP submesh so the pipeline handles
99
- # TP communication (gather/scatter across TP ranks).
100
- dt_data = DTensor.from_local(slice_data,
101
- device_mesh=tp_mesh,
102
- placements=tp_placements_2d)
103
- dt_grad = DTensor.from_local(slice_grad,
104
- device_mesh=tp_mesh,
105
- placements=tp_placements_2d)
106
- expert_param = torch.nn.Parameter(dt_data, requires_grad=False)
107
- expert_param.grad = dt_grad
108
- else:
109
- expert_param = torch.nn.Parameter(slice_data,
110
- requires_grad=False)
111
- expert_param.grad = slice_grad
112
-
113
- expanded_names.append(f"{n}[{i}]")
114
- expanded_params.append(expert_param)
115
-
116
- p.grad = None # allow expert grad storage to be freed after pipeline
117
-
118
- return expanded_names, expanded_params
119
-
120
-
121
- class Muon(torch.optim.Optimizer):
122
- """
123
- Muon - MomentUm Orthogonalized by Newton-schulz
124
-
125
- Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-
126
- processing step, in which each 2D parameter's update is replaced with the nearest orthogonal
127
- matrix. To efficiently orthogonalize each update, we use a Newton-Schulz iteration, which has
128
- the advantage that it can be stably run in bfloat16 on the GPU.
129
-
130
- Some warnings:
131
- - We believe this optimizer is unlikely to work well for training with small batch size.
132
- - We believe it may not work well for finetuning pretrained models, but we haven't tested this.
133
-
134
- Arguments:
135
- model: The model to be optimized by Muon.
136
- is_muon_func: A function that takes a parameter and its name, and returns whether the parameter should be optimized by Muon.
137
- lr: The learning rate. The updates will have spectral norm of `lr`. (0.02 is a good default)
138
- momentum: The momentum used by the internal SGD. (0.95 is a good default)
139
- nesterov: Whether to use Nesterov-style momentum in the internal SGD. (recommended)
140
- ns_steps: The number of Newton-Schulz iterations to run. (6 is probably always enough)
141
- weight_decay: The weight decay for Muon and AdamW.
142
- Parameters that are {0, 1}-D or are detected as being the embed or lm_head will be optimized by AdamW instead.
143
- adamw_lr: The learning rate for the internal AdamW.
144
- adamw_betas: The betas for the internal AdamW.
145
- adamw_eps: The epsilon for the internal AdamW.
146
- none_grad: Whether to set p.grad to None after gathering the gradients. This can save memory.
147
- debug: Whether to print debug information.
148
- clip_info : Configuration for QK clipping. Expected keys:
149
- - "q_indices" (list[int]): Indices of query heads to consider.
150
- - "k_indices" (list[int]): Indices of key heads to consider.
151
- - "head_dim" (int): Dimensionality of each attention head.
152
- - "threshold" (float): Threshold value; heads whose QK logits exceed
153
- this value will be scaled down.
154
- Default is:
155
- {
156
- "q_indices": [],
157
- "k_indices": [],
158
- "head_dim": 128,
159
- "threshold": 100
160
- }
161
- warmup_step : How many all2all gather, compute operations are launched in advance
162
- before the corresponding all2all scatter steps begin.
163
- A higher warmup_step increases memory usage but can improve
164
- performance by overlapping communication.
165
- Parallel muon only.
166
- chunk_size : Batch size of parameters to process in each
167
- all2all gather/compute/scatter step.
168
- Use shard ranks * DEFAULT_CHUNK_SIZE_RATIO when -1 is specified.
169
- use_distributed_muon: Use distributed muon by Liu et al. (2024).
170
- For testing purpose only.
171
- small_param_numel_threshold: Threshold for classifying parameters as small and falling back to distributed Muon
172
- expert_keys: List of strings to identify expert-parallel parameters.
173
- If any key appears in a parameter's name, its outermost
174
- dimension is treated as the expert dimension and expanded
175
- into per-expert 2D params for Muon. For example,
176
- ``expert_keys=["experts"]`` matches any param whose name
177
- contains "experts". 3D+ params not matched by any key
178
- will raise an error.
179
- """
180
-
181
- def __init__(self,
182
- params,
183
- lr=1e-3,
184
- momentum=0.95,
185
- nesterov=True,
186
- ns_steps=5,
187
- weight_decay=0.1,
188
- adamw_betas=(0.9, 0.95),
189
- adamw_eps=1e-8,
190
- none_grad=True,
191
- debug=False,
192
- clip_config=None,
193
- warmup_step=5,
194
- chunk_size=-1,
195
- use_distributed_muon=False,
196
- small_param_numel_threshold=65536,
197
- expert_keys=None):
198
- defaults = dict(
199
- lr=lr,
200
- weight_decay=weight_decay,
201
- momentum=momentum,
202
- nesterov=nesterov,
203
- ns_steps=ns_steps,
204
- adamw_betas=adamw_betas,
205
- adamw_eps=adamw_eps,
206
- none_grad=none_grad,
207
- use_muon=True,
208
- )
209
- error_message = "The key 'use_muon' is not set in parameter group {idx}. Assuming all parameters in the group will use muon optimization, which may lead to unexpected behavior."
210
- instruction_code = "\n\n please follow this code snippet \n```optimizer = get_kernel('motif-technologies/optimizer')\n\n\nparams = optimizer.muon.get_default_muon_param_groups(model)\n\noptim = optimizer.Muon(params, ...)```"
211
-
212
- if isinstance(params, types.GeneratorType):
213
- raise ValueError(error_message.format(idx=0) + instruction_code)
214
- for _idx, param_group in enumerate(params):
215
- if param_group.get("use_muon", None) is None:
216
- raise ValueError(
217
- error_message.format(idx=_idx) + instruction_code)
218
-
219
- super().__init__(params, defaults)
220
-
221
- self.debug = debug
222
- self.clip_config = clip_config if clip_config is not None else {
223
- "q_indices": [],
224
- "k_indices": [],
225
- "head_dim": 128,
226
- "threshold": 100,
227
- }
228
- self.warmup_step = warmup_step
229
- self.chunk_size = chunk_size
230
- self.use_distributed_muon = use_distributed_muon
231
- self.small_param_numel_threshold = small_param_numel_threshold
232
- self.expert_keys = expert_keys
233
-
234
- def _calc_flops(self, G, steps):
235
- assert len(G.shape) == 2
236
- M, N = G.shape
237
- if M > N:
238
- M, N = N, M
239
-
240
- return steps * ((M**3) * 2 + (M**2 * N) * 4 + M * N * 2 + M**2 * 3)
241
-
242
- def get_shard_mesh(self, p):
243
- """
244
- Get the shard mesh for a parameter p on the given rank.
245
- """
246
- assert isinstance(
247
- p, DTensor), "Parallel Muon only supports DTensor parameters."
248
-
249
- shard_mesh, shard_pg, shard_placements = construct_shard_mesh(
250
- p.placements, p.device_mesh)
251
-
252
- return shard_mesh, shard_pg, shard_placements
253
-
254
- def init_state_and_assign_params(self, names, params, group, qk_logits):
255
- param_to_state = {}
256
- param_to_flops = {}
257
-
258
- total_flops = 0
259
- for p in params:
260
- g = p.grad
261
- if g is None:
262
- continue
263
- assert g.ndim == 2, "Muon only supports 2D parameters."
264
-
265
- flops = self._calc_flops(g, group["ns_steps"])
266
- param_to_flops[id(p)] = flops
267
- total_flops += flops
268
-
269
- if self.debug:
270
- logger.debug("Total TFLOPs for Muon: %.2f TFLOPs",
271
- total_flops / 1e12)
272
-
273
- paired = list(zip(names, params))
274
-
275
- paired_sorted = sorted(paired,
276
- key=lambda x: param_to_flops[id(x[1])],
277
- reverse=True)
278
-
279
- names_sorted, params_sorted = zip(*paired_sorted)
280
- ordered_names = list(names_sorted)
281
- ordered_params = list(params_sorted)
282
-
283
- round_robin = 0
284
- mesh = ordered_params[0].device_mesh
285
- placements = ordered_params[0].placements
286
-
287
- shard_mesh, shard_pg, shard_placements = self.get_shard_mesh(
288
- ordered_params[0])
289
- shard_mesh_flattened = shard_mesh.mesh.flatten()
290
- num_ranks = dist.get_world_size(group=shard_pg)
291
-
292
- for n, p in zip(ordered_names, ordered_params):
293
- if mesh != p.device_mesh:
294
- raise ValueError("All parameters must be on the same mesh.")
295
- if placements != p.placements:
296
- raise ValueError("All parameters must have same placements.")
297
-
298
- worker_rank = shard_mesh_flattened[round_robin].item() % num_ranks
299
- round_robin = (round_robin + 1) % len(shard_mesh_flattened)
300
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
301
-
302
- # Precompute per-rank indices and numels for all-to-all.
303
- rank_indices: dict[int, tuple] = {}
304
- rank_numels: dict[int, int] = {}
305
- for r in range(num_ranks):
306
- indices = get_slices_of_dtensor(p, r, shard_mesh,
307
- shard_placements)
308
- rank_indices[r] = indices
309
- numel = 1
310
- for idx, dim_size in zip(indices, p.shape):
311
- if isinstance(idx, slice):
312
- start, stop, step = idx.indices(dim_size)
313
- numel *= max(0, (stop - start + (step - 1)) // step)
314
- else:
315
- numel *= len(idx)
316
- rank_numels[r] = numel
317
-
318
- param_to_state[id(p)] = _muon_state(
319
- worker_rank=worker_rank,
320
- process_group=shard_pg,
321
- rank_indices=rank_indices,
322
- rank_numels=rank_numels,
323
- name=n,
324
- qk_clip_state=qk_clip_state,
325
- )
326
-
327
- return param_to_state, ordered_params
328
-
329
- def base(self, names, params, group, lr, weight_decay, qk_logits):
330
- # Momentum is already applied by _step_muon before this method.
331
- for n, p in zip(names, params):
332
- g = p.grad
333
- if g is None:
334
- continue
335
-
336
- u = _zeropower_via_newtonschulz5(g.to(COMM_DTYPE),
337
- steps=group["ns_steps"])
338
-
339
- adjusted_lr = adjust_lr_for_muon(lr, p.shape)
340
- update_p(p, u, lr, adjusted_lr, weight_decay)
341
-
342
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
343
-
344
- scales_full = compute_scales(
345
- p, qk_clip_state) if qk_clip_state is not None else None
346
- if scales_full is not None:
347
- qk_clip(p, scales_full, qk_clip_state.head_dim)
348
-
349
- def distributed_muon(
350
- self,
351
- names: list[str],
352
- params: list[torch.nn.Parameter],
353
- group: dict[str, Any],
354
- lr: float,
355
- weight_decay: float,
356
- qk_logits: list[torch.Tensor | DTensor] | None,
357
- ):
358
- """ Implementation of Distributed Muon by Liu et al. """
359
-
360
- # Momentum is already applied by _step_muon before this method.
361
- for n, p in zip(names, params):
362
- g = p.grad
363
- if g is None:
364
- continue
365
-
366
- # Gather G
367
- if isinstance(p.data, DTensor):
368
- g_full = g.full_tensor()
369
- p_full = p.data.full_tensor()
370
- else:
371
- g_full = g
372
- p_full = p
373
-
374
- u_full = _zeropower_via_newtonschulz5(g_full.to(COMM_DTYPE),
375
- steps=group["ns_steps"])
376
-
377
- adjusted_lr = adjust_lr_for_muon(lr, p_full.shape)
378
- update_p(p_full, u_full, lr, adjusted_lr, weight_decay)
379
-
380
- qk_clip_state = get_qk_clip_info(self.clip_config, n, qk_logits)
381
-
382
- scales_full = compute_scales(
383
- p_full, qk_clip_state) if qk_clip_state is not None else None
384
-
385
- if scales_full is not None:
386
- qk_clip(p_full, scales_full, qk_clip_state.head_dim)
387
-
388
- if isinstance(p.data, DTensor):
389
- ndims = len(p.device_mesh.mesh.shape)
390
- p_replicate = DTensor.from_local(
391
- p_full,
392
- device_mesh=p.device_mesh,
393
- placements=[Replicate() for _ in range(ndims)],
394
- )
395
-
396
- p_sharded = p_replicate.redistribute(
397
- device_mesh=p.device_mesh,
398
- placements=p.placements,
399
- )
400
-
401
- p.copy_(p_sharded)
402
-
403
- def parallel(self, names, params, group, lr, weight_decay, qk_logits):
404
- """
405
- Perform a parallel optimization step using Muon.
406
-
407
- Parameters are chunked and each chunk is processed by a
408
- :func:`muon_chunk_pipeline` generator. :func:`run_pipeline`
409
- interleaves multiple chunks so that communication and computation
410
- overlap across chunks (the same overlap previously achieved by the
411
- warmup + main-loop index scheduling).
412
- """
413
-
414
- # Momentum is already applied by _step_muon before this method.
415
-
416
- param_to_state, ordered_params = self.init_state_and_assign_params(
417
- names, params, group, qk_logits)
418
-
419
- # Compute local rank for this group's shard process group.
420
- shard_pg = param_to_state[id(ordered_params[0])].process_group
421
- rank = dist.get_rank(group=shard_pg)
422
-
423
- if self.chunk_size == -1:
424
- shard_ranks = dist.get_world_size(param_to_state[id(
425
- ordered_params[0])].process_group)
426
- chunk_size = shard_ranks * DEFAULT_CHUNK_SIZE_RATIO
427
- elif self.chunk_size > 0:
428
- chunk_size = self.chunk_size
429
- else:
430
- raise ValueError("chunk_size must be -1 or a positive integer.")
431
-
432
- def pipelines():
433
- for start in range(0, len(ordered_params), chunk_size):
434
- chunk = ordered_params[start:start + chunk_size]
435
- if chunk:
436
- yield muon_chunk_pipeline(
437
- params=chunk,
438
- param_to_state=param_to_state,
439
- rank=rank,
440
- ns_steps=group["ns_steps"],
441
- lr=lr,
442
- weight_decay=weight_decay,
443
- none_grad=group["none_grad"],
444
- )
445
-
446
- with record_function("muon::barrier"):
447
- dist.barrier()
448
- with record_function("muon::pipeline"):
449
- run_pipeline(pipelines(), max_concurrent=self.warmup_step + 1)
450
-
451
- def _step_muon(self, group, qk_logits=None):
452
- params = group["params"]
453
- lr = group["lr"]
454
- weight_decay = group["weight_decay"]
455
- momentum = group["momentum"]
456
- names = group["names"]
457
-
458
- # Apply momentum to all params before routing/expansion.
459
- with record_function("muon::momentum"):
460
- for n, p in zip(names, params):
461
- g = p.grad
462
- if g is None:
463
- continue
464
- g = update_g(self.state, p, g, group, momentum)
465
- p.grad = g
466
-
467
- # Expand expert params by splitting on dim 0.
468
- names, params = _expand_expert_params(names, params, self.expert_keys)
469
-
470
- param_dtensors = []
471
- name_dtensors = []
472
-
473
- param_tensors = []
474
- name_tensors = []
475
-
476
- param_dtensors_small = []
477
- name_dtensors_small = []
478
-
479
- if self.use_distributed_muon:
480
- self.distributed_muon(names=names,
481
- params=params,
482
- group=group,
483
- lr=lr,
484
- weight_decay=weight_decay,
485
- qk_logits=qk_logits)
486
- return
487
-
488
- # For simplicity, we use distributed Muon for small parameters
489
- # whose number of elements is below a threshold.
490
- for n, p in zip(names, params):
491
- if p is None or p.grad is None:
492
- continue
493
- if isinstance(p.data, DTensor):
494
- if all(
495
- isinstance(placement, Replicate)
496
- for placement in p.placements):
497
- param_tensors.append(p)
498
- name_tensors.append(n)
499
- elif p.data.numel() <= self.small_param_numel_threshold:
500
- param_dtensors_small.append(p)
501
- name_dtensors_small.append(n)
502
- else:
503
- param_dtensors.append(p)
504
- name_dtensors.append(n)
505
- elif isinstance(p.data, torch.Tensor):
506
- param_tensors.append(p)
507
- name_tensors.append(n)
508
- else:
509
- raise TypeError(f"Unsupported parameter type: {type(p.data)}")
510
-
511
- logger.debug(
512
- f"[Muon] {len(param_dtensors)} DTensors, {len(param_tensors)} Tensors, "
513
- f"{len(param_dtensors_small)} Small DTensors")
514
-
515
- def group_dtensors(dtensors, names):
516
- # To support different placements, we group parameters by placements
517
- # and run parallel Muon on each group.
518
-
519
- placement_to_params = defaultdict(lambda: ([], []))
520
-
521
- assert len(dtensors) == len(names)
522
- for p, n in zip(dtensors, names):
523
- placement_to_params[tuple([p.placements,
524
- p.device_mesh])][0].append(n)
525
- placement_to_params[tuple([p.placements,
526
- p.device_mesh])][1].append(p)
527
- return placement_to_params
528
-
529
- if len(param_dtensors_small) > 0:
530
- if not dist.is_initialized():
531
- raise RuntimeError(
532
- "Parallel Muon requires torch.distributed to be initialized."
533
- )
534
-
535
- self.distributed_muon(
536
- params=param_dtensors_small,
537
- names=name_dtensors_small,
538
- group=group,
539
- lr=lr,
540
- weight_decay=weight_decay,
541
- qk_logits=qk_logits,
542
- )
543
-
544
- if len(param_dtensors) > 0:
545
- if not dist.is_initialized():
546
- raise RuntimeError(
547
- "Parallel Muon requires torch.distributed to be initialized."
548
- )
549
-
550
- dtensor_group = group_dtensors(param_dtensors, name_dtensors)
551
- for _, (names, params) in dtensor_group.items():
552
- self.parallel(
553
- names,
554
- params,
555
- group,
556
- lr=lr,
557
- weight_decay=weight_decay,
558
- qk_logits=qk_logits,
559
- )
560
-
561
- if len(param_tensors) > 0:
562
- self.base(
563
- name_tensors,
564
- param_tensors,
565
- group,
566
- lr=lr,
567
- weight_decay=weight_decay,
568
- qk_logits=qk_logits,
569
- )
570
-
571
- @torch.no_grad
572
- def step(self, closure=None, qk_logits=None):
573
- """Perform a single optimization step.
574
-
575
- Args:
576
- closure (Callable, optional): A closure that reevaluates the model
577
- and returns the loss.
578
- qk_logits (dict[int, Tensor], optional): A dictionary mapping layer indices
579
- to 1D tensors of shape (num_heads,), representing the maximum
580
- QK logits across all tokens, computed as
581
- (1 / sqrt(head_dim)) * (Q @ K^T).
582
- """
583
- loss = None
584
- if closure is not None:
585
- with torch.enable_grad():
586
- loss = closure()
587
-
588
- for group in self.param_groups:
589
- if group["use_muon"]:
590
- self._step_muon(group, qk_logits=qk_logits)
591
- else:
592
- step_adamw(self.state, group)
593
-
594
- return loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/torch210-cxx11-rocm70-x86_64-linux/newton_schulz.py DELETED
@@ -1,50 +0,0 @@
1
- import torch
2
-
3
- from .matmul_transpose_triton import matmul_transpose_assign
4
-
5
- COMM_DTYPE = torch.bfloat16
6
- DEFAULT_CHUNK_SIZE_RATIO = 4
7
-
8
-
9
- # This code snippet is a modified version adapted from the following GitHub repositories:
10
- # https://github.com/KellerJordan/Muon/blob/master/muon.py
11
- # Muon's Newton–Schulz iteration causes high variance in singular values
12
- # Idea: give each iteration its own 3 coefficients and optimize them via gradient descent.
13
- @torch.no_grad()
14
- # matmul_transpose_assign from : https://github.com/nil0x9/flash-muon
15
- def _zeropower_via_newtonschulz5(G, steps):
16
- """
17
- Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a
18
- quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose
19
- of minimizing steps, it turns out to be empirically effective to keep increasing the slope at
20
- zero even beyond the point where the iteration no longer converges all the way to one everywhere
21
- on the interval. This iteration therefore does not produce UV^T but rather something like US'V^T
22
- where S' is diagonal with S_{ii}' ~ Uniform(0.5, 1.5), which turns out not to hurt model
23
- performance at all relative to UV^T, where USV^T = G is the SVD.
24
- """
25
- assert len(G.shape) == 2
26
- assert G.dtype == COMM_DTYPE
27
- X = G # no manual typecast
28
-
29
- if G.size(0) > G.size(1):
30
- X = X.T
31
- # Ensure spectral norm is at most 1
32
- X = X / (X.norm() + 1e-7)
33
- buf1 = torch.empty(X.size(0), X.size(0), dtype=X.dtype, device=X.device)
34
- buf2 = torch.empty(X.size(0), X.size(0), dtype=X.dtype, device=X.device)
35
- # Perform the NS iterations
36
- for a, b, c in [
37
- (4.0848, -6.8946, 2.9270),
38
- (3.9505, -6.3029, 2.6377),
39
- (3.7418, -5.5913, 2.3037),
40
- (2.8769, -3.1427, 1.2046),
41
- (2.8366, -3.0525, 1.2012),
42
- ]:
43
- matmul_transpose_assign(X, buf1)
44
- matmul_transpose_assign(buf1, buf2)
45
- buf1.mul_(b).add_(buf2, alpha=c)
46
- X = torch.addmm(X, buf1, X, alpha=1.0, beta=a)
47
-
48
- if G.size(0) > G.size(1):
49
- X = X.T
50
- return X