diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7911daa --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,25 @@ +name: tests + +on: + push: + pull_request: + +jobs: + test: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + python: ["3.11"] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - name: Install CPU torch + run: python -m pip install torch --index-url https://download.pytorch.org/whl/cpu + - name: Install the rest + run: python -m pip install -e ".[serve,dev]" + - name: Tests + run: python -m pytest -q diff --git a/.gitignore b/.gitignore index 0fbe4f5..86fd95d 100644 --- a/.gitignore +++ b/.gitignore @@ -12,10 +12,19 @@ runs/* __pycache__/ *.pyc -# the training corpus - 1.2 GB of text, regenerated by tools/expand_corpus.py +# the training corpus - 1.2 GB of text, regenerated by corpora/expand.py data/ runs/corpus_index.json # secrets .env .env.* + +# local environments and tool state +.venv*/ +venv/ +.claude/ +.vscode/ +.idea/ +.pytest_cache/ +*.egg-info/ diff --git a/README.md b/README.md index 2f89ed0..b8ad3cd 100644 --- a/README.md +++ b/README.md @@ -424,7 +424,7 @@ The right panel shows which subjects are still moving. reasoning, code, stories, ## Running it -1. Make sure you have a CUDA-capable GPU with at least 8 GB of VRAM, and Python 3.10 or newer. The reference machine is an RTX 3070 Laptop GPU with 8 GB. +1. Make sure you have a GPU with at least 8 GB of memory - a CUDA card, or an AMD GPU with a ROCm build of PyTorch (see [AMD and Strix Halo](#amd-and-strix-halo)) - and Python 3.10 or newer. The reference machine is an RTX 3070 Laptop GPU with 8 GB. 2. Clone the repository: ```bash git clone @@ -438,6 +438,8 @@ The right panel shows which subjects are still moving. reasoning, code, stories, pip install scipy # a few of the analysis tools ``` PyTorch has to match your CUDA version - see [the PyTorch install page](https://pytorch.org/get-started/locally/). The reference environment is torch 2.6.0+cu124 with numpy 1.24.4. Only the first line is needed to train. + + Or, with torch already installed for your GPU, `pip install -e .[serve,corpora]` installs everything else from `pyproject.toml`, which leaves torch alone on purpose. 4. Build the corpus. One command downloads the four public datasets and generates the other four lanes: ```bash python3 -m corpora all # all eight subjects, a few GB @@ -457,6 +459,41 @@ The right panel shows which subjects are still moving. reasoning, code, stories, The run writes a sample log, redraws its graphs as it goes, and checkpoints every few minutes. It is meant to be left alone for days. +### AMD and Strix Halo + +ROCm builds of PyTorch answer to the same `torch.cuda` namespace, so nothing in the code is vendor-specific and `--device cuda` is still the flag. What an AMD APU such as the Ryzen AI Max (Strix Halo: Radeon 8060S, gfx1151, up to 128 GB of shared LPDDR5X) needs is a profile, because the hardware differs in ways the code cannot see: + +```bash +python train.py --config configs/strix_halo.yaml read --save # continue the released model +python train.py --config configs/strix_halo_large.yaml read --save # a new, larger one +python serve.py --config configs/strix_halo.yaml +python tools/bench_hw.py --config configs/strix_halo_large.yaml # measure before committing to a run +``` + +`--config` (or `MINAGI_CONFIG`) replaces `config.yaml` for every reader in the process. Both profiles set a `hardware:` block, read by [`minagi/device.py`](minagi/device.py): + +| key | what it does | +|---|---| +| `gpu_mem_gb` | the budget growth's ROOM brake measures against. **Set it to what the GPU may really use** - the Variable Graphics Memory in AMD Software on Windows, the GTT limit on Linux. torch reports the firmware carve-out as the card's size, which on an APU says little | +| `ram_tier_on_gpu` | holds the expert pool's RAM tier as device tensors, so paging an expert onto the card is a device-to-device copy rather than a blocking host transfer. System memory *is* the card's memory here | +| `rocm_aotriton` | `TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1` - the fast SDPA kernels on RDNA 3.5. Without them the cached forward falls back to math attention, which builds the full score matrix at every row | +| `tunableop` | `PYTORCH_TUNABLEOP_ENABLED=1` - tunes the expert dispatch's batched matmuls once and keeps the results in `runs/` | +| `expandable_segments` | the allocator setting train.py has always used; turn it off if your ROCm build warns it is unsupported | + +Every run prints a `hardware:` line naming the device, backend, whether memory is unified, the budget and where it came from. + +**Install.** Stock PyTorch wheels do not cover gfx1151. AMD publishes builds for it, for Linux and Windows, from its own index: + +```bash +pip install --index-url https://rocm.nightlies.amd.com/v2/gfx1151/ --pre torch +``` + +Then `pip install -e .[serve,corpora]` for the rest. A later `pip install -U` can pull a CUDA torch from PyPI over the ROCm one, so re-run the line above after any upgrade. Check with `python -c "import torch; print(torch.version.hip, torch.cuda.get_device_properties(0))"`, which should name gfx1151. + +**Memory.** On Linux, a small BIOS carve-out with a large GTT allowance is the usual setup - raise the TTM limit on the kernel command line (`ttm.pages_limit` counts 4 KiB pages: 27648000 is about 105 GiB) and set `gpu_mem_gb` a little below it. On Windows, set Variable Graphics Memory in AMD Software and set `gpu_mem_gb` to match. + +**What to expect.** The 8060S is in the same compute class as the reference RTX 3070 Laptop, with less memory bandwidth, so characters per second will be similar or lower - not higher. What it has is memory, roughly twelve times an 8 GB card's, and the profiles spend it on the axis this model is built around: `configs/strix_halo.yaml` keeps the released model's shape and gives it 64 experts per forward instead of 32, the whole pool in device memory, an 8k reach and a 100 GB disk ceiling; `configs/strix_halo_large.yaml` starts a new model with twice the experts at birth, four times the resident set and a trunk 768 wide. Raising `resident` changes routing, not only memory - a forward is admitted more of what its text asks for - so compare held-out loss before and after rather than assuming it is free. Its numbers are starting points: run `tools/bench_hw.py` on the machine first. + ### Everything else ```bash diff --git a/config.yaml b/config.yaml index 4a668c1..a610f7d 100644 --- a/config.yaml +++ b/config.yaml @@ -195,3 +195,18 @@ plots: enabled: true # redraw the graphs whenever the sample log grows last: 100 # millions of characters the recent-progress graph # covers, counted back from wherever reading has got + +hardware: + # What the machine is, where the code cannot tell for itself - read by + # minagi/device.py. Every key is optional; left out, a discrete NVIDIA card + # behaves exactly as it always has. See configs/strix_halo.yaml for an APU. + # + # gpu_mem_gb: 8 # the budget growth's ROOM brake measures against. + # # Unset, the card's reported size. Set it on an APU, + # # where the reported size is the firmware carve-out + # unified: false # CPU and GPU share memory. Detected for gfx1150/1/2 + # ram_tier_on_gpu: false # hold the expert RAM tier on the device. Defaults + # # to `unified` + # expandable_segments: true # PYTORCH_{CUDA,HIP}_ALLOC_CONF + # rocm_aotriton: false # TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 + # tunableop: false # PYTORCH_TUNABLEOP_ENABLED=1, results in runs/ diff --git a/configs/strix_halo.yaml b/configs/strix_halo.yaml new file mode 100644 index 0000000..c7e0f95 --- /dev/null +++ b/configs/strix_halo.yaml @@ -0,0 +1,235 @@ +# mini-AGI on AMD Strix Halo - CONTINUING THE EXISTING MODEL. +# +# python train.py --config configs/strix_halo.yaml read --save +# python serve.py --config configs/strix_halo.yaml +# +# The model block below is the released model's shape, so this profile +# continues weights/ as they are (including the Hugging Face snapshots). Only +# run-time settings change: more experts per forward, the whole pool held in +# device memory, a longer reach, a larger disk ceiling. For a NEW, larger +# model see configs/strix_halo_large.yaml. +# +# Expect characters per second close to an RTX 3070 Laptop's, not above it: +# the 8060S is in the same compute class with less memory bandwidth. What it +# has is memory, and this profile spends it. +# +# mini-AGI — the settings worth changing. +# +# Read when a model is created and every time it reads. Anything not here is +# either derived or was not worth a knob. + +model: + # THIS BLOCK BUILDS A MODEL; IT DOES NOT CHANGE ONE. Down as far as the + # depth rule, these are fixed in the manifest when the weights are created. + # Editing them later does nothing - the shapes would no longer match. + d_model: 512 # width of the trunk + n_head: 8 # attention heads + d_ff: 1408 # the trunk's own feed-forward + n_prelude: 2 # dense blocks before the recurrent core; run once + n_recur: 1 # blocks per row + n_coda: 0 # readout blocks after the last row + + # ------------------------------------------------------------------ DEPTH + # + # The model runs one row at a time and decides after each whether to stop. + # A row is n_recur + n_coda block applications. + # + # RESCALING RULE: max_steps, halt_prior, bptt_window and train_steps_mean + # are all counted in ROWS, so all four move together if n_recur or n_coda + # changes what a row is. Missing one is silent. + + max_steps: 24 # most rows a character may take + min_steps: 1 # rows it must run before halting may stop it + + halt_prior: 0.072 # halting is held to a mean of 1/this rows + halt_thresh: 0.9 # at inference, stop at the first row past this + halt_freeze: true # a halted character stops being computed, in + # training and writing alike; later characters read + # its final state at the deeper rows + ponder_beta: 0.01 # weight on the halting KL + + bptt_window: 24 # rows gradient reaches back through. Also the + # activation memory, so it sets peak VRAM + + train_steps_mean: 12.8 # depth sampled while training: poisson(this) + 1, + # clipped. 0 runs the ceiling every step + + # The window attention reaches back over. Reading starts at context_start + # and grows only when the model is still gaining from the far end of what + # it has; context_end is the ceiling and binds at load and at every growth. + context_start: 2048 # where a fresh model begins + context_end: 8192 # rotary, so the existing model can extend into it + + context_step: 1 # characters added per growth + context_grow_every_chars: 100_000 # characters between growths + context_gain_min: 0.015 # stop growing below this gain from depth + context_every_chars: 65536 # characters between asking + +pool: + # experts, width, depth and top_k are fixed in the manifest, like the model + # block. resident, ram_cache and capacity_factor are run-time and can be + # changed freely. + experts: 64 # how many exist at the start; it grows from here + width: 2048 # hidden units in one expert + depth: 1 # SwiGLU blocks stacked inside one expert + top_k: 8 # how many one character routes through + + # HOW EXPERTS ARE CHOSEN - one rule: the text chooses. Every character + # ranks the whole pool with the router and asks for its top_k, and every + # forward's first pass adds its characters' requests to the vote of its + # text - everything read since position 0. A forward - a training window, a + # chunk of held-out file, a prompt, each character of a reply - may use at + # most `resident` different experts: the ones its text has voted for most, + # and a character whose request was not admitted takes its best admitted + # expert instead. A character being written routes among what its prompt + # and the reply so far asked for, as it would inside a training window. + # + # Three tiers: disk holds every expert, RAM caches the recently wanted, + # VRAM holds what the current forward admitted. Only VRAM is scarce. + resident: 64 # experts one forward may use - TWICE the 8 GB card's. + # Changes routing, not only memory: a forward is + # admitted more of what its text asks for + # holding weights, gradient and Adam's moments + ram_cache: 0 # 0 = every expert stays in the tier, which here + # is device memory: disk is read once per expert + + capacity_factor: 1.5 # most of a batch one expert may take, as a multiple + # of its fair share; the rest is dropped. 0 removes + + # THE BALANCE TERM - how the whole pool gets used. Left alone the router + # keeps choosing the same experts: reading held-out on its own it put 59 of + # 118 on a card across every subject. This term in the loss charges the + # router, in every forward that trains, for the probability it puts on each + # expert over the whole pool, in proportion to that expert's share of recent + # admissions (the last ~1,000 training forwards). Busy experts get dearer and + # idle ones cheaper, so the router's own rows move toward the idle - and + # reading and writing use them too, not only training. A text is still free + # to want few experts; what gets evened out is use across texts. + # + # The weight sets how hard it leans against learning the text on the experts + # in use. An expert no text admits gets no other gradient, so Adam moves its + # row at the usual pace whatever the weight. 0 turns it off. In a 15-minute + # test 0.01 took the experts in use on held-out from 59 to 114, at a cost of + # 0.023 in held-out loss over those minutes. + balance: 0.001 + + # THE TEMPERATURE OF EXPERT SELECTION - which experts compute a character, + # NOT which character comes out. Characters are always chosen greedily; any + # randomness in what the model writes comes from here. + # + # 0 threshold selection, the rule as it has run: the card holds the + # 32 experts the text's first row asks for most, and every character + # takes its own top 8 of those + # > 0 drawn: at each row, 8 experts are drawn from the text's + # probabilities (the router's full distribution, summed over every + # character in the context window) in proportion to p^(1/T), until + # the card's 32 are full, and every character draws its own 8 from + # its own probabilities over the card, the same way + # + # 1 draws in proportion to the router's probabilities, 0.5 to their + # squares, 0.2 to their fifth powers. Close to 0 the draws approach each + # row's top 8 - which is not quite 0 itself: a drawn card fills 8 a row, so + # the first row has only 8 experts where 0 gives it all 32. + select_temperature: 0 + +training: + save_every: 5 # minutes between checkpoints + + precision: bf16 # what the forward computes in. Weights, gradients + # and the expert files stay fp32 + + # THE LEARNING RATE IS NOT SCHEDULED. minagi/plasticity.py watches held-out + # and moves the rate in both directions: easing it down without evidence of + # improvement, stepping it back up when held-out jumps and stays there. + chunk: 2048 # characters between steps within the window + lr: 3.0e-4 + trunk_lr_mult: 0.1 # the trunk is shared by every domain and is where + # forgetting happens; it learns slower on purpose + weight_decay: 0.1 + clip: 1.0 + +growth: + # Every `every_chars`, add `k` experts if all five brakes are off: + # ROOM there is disk and VRAM for it + # USED the capacity it already has is being asked for + # EARNING the experts added recently are being asked for + # FITS not too many are already inside their trial + # HONEST train and held-out have not separated + every_chars: 2_000_000 # characters between growth decisions + k: 1 # experts added per decision + + max_gap: 0.4 # HONEST: train minus held-out. 0 disables + + # USED. Staleness is a share of prune.survival_chars: 0.0 when a forward + # admits an expert, 1.0 when it has gone long enough unadmitted to be + # deleted. Past prune.dying_at it counts as dying. + dying_frac_max: 0.35 # stop growing once this share of the pool is dying + + # FITS. + max_in_flight: 100 # experts allowed inside their trial at once + + # EARNING. Of the experts past their trial and still young, this share must + # have earned a gate. + keep_ratio_min: 0.35 + recent_mult: 4.0 # "still young" is age < this x the trial + + # ROOM. An expert is 25.2 MB, so 10 GB is about 397 of them. + max_disk_gb: 100.0 # ~4,000 experts at 25.2 MB + mem_frac: 0.85 # of hardware.gpu_mem_gb; leaves the OS its share + + birth_gate: 0.001 # gate a new expert starts at - a scale, not a + # verdict. Small so it cannot shout before it earns + +prune: + # USE IT OR LOSE IT. An expert is deleted when nothing has admitted it for + # this long, and it is never deleted inside its first survival_chars. + survival_chars: 100_000_000 + + dying_at: 0.65 # how far through that window an expert must get, + # unaddressed, to count as dying for growth's brake + +data: + train: data/train + held_out: data/val + weights: weights # created on the first run if it is not there + + shuffle_seed: 0 # which file and which offset each window comes from + + # Each sub-folder of `train` is a subject, and reading rotates between them. + # A window never spans two subjects, but a subject may take several in a row. + passage: 32768 # characters read from one file before moving on + +decoding: + # Generation is greedy - no random numbers - so two samples taken at the + # same point in training are the same text. What holds off the loops greedy + # decoding usually falls into is a per-character trace that rises when a + # character is used and decays after. + adapt_strength: 2.5 # logits of suppression for a character just used + adapt_decay: 0.88 # half-life of 5.4 characters; 0 disables it + + rep_penalty: 1.0 # the weaker alternative, off at 1.0 + +plots: + enabled: true # redraw the graphs whenever the sample log grows + last: 100 # millions of characters the recent-progress graph + # covers, counted back from wherever reading has got + +hardware: + # AMD Ryzen AI Max (Strix Halo): Radeon 8060S, gfx1151, RDNA 3.5, sharing + # up to 128 GB of LPDDR5X with the CPU at ~256 GB/s. + # + # SET THIS to what the GPU may actually use on your machine: + # Windows - the Variable Graphics Memory set in AMD Software (e.g. 96) + # Linux - the GTT limit the kernel allows (ttm.pages_limit), less + # headroom for the OS; or the BIOS UMA size if you set it large + # torch reports the firmware carve-out as the card's size, which on an APU + # says little about what can be allocated, so growth measures against this. + gpu_mem_gb: 96 + unified: true + ram_tier_on_gpu: true # the expert RAM tier lives on the device: a + # page-in is a device-to-device copy + expandable_segments: true # turn off if your ROCm build warns it is + # unsupported (some Windows builds) + rocm_aotriton: true # fast SDPA kernels on RDNA 3.5; without them a + # 4k window builds its whole T x T scores per row + tunableop: true # tune each GEMM shape once, results in runs/ diff --git a/configs/strix_halo_large.yaml b/configs/strix_halo_large.yaml new file mode 100644 index 0000000..8fc89f1 --- /dev/null +++ b/configs/strix_halo_large.yaml @@ -0,0 +1,238 @@ +# mini-AGI on AMD Strix Halo - A NEW, LARGER MODEL. +# +# python train.py --config configs/strix_halo_large.yaml read --save +# +# The model block fixes the shape when weights-strix/ is created, so this is +# a fresh run: it cannot load the released weights. +# +# Larger on the axis Strix Halo is rich in. Memory is ~12x an 8 GB card; +# compute is about the same. So the pool, the resident set and the reach grow +# a lot (2x experts at birth, 4x resident, 2x context) and the trunk, which +# every character pays for at every row, grows modestly (512 -> 768 wide). +# Rough cost per character is 2-3x the released model's. +# +# THESE ARE STARTING NUMBERS. Run tools/bench_hw.py with this config on the +# machine first; if a step is too slow, d_model and context_end are the +# knobs that buy the most speed back, resident the one that costs the least +# to keep. +# +# mini-AGI — the settings worth changing. +# +# Read when a model is created and every time it reads. Anything not here is +# either derived or was not worth a knob. + +model: + # THIS BLOCK BUILDS A MODEL; IT DOES NOT CHANGE ONE. Down as far as the + # depth rule, these are fixed in the manifest when the weights are created. + # Editing them later does nothing - the shapes would no longer match. + d_model: 768 # width of the trunk + n_head: 12 # attention heads (64 per head, as before) + d_ff: 2048 # the trunk's own feed-forward + n_prelude: 2 # dense blocks before the recurrent core; run once + n_recur: 1 # blocks per row + n_coda: 0 # readout blocks after the last row + + # ------------------------------------------------------------------ DEPTH + # + # The model runs one row at a time and decides after each whether to stop. + # A row is n_recur + n_coda block applications. + # + # RESCALING RULE: max_steps, halt_prior, bptt_window and train_steps_mean + # are all counted in ROWS, so all four move together if n_recur or n_coda + # changes what a row is. Missing one is silent. + + max_steps: 24 # most rows a character may take + min_steps: 1 # rows it must run before halting may stop it + + halt_prior: 0.072 # halting is held to a mean of 1/this rows + halt_thresh: 0.9 # at inference, stop at the first row past this + halt_freeze: true # a halted character stops being computed, in + # training and writing alike; later characters read + # its final state at the deeper rows + ponder_beta: 0.01 # weight on the halting KL + + bptt_window: 24 # rows gradient reaches back through. Also the + # activation memory, so it sets peak VRAM + + train_steps_mean: 12.8 # depth sampled while training: poisson(this) + 1, + # clipped. 0 runs the ceiling every step + + # The window attention reaches back over. Reading starts at context_start + # and grows only when the model is still gaining from the far end of what + # it has; context_end is the ceiling and binds at load and at every growth. + context_start: 2048 # where a fresh model begins + context_end: 8192 # rotary, so the existing model can extend into it + + context_step: 1 # characters added per growth + context_grow_every_chars: 100_000 # characters between growths + context_gain_min: 0.015 # stop growing below this gain from depth + context_every_chars: 65536 # characters between asking + +pool: + # experts, width, depth and top_k are fixed in the manifest, like the model + # block. resident, ram_cache and capacity_factor are run-time and can be + # changed freely. + experts: 128 # how many exist at the start; it grows from here + width: 2048 # hidden units in one expert + depth: 1 # SwiGLU blocks stacked inside one expert + top_k: 8 # how many one character routes through + + # HOW EXPERTS ARE CHOSEN - one rule: the text chooses. Every character + # ranks the whole pool with the router and asks for its top_k, and every + # forward's first pass adds its characters' requests to the vote of its + # text - everything read since position 0. A forward - a training window, a + # chunk of held-out file, a prompt, each character of a reply - may use at + # most `resident` different experts: the ones its text has voted for most, + # and a character whose request was not admitted takes its best admitted + # expert instead. A character being written routes among what its prompt + # and the reply so far asked for, as it would inside a training window. + # + # Three tiers: disk holds every expert, RAM caches the recently wanted, + # VRAM holds what the current forward admitted. Only VRAM is scarce. + resident: 128 # experts one forward may use + # Changes routing, not only memory: a forward is + # admitted more of what its text asks for + # holding weights, gradient and Adam's moments + ram_cache: 0 # 0 = every expert stays in the tier, which here + # is device memory: disk is read once per expert + + capacity_factor: 1.5 # most of a batch one expert may take, as a multiple + # of its fair share; the rest is dropped. 0 removes + + # THE BALANCE TERM - how the whole pool gets used. Left alone the router + # keeps choosing the same experts: reading held-out on its own it put 59 of + # 118 on a card across every subject. This term in the loss charges the + # router, in every forward that trains, for the probability it puts on each + # expert over the whole pool, in proportion to that expert's share of recent + # admissions (the last ~1,000 training forwards). Busy experts get dearer and + # idle ones cheaper, so the router's own rows move toward the idle - and + # reading and writing use them too, not only training. A text is still free + # to want few experts; what gets evened out is use across texts. + # + # The weight sets how hard it leans against learning the text on the experts + # in use. An expert no text admits gets no other gradient, so Adam moves its + # row at the usual pace whatever the weight. 0 turns it off. In a 15-minute + # test 0.01 took the experts in use on held-out from 59 to 114, at a cost of + # 0.023 in held-out loss over those minutes. + balance: 0.001 + + # THE TEMPERATURE OF EXPERT SELECTION - which experts compute a character, + # NOT which character comes out. Characters are always chosen greedily; any + # randomness in what the model writes comes from here. + # + # 0 threshold selection, the rule as it has run: the card holds the + # 32 experts the text's first row asks for most, and every character + # takes its own top 8 of those + # > 0 drawn: at each row, 8 experts are drawn from the text's + # probabilities (the router's full distribution, summed over every + # character in the context window) in proportion to p^(1/T), until + # the card's 32 are full, and every character draws its own 8 from + # its own probabilities over the card, the same way + # + # 1 draws in proportion to the router's probabilities, 0.5 to their + # squares, 0.2 to their fifth powers. Close to 0 the draws approach each + # row's top 8 - which is not quite 0 itself: a drawn card fills 8 a row, so + # the first row has only 8 experts where 0 gives it all 32. + select_temperature: 0 + +training: + save_every: 5 # minutes between checkpoints + + precision: bf16 # what the forward computes in. Weights, gradients + # and the expert files stay fp32 + + # THE LEARNING RATE IS NOT SCHEDULED. minagi/plasticity.py watches held-out + # and moves the rate in both directions: easing it down without evidence of + # improvement, stepping it back up when held-out jumps and stays there. + chunk: 2048 # characters between steps within the window + lr: 3.0e-4 + trunk_lr_mult: 0.1 # the trunk is shared by every domain and is where + # forgetting happens; it learns slower on purpose + weight_decay: 0.1 + clip: 1.0 + +growth: + # Every `every_chars`, add `k` experts if all five brakes are off: + # ROOM there is disk and VRAM for it + # USED the capacity it already has is being asked for + # EARNING the experts added recently are being asked for + # FITS not too many are already inside their trial + # HONEST train and held-out have not separated + every_chars: 2_000_000 # characters between growth decisions + k: 1 # experts added per decision + + max_gap: 0.4 # HONEST: train minus held-out. 0 disables + + # USED. Staleness is a share of prune.survival_chars: 0.0 when a forward + # admits an expert, 1.0 when it has gone long enough unadmitted to be + # deleted. Past prune.dying_at it counts as dying. + dying_frac_max: 0.35 # stop growing once this share of the pool is dying + + # FITS. + max_in_flight: 100 # experts allowed inside their trial at once + + # EARNING. Of the experts past their trial and still young, this share must + # have earned a gate. + keep_ratio_min: 0.35 + recent_mult: 4.0 # "still young" is age < this x the trial + + # ROOM. An expert is 25.2 MB, so 10 GB is about 397 of them. + max_disk_gb: 200.0 # an expert is ~38 MB at this width + mem_frac: 0.85 # of hardware.gpu_mem_gb; leaves the OS its share + + birth_gate: 0.001 # gate a new expert starts at - a scale, not a + # verdict. Small so it cannot shout before it earns + +prune: + # USE IT OR LOSE IT. An expert is deleted when nothing has admitted it for + # this long, and it is never deleted inside its first survival_chars. + survival_chars: 100_000_000 + + dying_at: 0.65 # how far through that window an expert must get, + # unaddressed, to count as dying for growth's brake + +data: + train: data/train + held_out: data/val + weights: weights-strix # a new model gets its own directory + + shuffle_seed: 0 # which file and which offset each window comes from + + # Each sub-folder of `train` is a subject, and reading rotates between them. + # A window never spans two subjects, but a subject may take several in a row. + passage: 32768 # characters read from one file before moving on + +decoding: + # Generation is greedy - no random numbers - so two samples taken at the + # same point in training are the same text. What holds off the loops greedy + # decoding usually falls into is a per-character trace that rises when a + # character is used and decays after. + adapt_strength: 2.5 # logits of suppression for a character just used + adapt_decay: 0.88 # half-life of 5.4 characters; 0 disables it + + rep_penalty: 1.0 # the weaker alternative, off at 1.0 + +plots: + enabled: true # redraw the graphs whenever the sample log grows + last: 100 # millions of characters the recent-progress graph + # covers, counted back from wherever reading has got + +hardware: + # AMD Ryzen AI Max (Strix Halo): Radeon 8060S, gfx1151, RDNA 3.5, sharing + # up to 128 GB of LPDDR5X with the CPU at ~256 GB/s. + # + # SET THIS to what the GPU may actually use on your machine: + # Windows - the Variable Graphics Memory set in AMD Software (e.g. 96) + # Linux - the GTT limit the kernel allows (ttm.pages_limit), less + # headroom for the OS; or the BIOS UMA size if you set it large + # torch reports the firmware carve-out as the card's size, which on an APU + # says little about what can be allocated, so growth measures against this. + gpu_mem_gb: 96 + unified: true + ram_tier_on_gpu: true # the expert RAM tier lives on the device: a + # page-in is a device-to-device copy + expandable_segments: true # turn off if your ROCm build warns it is + # unsupported (some Windows builds) + rocm_aotriton: true # fast SDPA kernels on RDNA 3.5; without them a + # 4k window builds its whole T x T scores per row + tunableop: true # tune each GEMM shape once, results in runs/ diff --git a/corpora/arithmetic.py b/corpora/arithmetic.py index da96cbf..e541c84 100644 --- a/corpora/arithmetic.py +++ b/corpora/arithmetic.py @@ -279,7 +279,7 @@ def main(): "val_tokens": val_total, "tasks": list(TASKS), "tokenizer": "byte", "note": "answers in normal order; scratchpads show derivable steps"} - json.dump(meta, open(os.path.join(args.out, "meta.json"), "w"), indent=2) + json.dump(meta, open(os.path.join(args.out, "meta.json"), "w", encoding="utf-8"), indent=2) print(f"wrote {args.out}/meta.json") return 0 diff --git a/corpora/chat.py b/corpora/chat.py index 6b369ff..0873c5d 100644 --- a/corpora/chat.py +++ b/corpora/chat.py @@ -129,7 +129,7 @@ def _self_facts(): key=os.path.getmtime, reverse=True) for q in cands: try: - man = json.load(open(q)) + man = json.load(open(q, encoding="utf-8")) break except Exception: continue @@ -212,7 +212,7 @@ def _load_self_knowledge(): "self_knowledge.yaml") if not os.path.exists(p): return [] - with open(p) as fh: + with open(p, encoding="utf-8") as fh: doc = yaml.safe_load(fh) or [] out = [] for item in doc: @@ -497,7 +497,7 @@ def main(): "val_tokens": va, "pairs": len(pairs), "tokenizer": "byte", "format": f"{U0}...{U1}{B0}...{B1}"}, - open(os.path.join(args.out, "meta.json"), "w"), indent=2) + open(os.path.join(args.out, "meta.json"), "w", encoding="utf-8"), indent=2) print(f"wrote {args.out}/meta.json") return 0 diff --git a/corpora/chess_games.py b/corpora/chess_games.py index 49a0541..9739a0c 100644 --- a/corpora/chess_games.py +++ b/corpora/chess_games.py @@ -152,7 +152,7 @@ def main(): # legality check on a sample: if the text is not real chess, stop here import chess, chess.pgn bad = checked = 0 - with open(txt_path) as f: + with open(txt_path, encoding="utf-8") as f: for i, line in enumerate(f): if i >= 200: break @@ -186,7 +186,7 @@ def main(): json.dump({"vocab_size": 256, "tokenizer": "byte", "train_tokens": n_tr, "val_tokens": n_va, "games": kept, "min_elo": args.min_elo, "format": " SAN "}, - open(os.path.join(args.out, "meta.json"), "w"), indent=2) + open(os.path.join(args.out, "meta.json"), "w", encoding="utf-8"), indent=2) print(f"train {n_tr:,} tokens, val {n_va:,} tokens -> {args.out}") return 0 diff --git a/corpora/code.py b/corpora/code.py index 507535c..dd48f3f 100644 --- a/corpora/code.py +++ b/corpora/code.py @@ -228,7 +228,7 @@ def flush(): "self_close_id": tok.token_to_id(SELF_CLOSE), "roots": roots, } - with open(os.path.join(args.out, "meta.json"), "w") as f: + with open(os.path.join(args.out, "meta.json"), "w", encoding="utf-8") as f: json.dump(meta, f, indent=2) print(f"\ntrain {counts['train']:,} tokens ({counts['train']*2/1e6:.0f} MB)") diff --git a/corpora/fetch.py b/corpora/fetch.py index fb61758..5e63eba 100644 --- a/corpora/fetch.py +++ b/corpora/fetch.py @@ -19,8 +19,10 @@ Driven by `python3 -m corpora all`, which knows the datasets each lane wants. -The dataset cache is deleted afterwards unless --keep-cache: converting -OpenThoughts left thirteen gigabytes of Arrow behind. +The dataset cache is kept, so a rebuild does not download everything again. +--drop-cache deletes it afterwards - converting OpenThoughts left thirteen +gigabytes of Arrow behind - and it is the WHOLE datasets cache, every +dataset in it, not only the one this run fetched. """ import argparse @@ -78,7 +80,11 @@ def main(): help="characters per file; a record is never split") ap.add_argument("--shard", type=int, default=2000, help="files per subdirectory") - ap.add_argument("--keep-cache", action="store_true") + ap.add_argument("--drop-cache", action="store_true", + help="delete the Hugging Face datasets cache afterwards - " + "all of it, not only this dataset") + ap.add_argument("--keep-cache", action="store_true", + help="the default now; accepted so old commands still run") a = ap.parse_args() from datasets import load_dataset @@ -103,7 +109,7 @@ def flush(where, idx): sub = where if where == a.held_out else os.path.join( where, f"{idx // a.shard:04d}") os.makedirs(sub, exist_ok=True) - with open(os.path.join(sub, f"part-{idx:06d}.txt"), "w") as f: + with open(os.path.join(sub, f"part-{idx:06d}.txt"), "w", encoding="utf-8") as f: f.write(text) chars += len(text) buf.clear() @@ -129,12 +135,16 @@ def flush(where, idx): print(f" wrote {files:,} files to {a.out}" + (f" and {held:,} to {a.held_out}" if a.held_out else "") + f", {chars/1e6:,.1f}M characters ({skipped:,} skipped)", flush=True) - if not a.keep_cache: + if a.drop_cache and not a.keep_cache: # datasets/ only. The parent also holds downloaded models and tokens # that this script did not put there and has no business deleting. - shutil.rmtree(os.path.expanduser("~/.cache/huggingface/datasets"), - ignore_errors=True) - print(" removed the dataset cache", flush=True) + # Wherever datasets actually put it: HF_DATASETS_CACHE, then HF_HOME. + cache = (os.environ.get("HF_DATASETS_CACHE") + or os.path.join(os.environ.get("HF_HOME") or + os.path.expanduser("~/.cache/huggingface"), + "datasets")) + shutil.rmtree(cache, ignore_errors=True) + print(f" removed the dataset cache at {cache}", flush=True) if a.streaming: # datasets' streaming reader leaves a worker thread alive, and CPython diff --git a/corpora/reasoning.py b/corpora/reasoning.py index bef2eaf..282f671 100644 --- a/corpora/reasoning.py +++ b/corpora/reasoning.py @@ -106,12 +106,12 @@ def main(): # has a held-out score like every other one if n < a.hold: os.makedirs(a.held_out, exist_ok=True) - with open(os.path.join(a.held_out, f"trace-{n:06d}.txt"), "w") as f: + with open(os.path.join(a.held_out, f"trace-{n:06d}.txt"), "w", encoding="utf-8") as f: f.write(text) else: sub = os.path.join(a.out, f"{(n - a.hold) // a.shard:04d}") os.makedirs(sub, exist_ok=True) - with open(os.path.join(sub, f"trace-{n:06d}.txt"), "w") as f: + with open(os.path.join(sub, f"trace-{n:06d}.txt"), "w", encoding="utf-8") as f: f.write(text) n += 1 chars += len(text) diff --git a/minagi/build.py b/minagi/build.py new file mode 100644 index 0000000..73256a0 --- /dev/null +++ b/minagi/build.py @@ -0,0 +1,189 @@ +""" +Building a model from a weights directory. + +These lived in train.py, which made the library import its own entry point to +load a paged directory (recur.load_recur did `import train`). They are the +library's: train.py, serve.py and the replication probe all reach them here. +""" + +import json +import os + +import numpy as np +import torch + +from minagi.pool import PooledMLP +from minagi.recur import RecurConfig, RecurCoder + + +def _split_trunk_pool(model): + """ + Which parameters are the pool's, and which are the shared body. + + A resident pool keeps its experts as modules; a paged pool keeps three + stacked slot tensors instead, so the set has to be found by asking the + pool rather than by walking a ModuleList that is not there. + """ + p = model.pool + ids = {id(p.gate)} + if hasattr(p, "experts") and p.experts is not None: + ids |= {id(q) for e in p.experts for q in e.parameters()} + for nm in ("w1", "w3", "w2"): + obj = getattr(p, nm, None) + if obj is None: + continue + ids |= ({id(obj)} if torch.is_tensor(obj) + else {id(q) for q in obj.parameters()}) + for s in model.modules(): + if isinstance(s, PooledMLP): + ids.add(id(s.router.weight)) + ids.add(id(s.depth_emb)) + trunk = [q for q in model.parameters() if id(q) not in ids] + pool = [q for q in model.parameters() if id(q) in ids] + return trunk, pool + + +def build_adamw(model, lr, trunk_lr_mult, wd): + """ + The optimiser every path that trains a model uses, and its two groups. + + The trunk - everything every character passes through - learns at + trunk_lr_mult of the pool's rate, because it is where forgetting happens + (README, "How continual learning works"). The pool is the experts, their + gates and the routers' rows. There were four copies of this, and the + server's split by name prefix put the routers in the trunk: in a chat + they learned at a tenth of the rate training gives them. + + A paged pool is attached, so each expert on the card is stepped with its + own moments. Returns (opt, trunk, pool). + """ + trunk, pool_ps = _split_trunk_pool(model) + dev = next(model.parameters()).device + tg = {"params": trunk, "name": "trunk", "weight_decay": wd, + "lr": lr * trunk_lr_mult, "base_lr": lr * trunk_lr_mult} + pg = {"params": pool_ps, "name": "pool", "weight_decay": wd, + "lr": lr, "base_lr": lr} + opt = torch.optim.AdamW([tg, pg], lr=lr, betas=(0.9, 0.95), + fused=(dev.type == "cuda")) + pool = getattr(model, "pool", None) + if pool is not None and hasattr(pool, "attach_optimiser"): + pool.attach_optimiser(opt) + return opt, trunk, pool_ps + + +def build_paged(wdir, device, resident=None, ram_capacity=None, ceiling=None, + read_only=False): + """ + Load the model with its pool on disk rather than in VRAM. + + The three tiers the project describes: every expert is a file, RAM keeps + the recently wanted ones, and the card holds the experts the current + forward admitted. While a forward has room on the card, every character ranks the + whole pool; a forward may use at most `resident` experts, the ones its + characters ask for most - see PagedPool.admit. + + read_only makes the pool incapable of writing to `wdir`. Pass it from any + tool that inspects a directory a training run may own - paging an expert in + marks it dirty whether or not anything touched it, so a plain read would + otherwise write expert files back under the run. + + ram_capacity None takes pool.ram_cache from the config; 0 keeps every + expert the pool has. Where the RAM tier itself lives is + minagi.device.ram_tier_on_gpu's call - on a unified-memory APU it sits on + the device, so paging onto the card is a device-to-device copy. + """ + from minagi.paged import PagedPool + from minagi.device import ram_tier_on_gpu + from minagi.config import load as _load_cfg, get as _get_cfg + if ram_capacity is None: + ram_capacity = int(_get_cfg(_load_cfg(), "pool.ram_cache", 256)) + with open(os.path.join(wdir, "manifest.json"), encoding="utf-8") as f: + man = json.load(f) + cfgd = dict(man["cfg"]) + resident = resident or cfgd.get("pool_resident") or cfgd["pool_top_k"] + cfg = RecurConfig(**{k: v for k, v in cfgd.items() + if k in RecurConfig.__dataclass_fields__}) + # The capacity bound comes from config.yaml rather than from the + # checkpoint, because it is a property of the machine the model is running + # on - how much VRAM the dispatch may use - not of the model. A directory + # written before this existed carries no value for it and would otherwise + # get the dataclass default, which is right but silent; taking it from the + # config every load means the number in the file is the number in effect. + try: + from minagi.config import load as _load_cfg, get as _get_cfg + _c = _load_cfg() + cfg.pool_capacity_factor = float( + _get_cfg(_c, "pool.capacity_factor", cfg.pool_capacity_factor)) + except Exception: + pass + # the per-token router keeps one row per EXPERT, not per VRAM slot, so it + # is sized by the pool and grows with it - see PooledMLP.__init__ + # EXACTLY what the pool holds. pool_max sizes the routers, which keep one + # row per expert, so a checkpoint's router weights only fit a model built + # at the same count - one row too many and load_state_dict refuses the + # whole model. + # + # It was briefly max(cfg.pool_max, n_experts) to stop `stream` latching + # its growth ceiling to the pool's current size. That conflated two jobs + # in one number: sizing the routers, and capping growth. The manifest's + # pool_max ratchets up and never comes down, so after a prune took the + # pool from 158 to 157 the max() still read 158 and the directory would + # not load at all. The ceiling now lives in `stream` where it belongs. + cfg.pool_max = int(man["n_experts"]) + if ceiling and ceiling > cfg.block: + # RoPE tables are built to cfg.block and carry no learned parameters, + # so raising the ceiling on an existing model costs a bigger table and + # nothing else. The window the reader actually uses is separate, and + # grows a character at a time. + cfg.block = int(ceiling) + model = RecurCoder(cfg).to(device) + pool = PagedPool(os.path.join(wdir, "experts"), cfg.d_model, cfg.pool_d_ff, + int(man["n_experts"]), resident=resident, + ram_capacity=ram_capacity, device=device, + read_only=read_only, + tier_on_device=ram_tier_on_gpu(device)).to(device) + for m in model.modules(): + if isinstance(m, PooledMLP): + m._pool[0] = pool + model.pool = pool + pool.attach_sites(model) + pool.load_telemetry(man.get("telemetry")) + # The balance term's weight and the temperature of expert selection - see + # PagedPool.note_balance and PagedPool._draw. Read from config.yaml at + # every load, like the capacity bound: they are choices about how the model + # trains and chooses, not properties of its weights. + try: + from minagi.config import load as _load_cfg, get as _get_cfg + _c = _load_cfg() + pool.balance = float(_get_cfg(_c, "pool.balance", 0.0) or 0.0) + pool.select_temperature = float( + _get_cfg(_c, "pool.select_temperature", 0.0) or 0.0) + except Exception: + pass + ever = cfgd.get("pool_ever") + if ever: + n = min(len(ever), pool.ever.numel()) + pool.ever[:n] = torch.tensor(ever[:n], dtype=torch.bool, + device=pool.ever.device) + # the trunk still comes from the bundles; the experts come from their files + # + # Both are opened in `with` so the handles close here: on Windows a file + # still open cannot be replaced, and the next checkpoint replaces these. + with np.load(os.path.join(wdir, "core.npz")) as core, np.load(os.path.join(wdir, "routers.npz")) as rout: + sd = {k: torch.from_numpy(core[k]) for k in core.files} + # Router rows belong to EXPERTS, not to VRAM slots, so they are loaded + # whole. Slicing them to the resident count - which this did, left + # over from when rows were slots - silently discarded every expert + # past the card and made any resume after growth fail to load. + for k in rout.files: + # The segment router chose working sets before selection moved + # into the router itself; directories written then still carry + # its rows. + if k.startswith("pool.segment_router."): + continue + sd[k] = torch.from_numpy(rout[k]) + missing, unexpected = model.load_state_dict(sd, strict=False) + bad = [k for k in unexpected if "router" in k or "gate" in k] + if bad: + raise RuntimeError(f"router/gate tensors did not load: {bad}") + return model, cfg, pool, man diff --git a/minagi/config.py b/minagi/config.py index 445842d..772b431 100644 --- a/minagi/config.py +++ b/minagi/config.py @@ -5,20 +5,57 @@ model and the one that trains it read it, so a model cannot be built with one shape and trained with another. Command-line flags still win where they are given - the file is the default, not a cage. + +A different file can stand in for config.yaml - a hardware profile such as +configs/strix_halo.yaml - through MINAGI_CONFIG or `--config` on train.py and +serve.py. Every reader in the process then reads that one file, so the shape a +model is built with and the shape it is trained with still cannot disagree. """ import os +import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEFAULT = os.path.join(ROOT, "config.yaml") +ENV = "MINAGI_CONFIG" + + +def path(): + """The config file this process reads.""" + return os.environ.get(ENV) or DEFAULT + + +def take_config_flag(argv=None): + """ + Pull `--config FILE` out of argv and point MINAGI_CONFIG at it. + + Has to run before argparse, because the parsers take their defaults from + the config while they are being built, and before torch, because the + hardware block sets environment variables torch reads once at import. + """ + argv = sys.argv if argv is None else argv + for i, a in enumerate(argv): + if a == "--config" and i + 1 < len(argv): + p = argv[i + 1] + del argv[i:i + 2] + elif a.startswith("--config="): + p = a.split("=", 1)[1] + del argv[i] + else: + continue + if not os.path.exists(p): + raise SystemExit(f"--config {p}: no such file") + os.environ[ENV] = os.path.abspath(p) + return os.environ[ENV] + return None -def load(path=None): +def load(path_=None): import yaml - path = path or DEFAULT - if not os.path.exists(path): + p = path_ or path() + if not os.path.exists(p): return {} - with open(path) as f: + with open(p, encoding="utf-8") as f: return yaml.safe_load(f) or {} diff --git a/minagi/corpus.py b/minagi/corpus.py index eae7847..22db835 100644 --- a/minagi/corpus.py +++ b/minagi/corpus.py @@ -14,7 +14,7 @@ class Corpus: def __init__(self, data_dir, device, block, batch): - self.meta = json.load(open(os.path.join(data_dir, "meta.json"))) + self.meta = json.load(open(os.path.join(data_dir, "meta.json"), encoding="utf-8")) self.train = np.memmap(os.path.join(data_dir, "train.bin"), dtype=np.uint16, mode="r") self.val = np.memmap(os.path.join(data_dir, "val.bin"), diff --git a/minagi/device.py b/minagi/device.py new file mode 100644 index 0000000..b39dc57 --- /dev/null +++ b/minagi/device.py @@ -0,0 +1,179 @@ +""" +The hardware this process runs on, in one place. + +The code was written against one NVIDIA laptop card, and ROCm builds of +PyTorch answer to the same `torch.cuda` namespace, so almost nothing needs to +know which vendor it is on. What does need to know: + + - the memory budget. Growth refuses to add an expert once the peak this + process allocated passes a share of the card. A discrete card reports its + size honestly; an APU such as Strix Halo (gfx1151) reports whatever the + firmware carved out, which can be 512 MB or 96 GB on the same machine and + says nothing about the GTT memory the driver will also hand out. So the + budget can be stated, and a stated budget wins. + - whether CPU and GPU share memory. When they do, the RAM tier of the + expert pool can sit on the device itself, and paging an expert onto the + card becomes a device-to-device copy instead of a blocking host transfer. + - environment variables torch reads once at import - the allocator, ROCm's + experimental attention kernels, TunableOp - which have to be set before + torch loads. set_env_before_torch() is the only function here that may be + called before `import torch`; everything else imports it lazily. + +The `hardware:` block of the config file drives all of it; every key is +optional and the defaults reproduce the behaviour on a discrete NVIDIA card. +""" + +import os + +# Integrated RDNA 3.5: Strix Point (gfx1150), Strix Halo (gfx1151), Krackan +# Point (gfx1152). Memory is the system's LPDDR5X, shared with the CPU. +UNIFIED_ARCHES = ("gfx1150", "gfx1151", "gfx1152") + +_HW = None + + +def hw(): + """The `hardware:` block of the active config, {} when there is none.""" + global _HW + if _HW is None: + from minagi.config import load, get + _HW = get(load(), "hardware", {}) or {} + return _HW + + +def set_env_before_torch(): + """ + Environment torch reads once, at import or at first device init. + + Every variable is setdefault: anything exported in the shell wins. + """ + h = hw() + if h.get("expandable_segments", True): + # PyTorch's caching allocator otherwise strands memory between the + # checkpointed expert dispatch's large short-lived tensors - see the + # note in train.py. ROCm builds read the HIP name; recent CUDA builds + # the CUDA one. A build that does not support it warns and carries on. + for k in ("PYTORCH_CUDA_ALLOC_CONF", "PYTORCH_HIP_ALLOC_CONF"): + os.environ.setdefault(k, "expandable_segments:True") + if h.get("rocm_aotriton"): + # Without it SDPA on RDNA 3/3.5 can fall back to the math kernel, + # which materialises the whole T x T score matrix at every row. + os.environ.setdefault("TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL", "1") + if h.get("tunableop"): + # Tunes each GEMM shape once and remembers the winner. The expert + # dispatch's batched matmuls are the shapes that matter here. + os.environ.setdefault("PYTORCH_TUNABLEOP_ENABLED", "1") + os.environ.setdefault("PYTORCH_TUNABLEOP_FILENAME", + h.get("tunableop_file", "runs/tunableop.csv")) + + +def _props(): + import torch + if not torch.cuda.is_available(): + return None + return torch.cuda.get_device_properties(torch.cuda.current_device()) + + +def backend(): + """'rocm', 'cuda' or 'cpu'.""" + import torch + if not torch.cuda.is_available(): + return "cpu" + return "rocm" if getattr(torch.version, "hip", None) else "cuda" + + +def arch(): + """gfx1151, sm_86, ... or 'cpu'.""" + p = _props() + if p is None: + return "cpu" + name = getattr(p, "gcnArchName", "") or "" + if name: + return name.split(":")[0] + return f"sm_{p.major}{p.minor}" + + +def is_unified(): + """True when the GPU's memory is the system's memory.""" + if "unified" in hw(): + return bool(hw()["unified"]) + p = _props() + if p is None: + return False + return arch() in UNIFIED_ARCHES or bool(getattr(p, "is_integrated", 0)) + + +def memory_budget_bytes(): + """ + What this process may plan to allocate on the GPU, in bytes. + + hardware.gpu_mem_gb, then MINAGI_GPU_MEM_GB, then what the device reports. + 0 without a GPU. + """ + gb = hw().get("gpu_mem_gb") or os.environ.get("MINAGI_GPU_MEM_GB") + if gb: + return int(float(gb) * (1 << 30)) + p = _props() + return int(p.total_memory) if p is not None else 0 + + +def budget_source(): + if hw().get("gpu_mem_gb"): + return "config" + if os.environ.get("MINAGI_GPU_MEM_GB"): + return "MINAGI_GPU_MEM_GB" + return "device" + + +def peak_allocated(): + """Peak bytes this process has allocated on the GPU, None without one.""" + import torch + if not torch.cuda.is_available(): + return None + return torch.cuda.max_memory_allocated() + + +def mem_frac(): + """Peak allocated as a share of the budget. 0.0 without a GPU.""" + peak, budget = peak_allocated(), memory_budget_bytes() + if peak is None or budget <= 0: + return 0.0 + return peak / budget + + +def ram_tier_on_gpu(device): + """ + Whether the expert pool's RAM tier should live on `device`. + + hardware.ram_tier_on_gpu when it is set, otherwise yes exactly when the + device is a GPU that shares memory with the CPU. + """ + import torch + if torch.device(device).type != "cuda": + return False + if "ram_tier_on_gpu" in hw(): + return bool(hw()["ram_tier_on_gpu"]) + return is_unified() + + +def banner(device): + """One line naming the hardware, printed at startup.""" + import torch + if torch.device(device).type != "cuda" or not torch.cuda.is_available(): + return f"hardware: cpu, torch {torch.__version__}" + p = _props() + b = backend() + ver = (f"HIP {torch.version.hip}" if b == "rocm" + else f"CUDA {torch.version.cuda}") + extras = [] + if os.environ.get("TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL") == "1": + extras.append("aotriton") + if os.environ.get("PYTORCH_TUNABLEOP_ENABLED") == "1": + extras.append("tunableop") + if ram_tier_on_gpu(device): + extras.append("ram tier on gpu") + return (f"hardware: {p.name} ({arch()}), {b}, torch {torch.__version__} " + f"{ver}, {'unified' if is_unified() else 'discrete'} memory, " + f"budget {memory_budget_bytes() / (1 << 30):.1f} GB " + f"({budget_source()})" + + (f", {', '.join(extras)}" if extras else "")) diff --git a/minagi/ingest.py b/minagi/ingest.py index dba15d5..1030a88 100644 --- a/minagi/ingest.py +++ b/minagi/ingest.py @@ -94,7 +94,7 @@ def collect(paths, follow_symlinks=False, cache="runs/corpus_index.json"): held = {} if cache and os.path.exists(cache): try: - with open(cache) as f: + with open(cache, encoding="utf-8") as f: got = json.load(f) held = got.get("entries") or {} if sig in held: @@ -114,7 +114,7 @@ def collect(paths, follow_symlinks=False, cache="runs/corpus_index.json"): del held[k] os.makedirs(os.path.dirname(cache) or ".", exist_ok=True) tmp = cache + ".tmp" - with open(tmp, "w") as f: + with open(tmp, "w", encoding="utf-8") as f: json.dump({"entries": held}, f) os.replace(tmp, cache) except OSError: diff --git a/minagi/live.py b/minagi/live.py index 76e5c31..19d7e70 100644 --- a/minagi/live.py +++ b/minagi/live.py @@ -65,20 +65,10 @@ def __init__(self, model, lr=3e-4, trunk_lr_mult=0.2, wd=0.1, clip=1.0, self.context = int(context or getattr(model.cfg, "block", 16384)) self.buf = [] self.pending = 0 - dev = next(model.parameters()).device - trunk = [p for n, p in model.named_parameters() - if not n.startswith("pool.")] - pool_ps = [p for n, p in model.named_parameters() - if n.startswith("pool.")] - self.opt = torch.optim.AdamW( - [{"params": trunk, "name": "trunk", "weight_decay": wd, - "lr": lr * trunk_lr_mult, "base_lr": lr * trunk_lr_mult}, - {"params": pool_ps, "name": "pool", "weight_decay": wd, - "lr": lr, "base_lr": lr}], - lr=lr, betas=(0.9, 0.95), fused=(dev.type == "cuda")) - pool = getattr(model, "pool", None) - if pool is not None and hasattr(pool, "attach_optimiser"): - pool.attach_optimiser(self.opt) + # the same groups training uses - routers with the pool - and the + # paged pool attached; see minagi/build.py + from minagi.build import build_adamw + self.opt, _, _ = build_adamw(model, lr, trunk_lr_mult, wd) # ADAM'S MOMENTS carry on from where the weights directory left them, # as they do when the trainer resumes. A fresh optimiser would start # every tensor from zero moments at the first step - the trunk's and diff --git a/minagi/lock.py b/minagi/lock.py new file mode 100644 index 0000000..0823090 --- /dev/null +++ b/minagi/lock.py @@ -0,0 +1,127 @@ +""" +One writer per weights directory. + +A training read and a learning server both page experts in and out of the +same directory, and each writes back what it trained. Nothing used to stop +them running at once, and then the last writer won: a manifest from one with +the expert count of the other, an expert file pruned by one while the other +was about to read it. On Windows a save could also fail outright, because a +file the other process holds open cannot be replaced. + +So the directory carries a lock file naming its owner. It is created with +O_EXCL, which makes taking it atomic, and holds the pid, host and role of the +process that took it. A lock whose process is gone - a run that was killed - +is stale and is taken over; one held by a live process is refused, and the +caller decides what to do instead (serve.py serves read-only). +""" + +import atexit +import json +import os +import socket +import sys +import time + +NAME = ".lock" + + +class Busy(RuntimeError): + """The directory is held by another live process.""" + + def __init__(self, path, owner): + self.path, self.owner = path, owner + super().__init__( + f"{os.path.dirname(path)} is in use by {owner.get('role', '?')} " + f"(pid {owner.get('pid')} on {owner.get('host')}, since " + f"{owner.get('since', '?')}). Stop it first, or point this at " + f"another directory. Delete {path} only if you are sure it is " + f"not running.") + + +def _alive(pid): + """Whether a process with this pid exists on this machine.""" + if pid <= 0: + return False + if sys.platform == "win32": + import ctypes + from ctypes import wintypes + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + k32.OpenProcess.restype = wintypes.HANDLE + h = k32.OpenProcess(0x1000, False, pid) # QUERY_LIMITED_INFORMATION + if not h: + # access denied means it exists; anything else, that it does not + return ctypes.get_last_error() == 5 + try: + code = wintypes.DWORD() + if not k32.GetExitCodeProcess(h, ctypes.byref(code)): + return True + return code.value == 259 # STILL_ACTIVE + finally: + k32.CloseHandle(h) + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True + + +def owner(wdir): + """The lock's contents, or None when the directory is free.""" + try: + with open(os.path.join(wdir, NAME), encoding="utf-8") as f: + return json.load(f) + except (OSError, ValueError): + return None + + +def _stale(info): + if not info: + return True + if info.get("host") != socket.gethostname(): + return False # cannot see another machine's processes + return not _alive(int(info.get("pid", -1))) + + +def acquire(wdir, role): + """ + Take the directory for this process, or raise Busy. + + Released at exit. Taking a lock this process already holds is a no-op. + """ + os.makedirs(wdir, exist_ok=True) + path = os.path.join(wdir, NAME) + me = {"pid": os.getpid(), "host": socket.gethostname(), "role": role, + "since": time.strftime("%Y-%m-%d %H:%M:%S")} + for _ in range(2): + try: + fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) + except FileExistsError: + info = owner(wdir) + if info and info.get("pid") == me["pid"] \ + and info.get("host") == me["host"]: + return path + if not _stale(info): + raise Busy(path, info) + try: + os.remove(path) # a dead owner's; take it over + except FileNotFoundError: + pass + continue + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(me, f) + atexit.register(release, wdir) + return path + raise Busy(path, owner(wdir) or {}) + + +def release(wdir): + """Give the directory back, if this process holds it.""" + info = owner(wdir) + if info and info.get("pid") == os.getpid() \ + and info.get("host") == socket.gethostname(): + try: + os.remove(os.path.join(wdir, NAME)) + except OSError: + pass diff --git a/minagi/optim.py b/minagi/optim.py index 0eb8091..05a823a 100644 --- a/minagi/optim.py +++ b/minagi/optim.py @@ -37,6 +37,11 @@ def observe(self, params): if not gs: return None flat = torch.cat([g.detach().float().reshape(-1) for g in gs]) + if self.m is not None and self.m.shape != flat.shape: + # A tensor it watches changed size - growth adds a row per + # newborn to tensors outside the pool too - so the running mean + # no longer lines up with the gradient. Start the meter over. + self.m, self.sq, self.n = None, 0.0, 0 self.m = flat.clone() if self.m is None else \ self.m.mul_(self.beta).add_(flat, alpha=1 - self.beta) s = float((flat * flat).sum()) diff --git a/minagi/paged.py b/minagi/paged.py index 6370920..ae88d73 100644 --- a/minagi/paged.py +++ b/minagi/paged.py @@ -109,12 +109,21 @@ class Tiers: """ def __init__(self, path, d_model, d_ff, ram_capacity=256, device="cpu", - read_only=False): + read_only=False, tier_on_device=False): self.path = path self.d_model, self.d_ff = d_model, d_ff - self.ram = OrderedDict() # id -> dict of CPU tensors + self.ram = OrderedDict() # id -> dict of tensors + # 0 keeps every expert the pool has: nothing is evicted, and disk is + # read once per expert and written only at a flush self.ram_capacity = ram_capacity self.device = device + # Where the "RAM" tier lives. On a discrete card it is system memory + # and every page-in is a host-to-device copy. On a unified-memory APU + # (Strix Halo) system memory IS the card's memory, so the tier can be + # held as device tensors: a page-in becomes a device-to-device copy, + # parking an expert never crosses to the host, and only a disk write + # does. See minagi.device.ram_tier_on_gpu. + self.store = torch.device(device) if tier_on_device else torch.device("cpu") # Read-only means exactly that: nothing is ever marked dirty and # nothing is ever written. Needed because paging an expert IN marks it # dirty regardless of whether anything changed it, so a visualisation @@ -139,13 +148,19 @@ def _from_disk(self, i): file the whole of what that expert is, which is what the weights directory claims about itself. """ - z = np.load(self._file(i)) - out = {k: torch.from_numpy(z[k]).clone() for k in ("w1", "w3", "w2")} - for k in ("w1_m", "w3_m", "w2_m", "w1_v", "w3_v", "w2_v"): - if k in z.files: - # bf16 if this file has been written since the moments were - # narrowed, fp32 if it has not; unpack_bf16 reads both - out[k] = unpack_bf16(z[k]).clone() + # Every z[k] is a fresh array, so the tensors may share its memory; + # `with` closes the file, which Windows needs before it can be + # replaced by the next write-back. + with np.load(self._file(i)) as z: + out = {k: torch.from_numpy(z[k]).to(self.store) + for k in ("w1", "w3", "w2")} + for k in ("w1_m", "w3_m", "w2_m", "w1_v", "w3_v", "w2_v"): + if k in z.files: + # bf16 if this file has been written since the moments + # were narrowed, fp32 if it has not; unpack_bf16 reads + # both. Moved first, so a device tier carries half the + # bytes across and widens them where they will live. + out[k] = unpack_bf16(torch.from_numpy(z[k]).to(self.store)) return out def fetch(self, i, count=True): @@ -167,6 +182,9 @@ def fetch(self, i, count=True): def put(self, i, tensors, dirty=True): """Hand an expert back after it has been resident.""" + # a no-op when they are already where the tier lives + tensors = {k: (v.to(self.store) if torch.is_tensor(v) else v) + for k, v in tensors.items()} self.ram[i] = tensors self.ram.move_to_end(i) if dirty and not self.read_only: @@ -174,7 +192,7 @@ def put(self, i, tensors, dirty=True): self._trim() def _trim(self): - while len(self.ram) > self.ram_capacity: + while self.ram_capacity and len(self.ram) > self.ram_capacity: j, ent = self.ram.popitem(last=False) # least recently used self.evictions += 1 if j in self.dirty: @@ -189,7 +207,8 @@ def _to_disk(self, i, ent): # what they need is exponent range and bf16 keeps all of fp32's. The # weights cannot go with them - see minagi/precision.py, which has the # measurement for both. - arrays = {k: (pack_bf16(v) if is_moment(k) else v.to(torch.float32).numpy()) + arrays = {k: (pack_bf16(v) if is_moment(k) + else v.detach().to("cpu", torch.float32).numpy()) for k, v in ent.items() if torch.is_tensor(v)} tmp = self._file(i) + ".tmp.npz" np.savez(tmp, **arrays) @@ -227,7 +246,7 @@ class PagedPool(nn.Module): def __init__(self, path, d_model, d_ff, n_experts, resident=16, ram_capacity=256, device="cpu", max_experts=1_000_000, - read_only=False): + read_only=False, tier_on_device=False): super().__init__() self.path = path self.d_model, self.d_ff = d_model, d_ff @@ -236,7 +255,7 @@ def __init__(self, path, d_model, d_ff, n_experts, resident=16, self._n = n_experts self.read_only = read_only self.tiers = Tiers(path, d_model, d_ff, ram_capacity, device, - read_only=read_only) + read_only=read_only, tier_on_device=tier_on_device) # the VRAM slots - fixed in number, their contents swapped self.w1 = nn.Parameter(torch.zeros(self.resident, d_ff, d_model)) @@ -718,13 +737,16 @@ def _entry(self, s, e, st): holds. An entry replaces the old one whole, so it never leaves them out. """ tensors = ((self.w1, "w1"), (self.w3, "w3"), (self.w2, "w2")) - ent = {nm: p.data[s].detach().to("cpu").clone() for p, nm in tensors} + # one copy each, to wherever the tier lives: the slot is reused by the + # next expert, so the entry cannot be a view of it + to = self.tiers.store + ent = {nm: p.data[s].detach().to(to, copy=True) for p, nm in tensors} if self._own[s]: for p, nm in tensors: o = st.get(p) if o and "exp_avg" in o: - ent[nm + "_m"] = o["exp_avg"][s].to("cpu").clone() - ent[nm + "_v"] = o["exp_avg_sq"][s].to("cpu").clone() + ent[nm + "_m"] = o["exp_avg"][s].to(to, copy=True) + ent[nm + "_v"] = o["exp_avg_sq"][s].to(to, copy=True) else: ent.update({k: v for k, v in self.tiers.fetch(self._f(e), count=False).items() diff --git a/minagi/pool.py b/minagi/pool.py index e68ecc8..1957d10 100644 --- a/minagi/pool.py +++ b/minagi/pool.py @@ -610,11 +610,13 @@ def _mem_frac(): reserved pool, which stays near 100% once the run is warm whether or not there is real room, so a brake reading it would refuse growth forever. Peak *allocated* is the honest number - it is what has to fit. + + The denominator is minagi.device's budget rather than the card's reported + size, because on an APU the reported size is the firmware carve-out and + not what the driver will actually hand out. """ - if not torch.cuda.is_available(): - return 0.0 - total = torch.cuda.get_device_properties(0).total_memory - return torch.cuda.max_memory_allocated() / max(total, 1) + from minagi.device import mem_frac + return mem_frac() class AutoGrow: diff --git a/minagi/precision.py b/minagi/precision.py index 906a182..6862d65 100644 --- a/minagi/precision.py +++ b/minagi/precision.py @@ -85,7 +85,7 @@ def pack_bf16(t): """A float tensor as int16 carrying bfloat16 bits, for storage.""" if not torch.is_tensor(t): t = torch.as_tensor(t) - return t.to(torch.bfloat16).view(torch.int16).numpy() + return t.detach().to("cpu", torch.bfloat16).view(torch.int16).numpy() def unpack_bf16(a): diff --git a/minagi/recur.py b/minagi/recur.py index 019f0f4..b4bf8e7 100644 --- a/minagi/recur.py +++ b/minagi/recur.py @@ -491,19 +491,13 @@ def _load_dir(path, device, paged=None, read_only=False): import os import sys from . import store as weights_store - with open(os.path.join(path, "manifest.json")) as f: + with open(os.path.join(path, "manifest.json"), encoding="utf-8") as f: man = json.load(f) if paged is None: paged = bool(man.get("paged")) if paged: - # build_paged lives in train.py; a caller in another directory (the - # film's captures run from video/) needs the repo root on the path - _root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - if _root not in sys.path: - sys.path.insert(0, _root) - import train as _train - m, cfg, pool, man2 = _train.build_paged(path, device, - read_only=read_only) + from .build import build_paged + m, cfg, pool, man2 = build_paged(path, device, read_only=read_only) return m, {"cfg": cfg.__dict__, "step": man2.get("step"), "val": man2.get("val")} cfg = RecurConfig(**{k: v for k, v in (man.get("cfg") or {}).items() diff --git a/minagi/store.py b/minagi/store.py index 3264f87..6e2c9ba 100644 --- a/minagi/store.py +++ b/minagi/store.py @@ -142,7 +142,7 @@ def save(model, path, step=None, val=None, opt=None, cfg=None, verbose=False, "removed_expert_files": removed, } tmp = os.path.join(path, "manifest.json.tmp") - with open(tmp, "w") as f: + with open(tmp, "w", encoding="utf-8") as f: json.dump(manifest, f, indent=1) os.replace(tmp, os.path.join(path, "manifest.json")) if verbose: @@ -248,7 +248,7 @@ def _save_paged(model, pool, path, step, val, opt, cfg, verbose, extra=None): "experts": entries, "total_bytes": int(total)} manifest.update(extra or {}) # where the reader had got to tmp = os.path.join(path, "manifest.json.tmp") - with open(tmp, "w") as f: + with open(tmp, "w", encoding="utf-8") as f: json.dump(manifest, f, indent=1) os.replace(tmp, os.path.join(path, "manifest.json")) if verbose: @@ -295,31 +295,33 @@ def _save_optim(opt, model, path): def load(model, path, opt=None, device=None, strict=False, verbose=False): """Rebuild a model's tensors from the directory.""" device = device or next(model.parameters()).device - with open(os.path.join(path, "manifest.json")) as f: + with open(os.path.join(path, "manifest.json"), encoding="utf-8") as f: man = json.load(f) sd = {} - core = np.load(os.path.join(path, "core.npz")) - routers = np.load(os.path.join(path, "routers.npz")) - for k in core.files: - sd[k] = torch.from_numpy(core[k]) - for k in routers.files: - sd[k] = torch.from_numpy(routers[k]) + # every npz is opened in `with`: Windows cannot replace a file that is + # still open, and the next save replaces all of them + with np.load(os.path.join(path, "core.npz")) as core: + for k in core.files: + sd[k] = torch.from_numpy(core[k]) + with np.load(os.path.join(path, "routers.npz")) as routers: + for k in routers.files: + sd[k] = torch.from_numpy(routers[k]) d_model, d_ff = man["d_model"], man["d_ff"] n1 = d_ff * d_model for e in man["experts"]: f = os.path.join(path, EXPERTS, e["file"]) i = e["id"] if f.endswith(".npz"): - z = np.load(f) - for leaf in z.files: - if leaf.endswith(("_m", "_v")): - continue # optimiser state, not weights - if leaf.startswith("b") and "_" in leaf: - b, nm = leaf[1:].split("_", 1) - key = f"pool.experts.{i}.blocks.{b}.{nm}.weight" - else: - key = f"pool.experts.{i}.{leaf}.weight" - sd[key] = torch.from_numpy(z[leaf]) + with np.load(f) as z: + for leaf in z.files: + if leaf.endswith(("_m", "_v")): + continue # optimiser state, not weights + if leaf.startswith("b") and "_" in leaf: + b, nm = leaf[1:].split("_", 1) + key = f"pool.experts.{i}.blocks.{b}.{nm}.weight" + else: + key = f"pool.experts.{i}.{leaf}.weight" + sd[key] = torch.from_numpy(z[leaf]) else: # the older flat layout, before moments moved into the file flat = torch.from_numpy(np.load(f)) @@ -342,27 +344,27 @@ def _load_optim(opt, model, path): f = os.path.join(path, "optim.npz") if not os.path.exists(f): return - z = np.load(f) - name_of = {id(p): n for n, p in model.named_parameters()} - for group in opt.param_groups: - for p in group["params"]: - n = name_of.get(id(p)) - if n is None or (n + "|m") not in z.files: - continue - m = unpack_bf16(z[n + "|m"]) - v = unpack_bf16(z[n + "|v"]) - # a tensor that changed shape since the moments were written - the - # embedding after a vocabulary extension, an expert after growth - - # has to start with fresh moments rather than mismatched ones - if m.shape != p.shape or v.shape != p.shape: - continue - st = opt.state[p] - st["exp_avg"] = m.to(device=p.device, dtype=p.dtype) - st["exp_avg_sq"] = v.to(device=p.device, dtype=p.dtype) - if (n + "|t") in z.files: - # fused AdamW requires the step counter on the same device as - # the parameter, not on the CPU where it was just loaded - st["step"] = torch.tensor(float(z[n + "|t"]), device=p.device) + with np.load(f) as z: + name_of = {id(p): n for n, p in model.named_parameters()} + for group in opt.param_groups: + for p in group["params"]: + n = name_of.get(id(p)) + if n is None or (n + "|m") not in z.files: + continue + m = unpack_bf16(z[n + "|m"]) + v = unpack_bf16(z[n + "|v"]) + # a tensor that changed shape since the moments were written - the + # embedding after a vocabulary extension, an expert after growth - + # has to start with fresh moments rather than mismatched ones + if m.shape != p.shape or v.shape != p.shape: + continue + st = opt.state[p] + st["exp_avg"] = m.to(device=p.device, dtype=p.dtype) + st["exp_avg_sq"] = v.to(device=p.device, dtype=p.dtype) + if (n + "|t") in z.files: + # fused AdamW requires the step counter on the same device as + # the parameter, not on the CPU where it was just loaded + st["step"] = torch.tensor(float(z[n + "|t"]), device=p.device) def _load_expert_moments(opt, model, path): @@ -387,10 +389,15 @@ def _load_expert_moments(opt, model, path): st = opt.state[p] st["exp_avg"] = m.to(device=p.device, dtype=p.dtype) st["exp_avg_sq"] = v.to(device=p.device, dtype=p.dtype) + # Windows cannot replace a file that is still open, and the next save + # replaces every one of these + for z in cache.values(): + if z is not None: + z.close() def summarise(path): - with open(os.path.join(path, "manifest.json")) as f: + with open(os.path.join(path, "manifest.json"), encoding="utf-8") as f: man = json.load(f) ne = len([f for f in os.listdir(os.path.join(path, EXPERTS)) if f.endswith((".npy", ".npz"))]) @@ -443,6 +450,6 @@ def best_val(path): f = os.path.join(path, "manifest.json") if not os.path.exists(f): return float("inf") - with open(f) as fh: + with open(f, encoding="utf-8") as fh: v = json.load(fh).get("val") return float(v) if v is not None else float("inf") diff --git a/minagi/tokenizer.py b/minagi/tokenizer.py index 9f17a8f..5b5a154 100644 --- a/minagi/tokenizer.py +++ b/minagi/tokenizer.py @@ -82,7 +82,7 @@ def token_to_id(self, token): def load_tokenizer(data_dir): meta_path = os.path.join(data_dir, "meta.json") if os.path.exists(meta_path): - meta = json.load(open(meta_path)) + meta = json.load(open(meta_path, encoding="utf-8")) if meta.get("tokenizer") == "byte": return ByteTokenizer() from tokenizers import Tokenizer diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a588fde --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,27 @@ +[project] +name = "mini-agi" +version = "0.1.0" +description = "A continual-learning byte-level model that pages its experts from disk" +readme = "README.md" +requires-python = ">=3.10" +license = { file = "LICENSE" } +# torch is deliberately NOT listed: the right wheel depends on the GPU - +# CUDA from pytorch.org, ROCm for AMD (gfx1151 / Strix Halo from AMD's own +# index). Installing it from PyPI here would silently replace a ROCm build +# with a CUDA one. See "Running it" in the README. +dependencies = [ + "numpy>=1.24", + "pyyaml>=6.0", + "matplotlib>=3.7", +] + +[project.optional-dependencies] +serve = ["flask>=2.3"] +corpora = ["chess>=1.10", "zstandard>=0.21", "datasets>=2.18", "tokenizers>=0.15"] +dev = ["pytest>=7.4"] + +[tool.setuptools] +packages = ["minagi", "corpora"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/replication/cl_summary.py b/replication/cl_summary.py index d6bd815..ca05acf 100644 --- a/replication/cl_summary.py +++ b/replication/cl_summary.py @@ -29,7 +29,7 @@ def R(name): def summarise(path): - j = json.load(open(path)) + j = json.load(open(path, encoding="utf-8")) doms, base, rows = j["domains"], j["baseline"], j["rows"] lanes = j.get("lanes", [j["domain"]]) read = [d for d in doms if d in lanes] diff --git a/replication/forgetting_probe.py b/replication/forgetting_probe.py index 5b87422..95ced19 100644 --- a/replication/forgetting_probe.py +++ b/replication/forgetting_probe.py @@ -178,15 +178,12 @@ def main(): doms = sorted(ev.groups) print(f" scoring {len(doms)} held-out domains: {', '.join(doms)}") - trunk, pool_ps = T._split_trunk_pool(model) - tg = {"params": trunk, "name": "trunk", "weight_decay": a.wd, - "lr": a.lr * a.trunk_lr_mult} - pg = {"params": pool_ps, "name": "pool", "weight_decay": a.wd, "lr": a.lr} - opt = torch.optim.AdamW([tg, pg], lr=a.lr, betas=(0.9, 0.95)) # The pool steps every expert on the card with that expert's own moments, - # which it can only do if it knows the optimiser. Unattached, an expert - # paged in was stepped with whatever its slot held for the one before. - pool.attach_optimiser(opt) + # which it can only do if it knows the optimiser - build_adamw attaches + # it. Unattached, an expert paged in was stepped with whatever its slot + # held for the one before. + from minagi.build import build_adamw + opt, trunk, pool_ps = build_adamw(model, a.lr, a.trunk_lr_mult, a.wd) if not a.cold_optim: from minagi.store import _load_optim try: @@ -369,7 +366,7 @@ def rel(ps, ref): "domains": doms, "baseline": {k: base[k] for k in doms}, "rows": rows} os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) - with open(a.out, "w") as f: + with open(a.out, "w", encoding="utf-8") as f: json.dump(out, f, indent=1) print(f"\n -> {a.out}") diff --git a/replication/plot_figures.py b/replication/plot_figures.py index 3a6882c..269cd5f 100644 --- a/replication/plot_figures.py +++ b/replication/plot_figures.py @@ -71,7 +71,7 @@ def label(d): def fig_probe(path, out): - j = json.load(open(path)) + j = json.load(open(path, encoding="utf-8")) doms, rows = j["domains"], j["rows"] base = j["baseline"] lanes = [d for d in j.get("lanes", [j["domain"]]) if d in doms] @@ -209,7 +209,7 @@ def fig_ablation(out): "swapping normally, trunk at 0.1x (the run)", "#2a78d6", "-", 2.7), ] RAND = float(np.log(265)) - _j0 = json.load(open(SPECS[-1][0])) + _j0 = json.load(open(SPECS[-1][0], encoding="utf-8")) READ = label(_j0["domain"]) NOTH = len([d for d in _j0["domains"] if d not in _j0.get("lanes", [_j0["domain"]])]) @@ -220,7 +220,7 @@ def fig_ablation(out): gridspec_kw={"width_ratios": [1.5, 1.15, 1]}) if os.path.exists(R("control.json")): - c = json.load(open(R("control.json"))) + c = json.load(open(R("control.json"), encoding="utf-8")) rd = _mean_delta(c, "read") if rd: ax.plot([x / 1000 for x, _ in rd], [y for _, y in rd], @@ -232,7 +232,7 @@ def fig_ablation(out): for path, name, col, dash, lw in SPECS: if not os.path.exists(path): continue - j = json.load(open(path)) + j = json.load(open(path, encoding="utf-8")) d = _mean_delta(j) xs = [x / 1000 for x, _ in d]; ys = [y for _, y in d] xmax = max(xmax, xs[-1]) diff --git a/serve.py b/serve.py index b8656d7..e44e3a0 100644 --- a/serve.py +++ b/serve.py @@ -30,8 +30,12 @@ import time # see train.py: the allocator reads this once at CUDA init, so it has to be -# set before torch loads -os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") +# set before torch loads - and `--config` picks the file whose hardware block +# decides it +from minagi.config import take_config_flag # noqa: E402 +from minagi.device import set_env_before_torch # noqa: E402 +take_config_flag() +set_env_before_torch() import torch from flask import Flask, Response, jsonify, request @@ -49,6 +53,37 @@ U0, U1, B0, B1 = "", "", "", "" +# The most characters one reply may ask for. Generation holds LOCK, so an +# unbounded request would hold every other conversation for as long as it +# liked. +MAX_NEW = 2048 + +# Host names a request may address when the server is bound to loopback. A +# page on another site can make the browser POST here; checking Origin +# refuses that, and checking Host refuses the DNS-rebinding form of it, where +# the attacker's name resolves to 127.0.0.1 and Origin matches Host. None +# when bound to a public interface, where the names are not knowable. +ALLOWED_HOSTS = None +LOOPBACK = ("127.0.0.1", "localhost", "::1") + + +def _hostname(netloc): + if netloc.startswith("["): + return netloc[1:netloc.find("]")] + return netloc.rsplit(":", 1)[0] if netloc.count(":") == 1 else netloc + + +def _refuse_foreign(): + """A response refusing a request from outside, or None to serve it.""" + from urllib.parse import urlparse + if (ALLOWED_HOSTS is not None + and _hostname(request.host) not in ALLOWED_HOSTS): + return jsonify(error="unknown Host"), 403 + origin = request.headers.get("Origin") + if origin and urlparse(origin).netloc != request.host: + return jsonify(error="cross-origin request refused"), 403 + return None + # A passage of the corpus the conversation opens with. Empty when priming is # off or no corpus is on disk. PRIME = "" @@ -89,7 +124,7 @@ def load_prime(chars, root="data/train/self-knowledge"): names = ([n for n in names if n.startswith("self-")] + [n for n in names if not n.startswith("self-")]) for name in names[:20]: - with open(os.path.join(root, name), errors="replace") as f: + with open(os.path.join(root, name), errors="replace", encoding="utf-8") as f: text = f.read(chars * 3) best = "" at = text.find(f"{B1}\n") @@ -108,7 +143,7 @@ def load_prime(chars, root="data/train/self-knowledge"): def _manifest(path): """As loaded, so a save does not overwrite it with a blank one.""" try: - with open(os.path.join(path, "manifest.json")) as f: + with open(os.path.join(path, "manifest.json"), encoding="utf-8") as f: return json.load(f) except (OSError, ValueError): return {} @@ -133,7 +168,9 @@ def load(weights, device=None, learn=True, lr=3e-4, save_every=8, print("[warn] CUDA is full, serving on CPU", file=sys.stderr) model.eval() STATE.update(model=model, tok=ByteTokenizer(), weights=weights) + from minagi.device import banner print(f"[loaded] {weights} on {dev}", file=sys.stderr) + print(f"[{banner(dev)}]", file=sys.stderr) # A paged model loads with an EMPTY card - every slot -1. A reply is # admitted by its own text's vote, so this does not change a reply; what @@ -239,6 +276,7 @@ def build_prompt(messages, budget, prime=""): def stream(prompt, max_new): from minagi.config import get as _g, load as _lc from minagi.decode import pick_next + from minagi.precision import amp from minagi.stream import trim_caches c = _lc() @@ -284,7 +322,11 @@ def where(caches): for i in range(0, out.shape[1], CHUNK): part = out[:, i:i + CHUNK] trim_caches(caches, model.cfg.block - part.shape[1]) - logits = model(part, caches=caches, pos_offset=where(caches))[0] + # In the compute dtype training runs in - bf16 by default. Without + # it a reply ran fp32 everywhere but the expert dispatch. Entered per + # forward rather than around the generator, which yields in between. + with amp(device): + logits = model(part, caches=caches, pos_offset=where(caches))[0] cur = out[:, -1:] produced = [] @@ -295,7 +337,8 @@ def where(caches): loads = getattr(pool, "loads", 0) if logits is None: trim_caches(caches, model.cfg.block - cur.shape[1]) - logits = model(cur, caches=caches, pos_offset=where(caches))[0] + with amp(device): + logits = model(cur, caches=caches, pos_offset=where(caches))[0] moved = getattr(pool, "loads", 0) - loads if moved: # this character asked for experts that were not on the card; @@ -357,11 +400,25 @@ def remember(user_text, bot_text): @app.route("/api/chat", methods=["POST"]) def api_chat(): - body = request.get_json(force=True) + # What is said here is trained into the weights on disk, so who may say + # it matters. JSON only: a cross-site form or a text/plain fetch is a + # "simple" request the browser sends without asking, and force=True used + # to parse it anyway. + bad = _refuse_foreign() + if bad is not None: + return bad + if not request.is_json: + return jsonify(error="send application/json"), 415 + body = request.get_json(silent=True) + if not isinstance(body, dict): + return jsonify(error="the body is not a JSON object"), 400 model = STATE["model"] - msgs = body.get("messages", []) + msgs = [m for m in body.get("messages", []) if isinstance(m, dict)] prompt = build_prompt(msgs, int(model.cfg.block * 0.9), PRIME) - max_new = int(body.get("max_new", 400)) + try: + max_new = max(1, min(int(body.get("max_new", 400)), MAX_NEW)) + except (TypeError, ValueError): + return jsonify(error="max_new must be a number"), 400 # the half of the exchange the model did not predict, which is where the # signal in a conversation is last_user = next((m.get("content") for m in reversed(msgs) @@ -832,6 +889,10 @@ def main(): "the cost of a denser diet than documents give") ap.add_argument("--save-every", type=int, default=8, help="optimiser steps between writing the weights out") + ap.add_argument("--allow-remote-learning", action="store_true", + help="keep learning on when --host is not loopback. Off " + "by default: anyone who can reach the port would be " + "writing to the weights") ap.add_argument("--precision", default=None, choices=["bf16", "fp16", "fp32"], help="what the forward computes in; defaults to whatever " @@ -854,6 +915,25 @@ def main(): print(" no corpus to prime from - the router will choose experts " "from the prompt alone", file=sys.stderr) + global ALLOWED_HOSTS + if args.host in LOOPBACK: + ALLOWED_HOSTS = set(LOOPBACK) + elif args.learn and not args.allow_remote_learning: + print(f" --host {args.host} is reachable from other machines, so " + f"learning is OFF. --allow-remote-learning turns it back on.", + file=sys.stderr) + args.learn = False + + if args.learn: + # One writer per directory: a training run reading into it at the + # same time would have its experts written over, and its manifest. + from minagi.lock import Busy, acquire + try: + acquire(args.weights, "serve.py (learning)") + except Busy as e: + print(f" {e}\n Serving READ-ONLY instead.", file=sys.stderr) + args.learn = False + if args.learn: print(f"\n LEARNING IS ON. Talking to this model CHANGES " f"{args.weights}/ on disk.\n Use --no-learn to serve it " diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..94221f1 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,37 @@ +""" +A model small enough to build, train and reload on a CPU in seconds. + +Every test that touches a model gets its own config file and weights +directory under tmp_path, selected through MINAGI_CONFIG exactly as +`--config` selects one for train.py and serve.py. +""" + +import os +import sys + +import pytest +import yaml + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + + +@pytest.fixture +def tiny(tmp_path, monkeypatch): + with open(os.path.join(ROOT, "config.yaml"), encoding="utf-8") as f: + c = yaml.safe_load(f) + c["model"].update(d_model=32, n_head=2, d_ff=64, max_steps=2, + bptt_window=2, train_steps_mean=0, context_start=128, + context_end=128) + c["pool"].update(experts=6, width=32, top_k=2, resident=3, ram_cache=2) + c["training"].update(chunk=64, precision="fp32") + w = str(tmp_path / "weights") + c["data"].update(weights=w) + c["plots"]["enabled"] = False + p = tmp_path / "tiny.yaml" + with open(p, "w", encoding="utf-8") as f: + yaml.safe_dump(c, f) + monkeypatch.setenv("MINAGI_CONFIG", str(p)) + from minagi import device + monkeypatch.setattr(device, "_HW", None) + return {"config": str(p), "weights": w, "cfg": c} diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..6117e30 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,30 @@ +import os + +import pytest + +from minagi import config + + +def test_take_config_flag(tmp_path, monkeypatch): + p = tmp_path / "c.yaml" + p.write_text("model:\n d_model: 7\n", encoding="utf-8") + monkeypatch.delenv(config.ENV, raising=False) + argv = ["train.py", "--config", str(p), "read", "x"] + config.take_config_flag(argv) + assert argv == ["train.py", "read", "x"] + assert os.environ[config.ENV] == str(p) + assert config.get(config.load(), "model.d_model") == 7 + + argv = ["serve.py", f"--config={p}"] + config.take_config_flag(argv) + assert argv == ["serve.py"] + + +def test_missing_config_file_is_an_error(): + with pytest.raises(SystemExit): + config.take_config_flag(["x", "--config", "no/such/file.yaml"]) + + +def test_default_without_env(monkeypatch): + monkeypatch.delenv(config.ENV, raising=False) + assert config.path() == config.DEFAULT diff --git a/tests/test_device.py b/tests/test_device.py new file mode 100644 index 0000000..fca1ea6 --- /dev/null +++ b/tests/test_device.py @@ -0,0 +1,66 @@ +import os +from types import SimpleNamespace + +from minagi import device + + +def _props(name="", total=8 << 30, integrated=0): + return SimpleNamespace(gcnArchName=name, total_memory=total, major=8, + minor=6, is_integrated=integrated, name="test") + + +def test_budget_precedence(monkeypatch): + monkeypatch.setattr(device, "_props", lambda: _props(total=2 << 30)) + monkeypatch.delenv("MINAGI_GPU_MEM_GB", raising=False) + + monkeypatch.setattr(device, "_HW", {}) + assert device.memory_budget_bytes() == 2 << 30 + assert device.budget_source() == "device" + + monkeypatch.setenv("MINAGI_GPU_MEM_GB", "16") + assert device.memory_budget_bytes() == 16 << 30 + assert device.budget_source() == "MINAGI_GPU_MEM_GB" + + monkeypatch.setattr(device, "_HW", {"gpu_mem_gb": 96}) + assert device.memory_budget_bytes() == 96 << 30 + assert device.budget_source() == "config" + + +def test_no_gpu_budget_is_zero(monkeypatch): + monkeypatch.setattr(device, "_props", lambda: None) + monkeypatch.setattr(device, "_HW", {}) + monkeypatch.delenv("MINAGI_GPU_MEM_GB", raising=False) + assert device.memory_budget_bytes() == 0 + + +def test_unified_detection(monkeypatch): + monkeypatch.setattr(device, "_HW", {}) + monkeypatch.setattr(device, "_props", lambda: _props("gfx1151:xnack-")) + assert device.arch() == "gfx1151" + assert device.is_unified() + + monkeypatch.setattr(device, "_props", lambda: _props("gfx1100")) + assert not device.is_unified() + + monkeypatch.setattr(device, "_props", lambda: _props("")) + assert device.arch() == "sm_86" + assert not device.is_unified() + + monkeypatch.setattr(device, "_HW", {"unified": True}) + assert device.is_unified() + + +def test_ram_tier_never_on_cpu(monkeypatch): + monkeypatch.setattr(device, "_HW", {"ram_tier_on_gpu": True}) + assert device.ram_tier_on_gpu("cpu") is False + + +def test_env_is_setdefault(monkeypatch): + monkeypatch.setattr(device, "_HW", {"rocm_aotriton": True, + "tunableop": True}) + monkeypatch.setenv("PYTORCH_TUNABLEOP_ENABLED", "0") + monkeypatch.delenv("TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL", + raising=False) + device.set_env_before_torch() + assert os.environ["TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL"] == "1" + assert os.environ["PYTORCH_TUNABLEOP_ENABLED"] == "0" # the shell wins diff --git a/tests/test_lock.py b/tests/test_lock.py new file mode 100644 index 0000000..ee0a4e8 --- /dev/null +++ b/tests/test_lock.py @@ -0,0 +1,45 @@ +import json +import os +import socket + +import pytest + +from minagi import lock + + +def _write(wdir, pid, host=None): + os.makedirs(wdir, exist_ok=True) + with open(os.path.join(wdir, lock.NAME), "w", encoding="utf-8") as f: + json.dump({"pid": pid, "host": host or socket.gethostname(), + "role": "test"}, f) + + +def test_acquire_release(tmp_path): + w = str(tmp_path / "w") + lock.acquire(w, "test") + assert lock.owner(w)["pid"] == os.getpid() + lock.acquire(w, "test") # already ours: fine + lock.release(w) + assert lock.owner(w) is None + + +def test_live_owner_refuses(tmp_path): + w = str(tmp_path / "w") + _write(w, os.getppid()) # the test runner's parent: alive + with pytest.raises(lock.Busy): + lock.acquire(w, "test") + + +def test_dead_owner_is_taken_over(tmp_path): + w = str(tmp_path / "w") + _write(w, 2 ** 22 + 12345) # no such process + lock.acquire(w, "test") + assert lock.owner(w)["pid"] == os.getpid() + lock.release(w) + + +def test_other_host_is_never_stale(tmp_path): + w = str(tmp_path / "w") + _write(w, 1, host="some-other-machine") + with pytest.raises(lock.Busy): + lock.acquire(w, "test") diff --git a/tests/test_roundtrip.py b/tests/test_roundtrip.py new file mode 100644 index 0000000..3edb2a2 --- /dev/null +++ b/tests/test_roundtrip.py @@ -0,0 +1,87 @@ +""" +Create, train, grow, save and reload a paged model - the life cycle every +run goes through - and check the reloaded model computes the same thing. +""" + +import os +from dataclasses import asdict + +import numpy as np +import torch + + +def _text(n, seed=0): + g = torch.Generator().manual_seed(seed) + return torch.randint(32, 127, (1, n), generator=g) + + +def _train(model, opt, steps=3): + model.train() + x = _text(65) + for _ in range(steps): + opt.zero_grad(set_to_none=True) + _, loss = model(x[:, :-1], targets=x[:, 1:]) + loss.backward() + opt.step() + return float(loss) + + +def test_create_train_grow_save_reload(tiny): + from minagi import store + from minagi.build import build_adamw, build_paged + from minagi.create import create + + w = tiny["weights"] + create(w, verbose=False) + torch.manual_seed(0) + model, cfg, pool, _ = build_paged(w, "cpu") + assert pool.tiers.ram_capacity == 2 # from the tiny config + opt, trunk, pool_ps = build_adamw(model, 1e-3, 0.1, 0.0) + assert {g["name"] for g in opt.param_groups} == {"trunk", "pool"} + loss = _train(model, opt) + assert np.isfinite(loss) + + n0 = pool.n_experts() + pool.add_experts(1, step=3) + assert pool.n_experts() == n0 + 1 + store.save(model, w, step=3, val=None, opt=opt, cfg=asdict(cfg)) + assert len(os.listdir(os.path.join(w, "experts"))) == n0 + 1 + + x = _text(64, seed=1) + model.eval() + with torch.no_grad(): + a = model(x)[0] + m2, _, p2, man = build_paged(w, "cpu") + m2.eval() + assert p2.n_experts() == n0 + 1 + assert man["step"] == 3 + with torch.no_grad(): + b = m2(x)[0] + assert torch.allclose(a, b, atol=1e-4), (a - b).abs().max() + + +def test_unlimited_tier_keeps_everything(tiny): + from minagi.create import create + from minagi.paged import Tiers + + w = tiny["weights"] + create(w, verbose=False) + t = Tiers(os.path.join(w, "experts"), 32, 32, ram_capacity=0, + read_only=True) + for i in range(6): + t.fetch(i) + assert len(t.ram) == 6 and t.evictions == 0 + + +def test_expert_file_replaceable_after_read(tiny): + """Windows cannot replace a file that is still open.""" + from minagi.create import create + from minagi.paged import Tiers + + w = tiny["weights"] + create(w, verbose=False) + t = Tiers(os.path.join(w, "experts"), 32, 32, ram_capacity=0) + ent = t.fetch(0) + t.put(0, ent, dirty=True) + t.flush() # os.replace over e00000.npz + assert t.writebacks == 1 diff --git a/tests/test_serve.py b/tests/test_serve.py new file mode 100644 index 0000000..22c4039 --- /dev/null +++ b/tests/test_serve.py @@ -0,0 +1,32 @@ +"""The chat endpoint trains on what it is sent, so who may send matters.""" + +import pytest + + +@pytest.fixture +def client(monkeypatch): + pytest.importorskip("flask") + import serve + monkeypatch.setattr(serve, "ALLOWED_HOSTS", set(serve.LOOPBACK)) + return serve.app.test_client() + + +def test_refuses_non_json(client): + r = client.post("/api/chat", data='{"messages": []}', + content_type="text/plain", + headers={"Host": "127.0.0.1:8080"}) + assert r.status_code == 415 + + +def test_refuses_foreign_origin(client): + r = client.post("/api/chat", json={"messages": []}, + headers={"Host": "127.0.0.1:8080", + "Origin": "https://evil.example"}) + assert r.status_code == 403 + + +def test_refuses_rebound_host(client): + r = client.post("/api/chat", json={"messages": []}, + headers={"Host": "evil.example:8080", + "Origin": "http://evil.example:8080"}) + assert r.status_code == 403 diff --git a/tools/bench_hw.py b/tools/bench_hw.py new file mode 100644 index 0000000..0b95d53 --- /dev/null +++ b/tools/bench_hw.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +""" +What this machine costs the model, measured. + + python tools/bench_hw.py # config.yaml + python tools/bench_hw.py --config configs/strix_halo_large.yaml + python tools/bench_hw.py --quick # a minute + +No corpus and no weights needed: it builds a throwaway model from the config +in a temporary directory and times the four things that decide how fast it +reads. + + attention F.scaled_dot_product_attention at the config's shapes, with no + cache (is_causal) and behind one (the boolean mask every + cached forward uses), and which SDPA kernels this build will + run. On ROCm without AOTriton the masked path is the math + kernel, which builds the whole T x T score matrix. + experts the expert dispatch's batched matmuls, forward and backward, + at [resident, capacity, d_model] x [resident, d_model, width]. + step one training step as the reader takes it: `chunk` characters + behind a cache of the rest of the window, forward, backward, + AdamW. Characters per second and peak memory. + paging one expert from disk into the RAM tier, and from the tier onto + a VRAM slot - with the tier in host memory and, on a GPU, on + the device. + +Run it once per config you are considering, on the machine you will train +on, before committing weeks to a run. Results go to runs/bench_hw-.json. +""" + +import os +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from minagi.config import take_config_flag # noqa: E402 +from minagi.device import set_env_before_torch # noqa: E402 +take_config_flag() +set_env_before_torch() + +import argparse # noqa: E402 +import json # noqa: E402 +import shutil # noqa: E402 +import tempfile # noqa: E402 +import time # noqa: E402 + +import torch # noqa: E402 +import torch.nn.functional as F # noqa: E402 + + +def sync(dev): + if dev.type == "cuda": + torch.cuda.synchronize() + + +def timed(fn, dev, reps, warm=2): + """Median milliseconds of fn() over reps, after warm calls.""" + for _ in range(warm): + fn() + sync(dev) + ts = [] + for _ in range(reps): + t = time.perf_counter() + fn() + sync(dev) + ts.append((time.perf_counter() - t) * 1e3) + ts.sort() + return ts[len(ts) // 2] + + +def sdpa_kernels(dev, dt, H, hd): + """Which SDPA backends this build will run at these shapes.""" + try: + from torch.nn.attention import SDPBackend, sdpa_kernel + except ImportError: + return {} + q = torch.randn(1, H, 256, hd, device=dev, dtype=dt) + out = {} + for name in ("FLASH_ATTENTION", "EFFICIENT_ATTENTION", "MATH"): + be = getattr(SDPBackend, name, None) + if be is None: + continue + try: + with sdpa_kernel(be): + F.scaled_dot_product_attention(q, q, q, is_causal=True) + out[name.lower()] = True + except RuntimeError: + out[name.lower()] = False + return out + + +def bench_attention(dev, dt, H, hd, lengths, chunk, reps): + rows = [] + for T in lengths: + q = torch.randn(1, H, T, hd, device=dev, dtype=dt) + try: + causal = timed(lambda: F.scaled_dot_product_attention( + q, q, q, is_causal=True), dev, reps) + except RuntimeError as e: # out of memory, most likely + causal = f"failed: {str(e).splitlines()[0][:80]}" + # the cached path: `chunk` queries against T keys, an offset triangle + Q = min(chunk, T) + qc = torch.randn(1, H, Q, hd, device=dev, dtype=dt) + P = T - Q + mask = (torch.arange(T, device=dev).unsqueeze(0) + <= torch.arange(Q, device=dev).unsqueeze(1) + P) + try: + masked = timed(lambda: F.scaled_dot_product_attention( + qc, q, q, attn_mask=mask), dev, reps) + except RuntimeError as e: + masked = f"failed: {str(e).splitlines()[0][:80]}" + rows.append({"T": T, "causal_ms": causal, "cached_ms": masked, + "cached_queries": Q}) + del q, qc, mask + return rows + + +def bench_experts(dev, dt, resident, d_model, width, chunk, top_k, cf, reps): + cap = max(1, int(chunk * top_k / resident * cf)) + x = torch.randn(resident, cap, d_model, device=dev, dtype=dt, + requires_grad=True) + w1 = torch.randn(resident, d_model, width, device=dev, dtype=dt, + requires_grad=True) + w3 = torch.randn_like(w1, requires_grad=True) + w2 = torch.randn(resident, width, d_model, device=dev, dtype=dt, + requires_grad=True) + + def fwd(): + return torch.bmm(F.silu(torch.bmm(x, w1)) * torch.bmm(x, w3), w2) + + def fwd_bwd(): + fwd().float().sum().backward() + + with torch.no_grad(): + f = timed(fwd, dev, reps) + fb = timed(fwd_bwd, dev, reps) + flops = 2 * resident * cap * d_model * width * 3 + return {"resident": resident, "capacity": cap, "fwd_ms": f, + "fwd_bwd_ms": fb, "fwd_tflops": flops / (f * 1e-3) / 1e12, + "fwd_bwd_tflops": 3 * flops / (fb * 1e-3) / 1e12} + + +def bench_step(dev, wdir, chunk, context, reps, lr=3e-4): + from minagi.build import build_paged, _split_trunk_pool + from minagi.precision import amp + from minagi.stream import detach_caches, trim_caches + + model, cfg, pool, _ = build_paged(wdir, dev, ceiling=context) + model.train() + trunk, pool_ps = _split_trunk_pool(model) + opt = torch.optim.AdamW( + [{"params": trunk, "lr": lr * 0.1}, {"params": pool_ps, "lr": lr}], + lr=lr, betas=(0.9, 0.95), fused=(dev.type == "cuda")) + pool.attach_optimiser(opt) + g = torch.Generator().manual_seed(0) + + def text(n): + return torch.randint(32, 127, (1, n), generator=g).to(dev) + + caches = model.empty_caches() + P = max(0, context - chunk) + if P: + with torch.no_grad(), amp(dev): + for i in range(0, P, chunk): + n = min(chunk, P - i) + model(text(n), caches=caches, pos_offset=i) + + def step(): + trim_caches(caches, context - chunk) + pos = caches[0]["k"].shape[-2] if caches[0].get("k") is not None else 0 + x = text(chunk + 1) + opt.zero_grad(set_to_none=True) + with amp(dev): + _, loss = model(x[:, :-1], targets=x[:, 1:], caches=caches, + pos_offset=pos) + loss.backward() + detach_caches(caches) + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + + if dev.type == "cuda": + torch.cuda.reset_peak_memory_stats() + ms = timed(step, dev, reps, warm=1) + peak = (torch.cuda.max_memory_allocated() / (1 << 30) + if dev.type == "cuda" else None) + rep = pool.report() if hasattr(pool, "report") else {} + return {"chunk": chunk, "context": context, "step_ms": ms, + "chars_per_s": chunk / (ms * 1e-3), "peak_gb": peak, + "resident": pool.resident, "experts": pool.n_experts(), + "loads": getattr(pool, "loads", None), + "tier_hit_rate": rep.get("hit_rate")} + + +def bench_paging(dev, wdir, reps): + from minagi.paged import Tiers + import json as _j + with open(os.path.join(wdir, "manifest.json"), encoding="utf-8") as f: + man = _j.load(f) + cfg = man["cfg"] + d_model, width = cfg["d_model"], cfg["pool_d_ff"] + exp = os.path.join(wdir, "experts") + ids = sorted(int(n[1:6]) for n in os.listdir(exp) if n.endswith(".npz")) + slot = torch.zeros(width, d_model, device=dev) + out = {} + places = [("host", False)] + ([("device", True)] if dev.type == "cuda" else []) + for name, on_dev in places: + t = Tiers(exp, d_model, width, ram_capacity=0, device=dev, + read_only=True, tier_on_device=on_dev) + n = min(reps, len(ids)) + t0 = time.perf_counter() + for i in ids[:n]: + t.fetch(i) + sync(dev) + disk_ms = (time.perf_counter() - t0) * 1e3 / max(n, 1) + + def to_slot(): + for i in ids[:n]: + slot.copy_(t.fetch(i)["w1"]) + slot.copy_(t.fetch(i)["w3"]) + tier_ms = timed(to_slot, dev, 3, warm=1) / max(n, 1) + out[name] = {"disk_to_tier_ms": disk_ms, + "tier_to_slot_ms_2_of_3_tensors": tier_ms} + return out + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--device", + default="cuda" if torch.cuda.is_available() else "cpu") + ap.add_argument("--quick", action="store_true", + help="fewer repetitions and shorter windows") + ap.add_argument("--out", default=None) + ap.add_argument("--skip", default="", + help="comma list of attention,experts,step,paging") + a = ap.parse_args() + + from minagi import device as hwdev + from minagi.config import get, load, path as cfg_path + from minagi.precision import compute_dtype, set_compute_dtype + + c = load() + dev = torch.device(a.device) + set_compute_dtype(get(c, "training.precision", "bf16")) + dt = compute_dtype() if dev.type == "cuda" else torch.float32 + skip = set(s for s in a.skip.split(",") if s) + + d_model = int(get(c, "model.d_model", 512)) + H = int(get(c, "model.n_head", 8)) + width = int(get(c, "pool.width", 2048)) + resident = int(get(c, "pool.resident", 32)) + top_k = int(get(c, "pool.top_k", 8)) + cf = float(get(c, "pool.capacity_factor", 1.5) or 1.5) + chunk = int(get(c, "training.chunk", 2048)) + ctx = int(get(c, "model.context_end", 4096)) + reps = 3 if a.quick else 10 + if a.quick: + ctx = min(ctx, 4096) + + res = {"config": cfg_path(), "banner": hwdev.banner(dev), + "backend": hwdev.backend(), "arch": hwdev.arch(), + "torch": torch.__version__, "dtype": str(dt)} + print(res["banner"]) + print(f"config {cfg_path()}: d_model {d_model}, heads {H}, width {width}, " + f"resident {resident}, top_k {top_k}, chunk {chunk}, " + f"context {ctx}") + + if "attention" not in skip: + res["sdpa_kernels"] = sdpa_kernels(dev, dt, H, d_model // H) + print(f"\nSDPA kernels available: {res['sdpa_kernels']}") + lengths = sorted({min(2048, ctx), ctx} | ({2 * ctx} if not a.quick + else set())) + res["attention"] = bench_attention(dev, dt, H, d_model // H, lengths, + chunk, reps) + for r in res["attention"]: + f = (lambda v: f"{v:8.2f} ms" if isinstance(v, float) else v) + print(f" T {r['T']:>6}: causal {f(r['causal_ms'])} " + f"cached ({r['cached_queries']} queries) {f(r['cached_ms'])}") + + if "experts" not in skip: + res["experts"] = bench_experts(dev, dt, resident, d_model, width, + chunk, top_k, cf, reps) + e = res["experts"] + print(f"\nexperts: {resident} x [{e['capacity']}, {d_model}] x " + f"[{d_model}, {width}] fwd {e['fwd_ms']:.2f} ms " + f"({e['fwd_tflops']:.1f} TFLOP/s) fwd+bwd " + f"{e['fwd_bwd_ms']:.2f} ms ({e['fwd_bwd_tflops']:.1f} TFLOP/s)") + + if not ({"step", "paging"} <= skip): + from minagi.create import create + tmp = tempfile.mkdtemp(prefix="minagi-bench-") + wdir = os.path.join(tmp, "weights") + try: + create(wdir, verbose=False) + if "paging" not in skip: + res["paging"] = bench_paging(dev, wdir, 8 if a.quick else 32) + print("\npaging, per expert:") + for k, v in res["paging"].items(): + print(f" tier in {k:6}: disk -> tier " + f"{v['disk_to_tier_ms']:.1f} ms, tier -> slot " + f"{v['tier_to_slot_ms_2_of_3_tensors']:.2f} ms") + if "step" not in skip: + res["step"] = bench_step(dev, wdir, chunk, ctx, + 2 if a.quick else 5) + s = res["step"] + pk = (f", peak {s['peak_gb']:.1f} GB" + if s["peak_gb"] is not None else "") + print(f"\ntraining step: {s['chunk']} characters behind " + f"{s['context']}: {s['step_ms']:.0f} ms, " + f"{s['chars_per_s']:,.0f} char/s{pk}") + finally: + shutil.rmtree(tmp, ignore_errors=True) + + out = a.out or os.path.join(HERE, "runs", f"bench_hw-{res['arch']}.json") + os.makedirs(os.path.dirname(out), exist_ok=True) + with open(out, "w", encoding="utf-8") as f: + json.dump(res, f, indent=2) + print(f"\n-> {out}") + + +if __name__ == "__main__": + main() diff --git a/tools/plot_dashboard.py b/tools/plot_dashboard.py index ba40647..0d94105 100644 --- a/tools/plot_dashboard.py +++ b/tools/plot_dashboard.py @@ -83,7 +83,7 @@ def main(): hist = PE.history(a.history) man = {} try: - man = json.load(open(os.path.join(a.weights, "manifest.json"))) + man = json.load(open(os.path.join(a.weights, "manifest.json"), encoding="utf-8")) except OSError: pass tel = man.get("telemetry") or {} diff --git a/tools/plot_experts.py b/tools/plot_experts.py index d9614c7..40916ca 100644 --- a/tools/plot_experts.py +++ b/tools/plot_experts.py @@ -47,7 +47,7 @@ def cfg(root): "resident": 32} try: import yaml - c = yaml.safe_load(open(os.path.join(root, "config.yaml"))) + c = yaml.safe_load(open(os.path.join(root, "config.yaml"), encoding="utf-8")) out["survival_chars"] = int(str(c["prune"]["survival_chars"]).replace("_", "")) out["dying_at"] = float(c["prune"].get("dying_at", 0.75)) out["chunk"] = int(c["training"]["chunk"]) @@ -61,7 +61,7 @@ def cfg(root): def history(path): rows = [] try: - with open(path) as f: + with open(path, encoding="utf-8") as f: for line in f: try: d = json.loads(line) @@ -158,7 +158,7 @@ def main(): rows = history(a.history) try: - man = json.load(open(os.path.join(a.weights, "manifest.json"))) + man = json.load(open(os.path.join(a.weights, "manifest.json"), encoding="utf-8")) except OSError: print(f" no checkpoint at {a.weights}") return 1 diff --git a/tools/plot_progress.py b/tools/plot_progress.py index e93bb48..df515e3 100644 --- a/tools/plot_progress.py +++ b/tools/plot_progress.py @@ -31,7 +31,7 @@ import yaml _c = yaml.safe_load(open(os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), - "config.yaml"))) + "config.yaml"), encoding="utf-8")) DYING_AT = float(_c["prune"].get("dying_at", 0.75)) SURVIVAL_CHARS = int(str(_c["prune"].get("survival_chars", 0)).replace("_", "")) CHUNK = int(_c["training"].get("chunk", 1536)) @@ -73,7 +73,7 @@ def _dead_pct(r): def parse(path): - txt = open(path, errors="ignore").read() + txt = open(path, errors="ignore", encoding="utf-8").read() rows = [] for m in HEAD.finditer(txt): blk = txt[m.end():m.end() + 700] @@ -237,7 +237,7 @@ def main(): p = ax[1][1] ph = [] if os.path.exists(a.pool_log): - with open(a.pool_log) as f: + with open(a.pool_log, encoding="utf-8") as f: for line in f: if line.strip(): try: diff --git a/train.py b/train.py index b433e46..153ee87 100644 --- a/train.py +++ b/train.py @@ -37,7 +37,14 @@ # MiB free and 861 MiB reserved but unallocated. There was plenty of memory; # there was no contiguous piece of it. Set it here rather than in a shell so it # is a property of the program, not of how it happened to be launched. -os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") +# +# `--config FILE` is taken first because the hardware block of that file is +# what decides the rest of the environment - ROCm's attention kernels and +# TunableOp among it. minagi.config and minagi.device do not import torch. +from minagi.config import take_config_flag # noqa: E402 +from minagi.device import set_env_before_torch # noqa: E402 +take_config_flag() +set_env_before_torch() import numpy as np import torch @@ -49,6 +56,9 @@ from minagi.plasticity import Plasticity from minagi.optim import GradSNR from minagi import store as weights_store +# build_paged and _split_trunk_pool live in the library now; the names stay +# importable from here for the tools that reach for them as T.build_paged +from minagi.build import build_paged, _split_trunk_pool # noqa: F401 def lr_at(step, total, base, warmup, floor_frac=0.1): @@ -118,7 +128,7 @@ def cmd_stream(args): wdir = args.weights_dir man = None if os.path.exists(os.path.join(wdir, "manifest.json")): - with open(os.path.join(wdir, "manifest.json")) as f: + with open(os.path.join(wdir, "manifest.json"), encoding="utf-8") as f: man = json.load(f) cfgd = dict(man["cfg"]) if man and man.get("cfg") else {} @@ -213,7 +223,7 @@ def cmd_stream(args): # model bug and was not. Appended a line at a time, so an interrupted run # keeps everything up to the interruption. hist_path = os.path.join(args.out, "history.jsonl") - hist = open(hist_path, "a", buffering=1) + hist = open(hist_path, "a", buffering=1, encoding="utf-8") def record(kind, step=None, **kw): hist.write(json.dumps({"kind": kind, "step": step, **kw}) + "\n") @@ -319,7 +329,7 @@ def record(kind, step=None, **kw): print(f" DIVERGED: val {val:.4f} is {val/best:.1f}x the best " f"{best:.4f} - reloading weights/ and halving the " f"learning rate", flush=True) - with open(os.path.join(wdir, "manifest.json")) as _f: + with open(os.path.join(wdir, "manifest.json"), encoding="utf-8") as _f: man_b = json.load(_f) n_back = int(man_b["n_experts"]) if n_back != model.pool.n_experts(): @@ -558,7 +568,7 @@ def _truncate_history(path, chars): if not path or not os.path.exists(path) or chars <= 0: return try: - with open(path) as f: + with open(path, encoding="utf-8") as f: rows = f.read().splitlines() keep, dropped = [], 0 for line in rows: @@ -570,7 +580,7 @@ def _truncate_history(path, chars): pass # keep anything unparseable keep.append(line) if dropped: - with open(path, "w") as f: + with open(path, "w", encoding="utf-8") as f: f.write("\n".join(keep) + ("\n" if keep else "")) print(f" history: dropped {dropped} row(s) past " f"{chars/1e6:.1f}M - superseded by this resume", flush=True) @@ -618,6 +628,8 @@ def _in_steps(chars, least=1): device = torch.device(args.device) torch.manual_seed(args.seed) set_compute_dtype(args.precision) + from minagi.device import banner + print(banner(device), flush=True) files = collect(args.paths) if not files: @@ -637,7 +649,8 @@ def _in_steps(chars, least=1): # sent every new reader straight into a missing core.npz. if not os.path.exists(os.path.join(wdir, "core.npz")): from minagi.create import create - leftovers = ([f for f in os.listdir(wdir) if f != "manifest.json"] + leftovers = ([f for f in os.listdir(wdir) + if f not in ("manifest.json", ".lock")] if os.path.isdir(wdir) else []) if leftovers: # Something is in there, but not a model. Wiping it is not this @@ -656,6 +669,13 @@ def _in_steps(chars, least=1): f"config.yaml") create(wdir, force=True) print() + # One writer per directory - see minagi/lock.py. Taken even for a dry + # read: paging writes evicted experts back whether or not --save is set. + from minagi.lock import Busy, acquire + try: + acquire(wdir, "train.py read") + except Busy as e: + raise SystemExit(str(e)) model, cfg, pool, man = build_paged(wdir, device, args.resident, args.ram_capacity, args.context) # the best held-out this run has seen, for the optional notifier below. @@ -748,15 +768,9 @@ def _in_steps(chars, least=1): n_off += 1 print(f" pool activations kept, not recomputed ({n_off} call sites) " f"- faster, and it needs the memory depth was using") - trunk, pool_ps = _split_trunk_pool(model) - - tg = {"params": trunk, "name": "trunk", "weight_decay": args.wd, - "lr": args.lr * args.trunk_lr_mult, - "base_lr": args.lr * args.trunk_lr_mult} - pg = {"params": pool_ps, "name": "pool", "weight_decay": args.wd, - "lr": args.lr, "base_lr": args.lr} - opt = torch.optim.AdamW([tg, pg], lr=args.lr, betas=(0.9, 0.95), - fused=(device.type == "cuda")) + from minagi.build import build_adamw + opt, trunk, pool_ps = build_adamw(model, args.lr, args.trunk_lr_mult, + args.wd) snr = GradSNR() print(f" trunk learns at {args.trunk_lr_mult:g}x the pool's rate " f"({sum(q.numel() for q in trunk)/1e6:.1f}M trunk, " @@ -855,7 +869,7 @@ def _in_steps(chars, least=1): # Append. A resumed run continues the same model, so wiping the file # would throw away the only record of how it got here; the banner is # what separates one session from the next. - with open(args.sample_log, "a") as f: + with open(args.sample_log, "a", encoding="utf-8") as f: f.write(f"\n\n{'#' * 78}\n") f.write(f"# session started {time.strftime('%Y-%m-%d %H:%M')} " f"at step {step:,}, {base_chars/1e6:.1f}M of " @@ -929,6 +943,12 @@ def context_gain(): # One lane per subject, rotated a window at a time. lanes = _lanes(files, args.shuffle_seed, args.paths, resume=int(man.get("read_chars", 0) or 0)) + # torch's generator gets the same treatment as the lanes', for the same + # reason: seeded with --seed alone, every session replayed one random + # sequence - the same sampled depths, the same recombination draws at + # each growth, the same drawn selections - from wherever it resumed. + torch.manual_seed(hash((int(args.seed), + int(man.get("read_chars", 0) or 0))) & (2**63 - 1)) # How long a subject is read for before the next one. It is a whole # number of context windows - a window never spans two subjects, because # attention across the seam where chess becomes Python teaches nothing - @@ -991,7 +1011,7 @@ def log_history(val=None): "last_seen": t.get("last_seen"), "uid": t.get("uid"), "trial": getattr(model.pool, "trial", 0)} os.makedirs(os.path.dirname(args.history) or ".", exist_ok=True) - with open(args.history, "a") as f: + with open(args.history, "a", encoding="utf-8") as f: f.write(json.dumps(row, separators=(",", ":")) + "\n") except Exception as e: # telemetry must never stop a run print(f" (history not written: {e})", flush=True) @@ -1304,9 +1324,9 @@ def _on_int(sig, frm): print(f" pool {pool.n_experts()} experts " f"({'+%d' % rec['grew'] if rec['grew'] else ''}" f"{'-%d' % gone if gone else ''}) " - f"{pool.vram_params()/1e6:.1f}M in VRAM " - f"vram {torch.cuda.max_memory_allocated()/1e6:.0f}MB" - if device.type == "cuda" else "", flush=True) + f"{pool.vram_params()/1e6:.1f}M in VRAM" + + (f" vram {torch.cuda.max_memory_allocated()/1e6:.0f}MB" + if device.type == "cuda" else ""), flush=True) if asked_stop or (args.minutes and (time.time() - t0) / 60 >= args.minutes): break @@ -1656,13 +1676,19 @@ def refresh_plots(): if _PLOTS["since"] is not None: c += ["--last", str(_PLOTS["since"])] cmds.append(c) + # One background python that runs them in order and stops at the first + # failure - what `bash -c "a && b"` did, without needing bash, which a + # Windows machine does not have. + chain = ("import json, subprocess, sys\n" + "for c in json.loads(sys.argv[1]):\n" + " if subprocess.run(c).returncode:\n" + " sys.exit(1)\n") try: - script = " && ".join(" ".join(f'"{x}"' for x in c) for c in cmds) _PLOTS["proc"] = subprocess.Popen( - ["bash", "-c", script], cwd=here, + [sys.executable, "-c", chain, json.dumps(cmds)], cwd=here, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except OSError: - _PLOTS["on"] = False # no python, no bash - stop trying + _PLOTS["on"] = False # no python to run them - stop trying def write_samples(path, step, chars, minutes, samples, val=None, se=None, @@ -1670,7 +1696,7 @@ def write_samples(path, step, chars, minutes, samples, val=None, se=None, corpus=None, context=None, ceiling=None, gain=None, rate=None, gnorm=None, clip=None, plast=None, write_rate=None): - with open(path, "a") as f: + with open(path, "a", encoding="utf-8") as f: f.write(f"\n{'=' * 78}\n") # How much has been read, against how much there is. A bare count of # characters read says nothing on its own - the same 4M is most of a @@ -1790,138 +1816,6 @@ def write_samples(path, step, chars, minutes, samples, val=None, se=None, refresh_plots() return path -def _split_trunk_pool(model): - """ - Which parameters are the pool's, and which are the shared body. - - A resident pool keeps its experts as modules; a paged pool keeps three - stacked slot tensors instead, so the set has to be found by asking the - pool rather than by walking a ModuleList that is not there. - """ - p = model.pool - ids = {id(p.gate)} - if hasattr(p, "experts") and p.experts is not None: - ids |= {id(q) for e in p.experts for q in e.parameters()} - for nm in ("w1", "w3", "w2"): - obj = getattr(p, nm, None) - if obj is None: - continue - ids |= ({id(obj)} if torch.is_tensor(obj) - else {id(q) for q in obj.parameters()}) - for s in model.modules(): - if isinstance(s, PooledMLP): - ids.add(id(s.router.weight)) - ids.add(id(s.depth_emb)) - trunk = [q for q in model.parameters() if id(q) not in ids] - pool = [q for q in model.parameters() if id(q) in ids] - return trunk, pool - - -def build_paged(wdir, device, resident=None, ram_capacity=256, ceiling=None, - read_only=False): - """ - Load the model with its pool on disk rather than in VRAM. - - The three tiers the project describes: every expert is a file, RAM keeps - the recently wanted ones, and the card holds the experts the current - forward admitted. While a forward has room on the card, every character ranks the - whole pool; a forward may use at most `resident` experts, the ones its - characters ask for most - see PagedPool.admit. - - read_only makes the pool incapable of writing to `wdir`. Pass it from any - tool that inspects a directory a training run may own - paging an expert in - marks it dirty whether or not anything touched it, so a plain read would - otherwise write expert files back under the run. - """ - from minagi.paged import PagedPool - with open(os.path.join(wdir, "manifest.json")) as f: - man = json.load(f) - cfgd = dict(man["cfg"]) - resident = resident or cfgd.get("pool_resident") or cfgd["pool_top_k"] - cfg = RecurConfig(**{k: v for k, v in cfgd.items() - if k in RecurConfig.__dataclass_fields__}) - # The capacity bound comes from config.yaml rather than from the - # checkpoint, because it is a property of the machine the model is running - # on - how much VRAM the dispatch may use - not of the model. A directory - # written before this existed carries no value for it and would otherwise - # get the dataclass default, which is right but silent; taking it from the - # config every load means the number in the file is the number in effect. - try: - from minagi.config import load as _load_cfg, get as _get_cfg - _c = _load_cfg() - cfg.pool_capacity_factor = float( - _get_cfg(_c, "pool.capacity_factor", cfg.pool_capacity_factor)) - except Exception: - pass - # the per-token router keeps one row per EXPERT, not per VRAM slot, so it - # is sized by the pool and grows with it - see PooledMLP.__init__ - # EXACTLY what the pool holds. pool_max sizes the routers, which keep one - # row per expert, so a checkpoint's router weights only fit a model built - # at the same count - one row too many and load_state_dict refuses the - # whole model. - # - # It was briefly max(cfg.pool_max, n_experts) to stop `stream` latching - # its growth ceiling to the pool's current size. That conflated two jobs - # in one number: sizing the routers, and capping growth. The manifest's - # pool_max ratchets up and never comes down, so after a prune took the - # pool from 158 to 157 the max() still read 158 and the directory would - # not load at all. The ceiling now lives in `stream` where it belongs. - cfg.pool_max = int(man["n_experts"]) - if ceiling and ceiling > cfg.block: - # RoPE tables are built to cfg.block and carry no learned parameters, - # so raising the ceiling on an existing model costs a bigger table and - # nothing else. The window the reader actually uses is separate, and - # grows a character at a time. - cfg.block = int(ceiling) - model = RecurCoder(cfg).to(device) - pool = PagedPool(os.path.join(wdir, "experts"), cfg.d_model, cfg.pool_d_ff, - int(man["n_experts"]), resident=resident, - ram_capacity=ram_capacity, device=device, - read_only=read_only).to(device) - for m in model.modules(): - if isinstance(m, PooledMLP): - m._pool[0] = pool - model.pool = pool - pool.attach_sites(model) - pool.load_telemetry(man.get("telemetry")) - # The balance term's weight and the temperature of expert selection - see - # PagedPool.note_balance and PagedPool._draw. Read from config.yaml at - # every load, like the capacity bound: they are choices about how the model - # trains and chooses, not properties of its weights. - try: - from minagi.config import load as _load_cfg, get as _get_cfg - _c = _load_cfg() - pool.balance = float(_get_cfg(_c, "pool.balance", 0.0) or 0.0) - pool.select_temperature = float( - _get_cfg(_c, "pool.select_temperature", 0.0) or 0.0) - except Exception: - pass - ever = cfgd.get("pool_ever") - if ever: - n = min(len(ever), pool.ever.numel()) - pool.ever[:n] = torch.tensor(ever[:n], dtype=torch.bool, - device=pool.ever.device) - # the trunk still comes from the bundles; the experts come from their files - core = np.load(os.path.join(wdir, "core.npz")) - rout = np.load(os.path.join(wdir, "routers.npz")) - sd = {k: torch.from_numpy(core[k]) for k in core.files} - # Router rows belong to EXPERTS, not to VRAM slots, so they are loaded - # whole. Slicing them to the resident count - which this did, left over - # from when rows were slots - silently discarded every expert past the - # card and made any resume after growth fail to load. - for k in rout.files: - # The segment router chose working sets before selection moved into - # the router itself; directories written then still carry its rows. - if k.startswith("pool.segment_router."): - continue - sd[k] = torch.from_numpy(rout[k]) - missing, unexpected = model.load_state_dict(sd, strict=False) - bad = [k for k in unexpected if "router" in k or "gate" in k] - if bad: - raise RuntimeError(f"router/gate tensors did not load: {bad}") - return model, cfg, pool, man - - def cmd_ponder_probe(args): """ Does the model actually spend more computation on harder problems?